├── README.md
├── Sources
├── CSharpIDW
│ ├── CSharpIDW.csproj
│ ├── InterpolationResult.cs
│ ├── Point.cs
│ ├── CSharpIDW.nuspec
│ └── IdwInterpolator.cs
├── CSharpIDW.Test
│ ├── CSharpIDW.Test.csproj
│ └── IdwInterpolatorTests.cs
└── CSharpIDW.sln
├── LICENSE
└── .gitignore
/README.md:
--------------------------------------------------------------------------------
1 | [](https://ci.appveyor.com/project/argonavis80/csharp-idw)
2 |
3 | # CSharp-IDW
4 | C# library for fast multi-dimensional inverse distance weighting (IDW) interpolation.
5 |
--------------------------------------------------------------------------------
/Sources/CSharpIDW/CSharpIDW.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Sources/CSharpIDW/InterpolationResult.cs:
--------------------------------------------------------------------------------
1 | namespace CSharpIDW
2 | {
3 | public class InterpolationResult
4 | {
5 | public enum ResultOptions
6 | {
7 | Hit,
8 | NearestNeighbor,
9 | Interpolated,
10 | Extrapolated,
11 | OutOfBounds
12 | }
13 |
14 | public ResultOptions Result { get; set; }
15 |
16 | public double Value { get; set; }
17 |
18 | public Point? Point { get; set; }
19 | }
20 | }
--------------------------------------------------------------------------------
/Sources/CSharpIDW/Point.cs:
--------------------------------------------------------------------------------
1 | using System.Globalization;
2 | using System.Linq;
3 |
4 | namespace CSharpIDW
5 | {
6 | public struct Point
7 | {
8 | public double Value { get; }
9 |
10 | public double[] Coordinates { get; }
11 |
12 | public Point(double value, params double[] coordinates)
13 | {
14 | Value = value;
15 | Coordinates = coordinates;
16 | }
17 |
18 | public override string ToString()
19 | {
20 | return $"{string.Join(";", Coordinates)} -> {Value}";
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/Sources/CSharpIDW.Test/CSharpIDW.Test.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 |
7 |
8 |
9 |
10 |
11 | all
12 | runtime; build; native; contentfiles; analyzers; buildtransitive
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Sources/CSharpIDW/CSharpIDW.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $id$
5 | $version$
6 | $title$
7 | $author$
8 | $author$
9 | https://github.com/argonavis80/CSharp-IDW/blob/master/LICENSE
10 | https://github.com/argonavis80/CSharp-IDW
11 |
12 | false
13 | $description$
14 |
15 | Copyright 2016
16 | Interpolation IDW Scatter
17 |
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 Henrik Alfke
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
24 |
25 | Credits
26 | ---------------------------
27 | This application uses Open Source components. You can find the source code of
28 | their open source projects along with license information below. We acknowledge
29 | and are grateful to these developers for their contributions to open source.
30 |
31 | Project: KdTree
32 | Copyright (c) 2013 codeandcats
33 | License (MIT): https://github.com/codeandcats/KdTree/blob/master/LICENSE
--------------------------------------------------------------------------------
/Sources/CSharpIDW.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30711.63
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{95954717-385E-4527-80BF-6E376ACD36F0}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpIDW", "CSharpIDW\CSharpIDW.csproj", "{8789D37F-0F8E-4E89-BF29-4F14B9FF6FF0}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpIDW.Test", "CSharpIDW.Test\CSharpIDW.Test.csproj", "{97727039-E72C-45A8-9AF5-5873F687A7FF}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {8789D37F-0F8E-4E89-BF29-4F14B9FF6FF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {8789D37F-0F8E-4E89-BF29-4F14B9FF6FF0}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {8789D37F-0F8E-4E89-BF29-4F14B9FF6FF0}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {8789D37F-0F8E-4E89-BF29-4F14B9FF6FF0}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {97727039-E72C-45A8-9AF5-5873F687A7FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {97727039-E72C-45A8-9AF5-5873F687A7FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {97727039-E72C-45A8-9AF5-5873F687A7FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {97727039-E72C-45A8-9AF5-5873F687A7FF}.Release|Any CPU.Build.0 = Release|Any CPU
26 | EndGlobalSection
27 | GlobalSection(SolutionProperties) = preSolution
28 | HideSolutionNode = FALSE
29 | EndGlobalSection
30 | GlobalSection(NestedProjects) = preSolution
31 | {97727039-E72C-45A8-9AF5-5873F687A7FF} = {95954717-385E-4527-80BF-6E376ACD36F0}
32 | EndGlobalSection
33 | GlobalSection(ExtensibilityGlobals) = postSolution
34 | SolutionGuid = {6A509FB9-7625-4283-9E2F-AAA18AC56F8C}
35 | EndGlobalSection
36 | EndGlobal
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
--------------------------------------------------------------------------------
/Sources/CSharpIDW.Test/IdwInterpolatorTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics.CodeAnalysis;
4 | using System.Linq;
5 | using Xunit;
6 | // ReSharper disable ArgumentsStyleLiteral
7 | // ReSharper disable PossibleInvalidOperationException
8 |
9 | namespace CSharpIDW.Test
10 | {
11 | [ExcludeFromCodeCoverage]
12 | public class IdwInterpolatorTests
13 | {
14 | private List _pointRange;
15 |
16 | public IdwInterpolatorTests()
17 | {
18 | _pointRange = new List
19 | {
20 | new Point(1.0, 0, 0),
21 | new Point(1.1, 0, 1),
22 | new Point(1.2, 0, 2),
23 | new Point(2.0, 1, 0),
24 | new Point(2.2, 1, 1),
25 | new Point(2.4, 1, 2),
26 | new Point(3.0, 2, 0),
27 | new Point(3.3, 2, 1),
28 | new Point(3.6, 2, 2),
29 | };
30 | }
31 |
32 | [Fact]
33 | public void FailDimensionOutOfRange()
34 | {
35 | // ReSharper disable once UnusedVariable
36 | Assert.Throws(() => new IdwInterpolator(dimensions: 0));
37 | }
38 |
39 | [Fact]
40 | public void FailPowerOutOfRange()
41 | {
42 | // ReSharper disable once UnusedVariable
43 | Assert.Throws(() => new IdwInterpolator(dimensions: 2, power: 0));
44 | }
45 |
46 | [Fact]
47 | public void FailNumberOfNeighboursOutOfRange()
48 | {
49 | // ReSharper disable once UnusedVariable
50 | Assert.Throws(() => new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 0));
51 | }
52 |
53 | [Fact]
54 | public void FailWithTooFewPoints()
55 | {
56 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
57 |
58 | target.AddPointRange(_pointRange.Take(4).ToList()); // Not enough points.
59 |
60 | Assert.Throws(() => target.Interpolate(1, 1));
61 | }
62 |
63 | [Fact]
64 | public void FailWithNullPointRange()
65 | {
66 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
67 |
68 | Assert.Throws(() => target.AddPointRange(null));
69 | }
70 |
71 | [Fact]
72 | public void FailWithPointWithWrongDimension()
73 | {
74 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
75 |
76 | Assert.Throws(() => target.AddPoint(new Point(1, 1, 1, 1))); // One dimension too much.
77 | }
78 |
79 | [Fact]
80 | public void FailWithPointAndMissingCoordinates()
81 | {
82 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
83 |
84 | Assert.Throws(() => target.AddPoint(1, null)); // Coordinates missing.
85 | }
86 |
87 | [Fact]
88 | public void FailWithPointAndCoordinatesWithWrongDimension()
89 | {
90 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
91 |
92 | Assert.Throws(() => target.AddPoint(1, 1, 1, 1)); // One dimension too much.
93 | }
94 |
95 | [Fact]
96 | public void FailWithPointRangeWithWrongDimension()
97 | {
98 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
99 |
100 | var pointRange = new List
101 | {
102 | new Point(1.0, 0, 0),
103 | new Point(1.1, 0, 1),
104 | new Point(1.2, 0, 2),
105 | new Point(2.0, 1, 0),
106 | new Point(2.2, 1, 1),
107 | new Point(2.4, 1) // Dimension wrong.
108 | };
109 |
110 | Assert.Throws(() => target.AddPointRange(pointRange));
111 | }
112 |
113 | [Fact]
114 | public void FailInterpolateWithWrongDimension()
115 | {
116 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 5);
117 |
118 | target.AddPointRange(_pointRange);
119 |
120 | Assert.Throws(() => target.Interpolate(1, 1, 1)); // One dimension to much.
121 | }
122 |
123 | [Fact]
124 | public void TestInterpolateWithPointHit()
125 | {
126 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 4);
127 |
128 | target.AddPointRange(_pointRange); // Test adding point range.
129 |
130 | var result = target.Interpolate(1, 1);
131 |
132 | Assert.Equal(2.2, result.Value);
133 | Assert.Equal(1, result.Point.Value.Coordinates[0]);
134 | Assert.Equal(1, result.Point.Value.Coordinates[1]);
135 | Assert.Equal(InterpolationResult.ResultOptions.Hit, result.Result);
136 | }
137 |
138 | [Fact]
139 | public void TestNearestNeighbourInterpolation()
140 | {
141 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 1);
142 |
143 | foreach (var point in _pointRange)
144 | {
145 | target.AddPoint(point); // Test adding points.
146 | }
147 |
148 | var result = target.Interpolate(1.1, 1.1);
149 |
150 | Assert.Equal(2.2, result.Value);
151 | Assert.Equal(1, result.Point.Value.Coordinates[0]);
152 | Assert.Equal(1, result.Point.Value.Coordinates[1]);
153 | Assert.Equal(InterpolationResult.ResultOptions.NearestNeighbor, result.Result);
154 | }
155 |
156 |
157 |
158 | [Fact]
159 | public void TestWeightedInterpolation()
160 | {
161 | var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 4);
162 |
163 | foreach (var point in _pointRange)
164 | {
165 | target.AddPoint(point.Value, point.Coordinates); // Test adding bare values.
166 | }
167 |
168 | var result = target.Interpolate(1.5, 1.5);
169 |
170 | Assert.Equal(2.875, result.Value, 3);
171 | Assert.Equal(InterpolationResult.ResultOptions.Interpolated, result.Result);
172 | Assert.Null(result.Point);
173 | }
174 |
175 | //[Fact]
176 | //public void TestWeightedExtrapolation()
177 | //{
178 | // // TODO: Currently failing, because convex hull not yet checked.
179 |
180 | // var target = new IdwInterpolator(dimensions: 2, power: 2, numberOfNeighbours: 4);
181 |
182 | // target.AddPointRange(_pointRange);
183 |
184 | // var result = target.Interpolate(2.1, 2.1);
185 |
186 | // Assert.AreEqual(2.2, result.Value);
187 | // Assert.AreEqual(InterpolationResult.ResultOptions.Extrapolated, result.Result);
188 | // Assert.IsNull(result.Point);
189 | //}
190 | }
191 | }
192 |
--------------------------------------------------------------------------------
/Sources/CSharpIDW/IdwInterpolator.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using KdTree;
5 | using KdTree.Math;
6 | // ReSharper disable SuggestBaseTypeForParameter
7 |
8 | namespace CSharpIDW
9 | {
10 | ///
11 | /// Inverse Distance Weighting (IDW) interpolator.
12 | ///
13 | ///
14 | /// The interpolator implements the modified Shepard's method, with only nearest neighbours.
15 | /// https://en.wikipedia.org/wiki/Inverse_distance_weighting
16 | ///
17 | public class IdwInterpolator
18 | {
19 | private readonly int _dimensions;
20 |
21 | private const double DefaultPower = 2;
22 | private const int DefaultNumberOfNeighbours = 5;
23 |
24 | private readonly KdTree _tree;
25 |
26 | private double Power { get; }
27 |
28 | private int NumberOfNeighbours { get; }
29 |
30 | public IdwInterpolator(int dimensions) : this(dimensions, DefaultPower)
31 | {
32 | }
33 |
34 | public IdwInterpolator(int dimensions, double power) : this(dimensions, power, DefaultNumberOfNeighbours)
35 | {
36 | }
37 |
38 | public IdwInterpolator(int dimensions, double power, int numberOfNeighbours)
39 | {
40 | if (dimensions < 1)
41 | throw new ArgumentOutOfRangeException(nameof(dimensions), dimensions,
42 | $"Parameter '{nameof(dimensions)}' must be a positive integer.");
43 |
44 | if (power <= 0)
45 | throw new ArgumentOutOfRangeException(nameof(power), power,
46 | $"Parameter '{nameof(power)}' must be a positive real value.");
47 |
48 | if (numberOfNeighbours < 1)
49 | throw new ArgumentOutOfRangeException(nameof(numberOfNeighbours), numberOfNeighbours,
50 | $"Parameter '{nameof(numberOfNeighbours)}' must be a positive integer.");
51 |
52 | _dimensions = dimensions;
53 |
54 | Power = power;
55 | NumberOfNeighbours = numberOfNeighbours;
56 |
57 | _tree = new KdTree(dimensions, new DoubleMath());
58 | }
59 |
60 | public void AddPoint(double value, params double[] coordinates)
61 | {
62 | if (coordinates == null)
63 | throw new ArgumentNullException(nameof(coordinates));
64 |
65 | if (coordinates.Length != _dimensions)
66 | throw new ArgumentException(nameof(coordinates),
67 | $"Size of {nameof(coordinates)} must match the dimension of the interpolator.");
68 |
69 | var point = new Point(value, coordinates);
70 |
71 | _tree.Add(coordinates, point);
72 | }
73 |
74 | public void AddPoint(Point point)
75 | {
76 | if (point.Coordinates.Length != _dimensions)
77 | throw new ArgumentException(nameof(point.Coordinates),
78 | $"Size of {nameof(point.Coordinates)} must match the dimension of the interpolator.");
79 |
80 | _tree.Add(point.Coordinates, point);
81 | }
82 |
83 | public void AddPointRange(IEnumerable points)
84 | {
85 | if (points == null)
86 | throw new ArgumentNullException(nameof(points));
87 |
88 | foreach (var point in points)
89 | {
90 | if (point.Coordinates.Length != _dimensions)
91 | {
92 | _tree.Clear();
93 |
94 | throw new ArgumentException(nameof(points),
95 | $"Size of coordinates of all items in {nameof(points)} must match the dimension of the interpolator.");
96 | }
97 |
98 | _tree.Add(point.Coordinates, point);
99 | }
100 | }
101 |
102 | public InterpolationResult Interpolate(params double[] coordinates)
103 | {
104 | if (coordinates.Length != _dimensions)
105 | throw new ArgumentException(nameof(coordinates),
106 | $"Size of {nameof(coordinates)} must match the dimension of the interpolator.");
107 |
108 | if (_tree.Count < NumberOfNeighbours)
109 | {
110 | throw new IndexOutOfRangeException(
111 | $"The number of found points ({_tree.Count}) is less than " +
112 | $"the number of required neighbours ({NumberOfNeighbours}). Consider reducing " +
113 | $"the required number of Neighbours with '{nameof(NumberOfNeighbours)}' property.");
114 | }
115 |
116 | Point point;
117 |
118 | if (_tree.TryFindValueAt(coordinates, out point))
119 | {
120 | return new InterpolationResult
121 | {
122 | Point = point,
123 | Value = point.Value,
124 | Result = InterpolationResult.ResultOptions.Hit
125 | };
126 | }
127 |
128 | var neighbours = _tree.GetNearestNeighbours(coordinates, NumberOfNeighbours);
129 |
130 | if (neighbours.Length == 1)
131 | {
132 | point = neighbours[0].Value;
133 |
134 | return new InterpolationResult
135 | {
136 | Point = point,
137 | Value = point.Value,
138 | Result = InterpolationResult.ResultOptions.NearestNeighbor
139 | };
140 | }
141 |
142 | var value = CalculateWeightedAverage(neighbours.Select(n => n.Value), coordinates);
143 |
144 | var result = new InterpolationResult
145 | {
146 | Value = value,
147 | Result = InterpolationResult.ResultOptions.Interpolated
148 | };
149 |
150 | if (false) // TODO: Check convex hull here.
151 | {
152 | result.Result = InterpolationResult.ResultOptions.Extrapolated;
153 | }
154 |
155 | return result;
156 | }
157 |
158 | private double CalculateWeightedAverage(IEnumerable points, double[] target)
159 | {
160 | var nominator = 0.0;
161 | var denominator = 0.0;
162 |
163 | foreach (var point in points)
164 | {
165 | var distance = CalculateDistance(point.Coordinates, target);
166 | var weight = 1/Math.Pow(distance, Power);
167 |
168 | nominator += weight*point.Value;
169 | denominator += weight;
170 | }
171 |
172 | var result = nominator/denominator;
173 |
174 | return result;
175 | }
176 |
177 | private static double CalculateDistance(double[] pointA, double[] pointB)
178 | {
179 | var sum = 0.0;
180 |
181 | for (var i = 0; i < pointA.Length; i++)
182 | {
183 | var p = pointA[i];
184 | var q = pointB[i];
185 |
186 | sum += Math.Pow(p - q, 2);
187 | }
188 |
189 | var result = Math.Sqrt(sum);
190 |
191 | return result;
192 | }
193 | }
194 | }
195 |
--------------------------------------------------------------------------------