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94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = np.array([[1,2,3],[4,5,6]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3],\n",
       "       [4, 5, 6]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "b = np.array([[2,3,4],[5,6,9]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[2, 3, 4],\n",
       "       [5, 6, 9]])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3],\n",
       "       [4, 5, 6]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-1, -1, -1],\n",
       "       [-1, -1, -3]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a - b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.7320508075688772"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.argmin([np.linalg.norm(a[i] - b[i]) for i in range(len(a))])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "np.min?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "\"\"\"\n",
    "This is a module for IDW Spatial Interpolation\n",
    "\"\"\"\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from copy import deepcopy\n",
    "class idw():\n",
    "    \"\"\" A class that is declared for performing IDW Interpolation.\n",
    "    For more information on how this method works, kindly refer to\n",
    "    https://en.wikipedia.org/wiki/Inverse_distance_weighting\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    exponent : positive float, optional\n",
    "        The rate of fall of values from source data points.\n",
    "        Higher the exponent, lower is the value when we move\n",
    "        across space. Default value is 2.\n",
    "    resolution: str, optional\n",
    "        Decides the smoothness of the interpolation. Note that\n",
    "        interpolation is done over a grid. Higher the resolution\n",
    "        means more grid cells and more time for interpolation.\n",
    "        Default value is 'standard'\n",
    "    coordinate_type: str, optional\n",
    "        Decides the distance metric to be used, while performing\n",
    "        interpolation. Euclidean by default.     \n",
    "    \"\"\"\n",
    "    def __init__(self, exponent = 2, resolution = 'standard', coordinate_type='Euclidean'):\n",
    "        \n",
    "        self.exponent = exponent\n",
    "        self.resolution = resolution\n",
    "        self.coordinate_type = coordinate_type\n",
    "        self.interpolated_values = None\n",
    "        self.x_grid = None\n",
    "        self.y_grid = None\n",
    "\n",
    "    def make_grid(self, x, y, res, offset=0.2):\n",
    "\n",
    "        \"\"\" This function returns the grid to perform interpolation on.\n",
    "           This function is used inside the fit() attribute of the idw class.\n",
    "        \n",
    "        Parameters\n",
    "        ----------\n",
    "        x: array-like, shape(n_samples,)\n",
    "            The first coordinate values of all points where\n",
    "            ground truth is available\n",
    "        y: array-like, shape(n_samples,)\n",
    "            The second coordinate values of all points where\n",
    "            ground truth is available\n",
    "        res: int\n",
    "            The resolution value\n",
    "        offset: float, optional\n",
    "            A value between 0 and 0.5 that specifies the extra interpolation to be done\n",
    "            Default is 0.2\n",
    "        \n",
    "        Returns\n",
    "        -------\n",
    "        xx : {array-like, 2D}, shape (n_samples, n_samples)\n",
    "        yy : {array-like, 2D}, shape (n_samples, n_samples)\n",
    "        \"\"\"\n",
    "        y_min = y.min() - offset\n",
    "        y_max = y.max()+ offset\n",
    "        x_min = x.min()-offset\n",
    "        x_max = x.max()+offset\n",
    "        x_arr = np.linspace(x_min,x_max,res)\n",
    "        y_arr = np.linspace(y_min,y_max,res)\n",
    "        xx,yy = np.meshgrid(x_arr,y_arr)  \n",
    "        return xx,yy\n",
    "\n",
    "    \n",
    "    def fit(self, X, y):\n",
    "        \"\"\" The function call to fit the model on the given data. \n",
    "        Parameters\n",
    "        ----------\n",
    "        X: {array-like, 2D matrix}, shape(n_samples, 2)\n",
    "            The set of all coordinates, where we have ground truth\n",
    "            values\n",
    "        y: array-like, shape(n_samples,)\n",
    "            The set of all the ground truth values using which\n",
    "            we perform interpolation\n",
    "\n",
    "        Returns\n",
    "        -------\n",
    "        self : object\n",
    "            Returns self\n",
    "        \"\"\"\n",
    "\n",
    "#          if self.coordinate_type == 'latlong_small':\n",
    "# \t \t\"\"\"\n",
    "# \t \t\tUse the conversions and projections for small changes in LatLong\n",
    "#  \t\t\"\"\"\n",
    "# \t \t    print (\"To be done later\")\n",
    "#             return self\n",
    "\n",
    "#         if self.coordinate_type == 'latlong_large':\n",
    "#             \"\"\"\n",
    "#                 Code to be written after understanding all the projections.\n",
    "#             \"\"\"\n",
    "#             print (\"To be done later\")\n",
    "#             return self\n",
    "\n",
    "        if self.coordinate_type==\"Euclidean\":\n",
    "            \n",
    "            X = deepcopy(np.c_[X,y])\n",
    "\n",
    "            if self.resolution=='high':\n",
    "                xx,yy = self.make_grid(X,y,1000)\n",
    "                \n",
    "            if self.resolution=='low':\n",
    "                xx,yy = self.make_grid(X,y,10)\n",
    "                \n",
    "            if self.resolution=='standard':\n",
    "                xx,yy = self.make_grid(X,y,100)\n",
    "\n",
    "            new = []\n",
    "            new_arr = deepcopy(X)\n",
    "            for points in new_arr:\n",
    "                min_dist = np.inf\n",
    "                val = 0\n",
    "                for j in range(len(yy)):\n",
    "                    temp = yy[j][0]\n",
    "                    for i in range(len(xx[0])):\n",
    "                        dist = np.linalg.norm(np.array([xx[0][i],temp]) - points[:2])\n",
    "                        if dist<min_dist:\n",
    "                            min_dist = dist\n",
    "                            val = (i,j)\n",
    "                new.append((points,val))\n",
    "            new_grid = np.zeros((len(xx),len(yy)))\n",
    "            for i in range(len(new)):\n",
    "                x = new[i][1][0]\n",
    "                y = new[i][1][1]\n",
    "                new_grid[x][y] = new[i][0][2]\n",
    "            x_nz,y_nz = np.nonzero(new_grid)\n",
    "            list_nz = []\n",
    "            for i in range(len(x_nz)):\n",
    "                list_nz.append((x_nz[i],y_nz[i]))\n",
    "            final = np.copy(new_grid)\n",
    "            for i in range(len(xx[0])):\n",
    "                for j in range(len(yy)):\n",
    "                    normalise = 0\n",
    "                    if (i,j) in list_nz:\n",
    "                        continue\n",
    "                    else:\n",
    "                        for elem in range(len(x_nz)):\n",
    "                            source = np.array([x_nz[elem],y_nz[elem]])\n",
    "                            target = np.array([xx[0][i],yy[j][0]])\n",
    "                            dist = (np.abs(xx[0][source[0]] - target[0])**self.exponent + np.abs(yy[source[1]][0] - target[1])**self.exponent)**(1/self.exponent)\n",
    "                            final[i][j]+=new_grid[x_nz[elem],y_nz[elem]]/dist\n",
    "                            normalise+=1/(dist)\n",
    "                    final[i][j]/=normalise\n",
    "            self.interpolated_values = final\n",
    "            self.x_grid = xx\n",
    "            self.y_grid = yy\n",
    "        \n",
    "        return self\n",
    "\n",
    "#     def predict(self, X):\n",
    "#         \"\"\" The function call to predict using the interpolated data\n",
    "#         Parameters\n",
    "#         ----------\n",
    "#         X: {array-like, 2D matrix}, shape(n_samples, 2)\n",
    "#             The set of all coordinates, where we have ground truth\n",
    "#             values\n",
    "        \n",
    "\n",
    "#         Returns\n",
    "#         -------\n",
    "#         y: array-like, shape(n_samples,)\n",
    "#             The set of all the ground truth values using which\n",
    "#             we perform interpolation \n",
    "#         \"\"\"\n",
    "#         if self.coordinate_type == 'Euclidean':\n",
    "#             for i in range(self.x_grid[0]):\n",
    "#                 for j in range()\n",
    "        \n",
    "#         else:\n",
    "#             print(\"Will be done later\")\n",
    "#             return \n",
    "            \n",
    "                \n",
    "# self.x_grid\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<__main__.idw at 0x7f36db6f9c88>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = idw()\n",
    "import pandas as pd\n",
    "df = pd.read_csv('../../testdata/30-03-18.csv')\n",
    "data = np.array(df[['longitude','latitude','value']])\n",
    "a.fit(data[:,:2],data[:,2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[171.89189189, 171.89597641, 171.90813547, ..., 173.89050472,\n",
       "        173.89261459, 173.89466512],\n",
       "       [171.77142857, 171.77625338, 171.79060316, ..., 173.89585441,\n",
       "        173.89787202, 173.89983245],\n",
       "       [171.63636364, 171.64211895, 171.65921778, ..., 173.9012935 ,\n",
       "        173.90321551, 173.90508269],\n",
       "       ...,\n",
       "       [174.49681529, 174.49676176, 174.49660126, ..., 174.24671184,\n",
       "        174.24416446, 174.24164382],\n",
       "       [174.49056604, 174.49051451, 174.49035999, ..., 174.24671343,\n",
       "        174.24419773, 174.2417078 ],\n",
       "       [174.48447205, 174.48442242, 174.48427358, ..., 174.2466762 ,\n",
       "        174.24419219, 174.24173298]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.interpolated_values"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}