Skip to content
This repository has been archived by the owner on Nov 28, 2023. It is now read-only.

Commit

Permalink
DAY 11
Browse files Browse the repository at this point in the history
Generated multiple images to be used in the report. Cleaned the code for 1D and 2D.

TODO: Write the Report
TODO: Generate difference images for some tiles.
  • Loading branch information
milosmicik committed Jun 13, 2022
1 parent 5361869 commit c6596bc
Show file tree
Hide file tree
Showing 50 changed files with 701 additions and 321 deletions.
5 changes: 2 additions & 3 deletions FictionalData.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from mayavi import mlab

import helpers.save_figure_position
from functions_2D import interpolate_low_output_resolution, plot_contours
from functions_2D import interpolate_discretized_data, plot_contours

datagrid = np.load("data/FictionalData.npy", allow_pickle=False)
maximum = np.max(datagrid)
Expand All @@ -30,11 +30,10 @@
#
#

interpolated_image = interpolate_low_output_resolution(
interpolated_image = interpolate_discretized_data(
x,
y,
datagrid - 1,
use_clip_to_data=False,
allow_hybrid_interpolation=True,
)
sea_fix = lambda x: np.where(np.all([0 < x, x < 1], axis=0), -(x**3) + 2 * x**2, np.maximum(x, 0))
Expand Down
92 changes: 92 additions & 0 deletions Slovakia.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import numpy as np
from mayavi import mlab
from PIL import Image
from matplotlib import pyplot as plt
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize, BoundaryNorm, LinearSegmentedColormap
from functions_2D import plot_contours
import os

import_step = 1
height_levels = 200

datagrid = Image.open("data/slovakia.tif")
datagrid = np.array(datagrid)[::-1][1200:2200:import_step, 2300:3300:import_step]
datagrid = np.maximum(0, datagrid)
dim_x = 50 * datagrid.shape[1] # Dimensions of loaded data in m
dim_y = 50 * datagrid.shape[0] # Dimensions of loaded data in m

minimum = int(np.floor(np.min(datagrid) / height_levels) * height_levels)
maximum = int(np.ceil(np.max(datagrid) / height_levels) * height_levels)
levels = np.arange(minimum, maximum + 1e-10, height_levels, dtype=int)
contour_levels = levels[:-1]

# Set up Figure
plt.rc("text", usetex=True)
plt.rc("font", family="serif")
size = 1
fig = plt.figure(figsize=(16 * size, 9 * size))
fig.tight_layout()
axes = fig.subplots(
1,
2,
sharex="all",
sharey="all",
subplot_kw={
"adjustable": "box",
"aspect": "equal",
"xticks": [x for x in np.linspace(0, dim_x, 6)],
"yticks": [y for y in np.linspace(0, dim_y, 6)],
"xticklabels": [f"{x:d} km" for x in np.linspace(0, dim_x / 1e3, 6, dtype=int)],
"yticklabels": [f"{y:d} km" for y in np.linspace(0, dim_x / 1e3, 6, dtype=int)],
"xlim": (0, dim_x),
"ylim": (0, dim_y),
},
gridspec_kw={"hspace": 0.3},
)
fig.add_subplot(111, frameon=False)
plt.tick_params(labelcolor="none", which="both", top=False, bottom=False, left=False, right=False)
plt.xlabel("Easting")
plt.ylabel("Northing")


mask = datagrid.T == 0
x = np.arange(0, dim_x, 50)
y = np.arange(0, dim_x, 50)

# Set up Colormaps
cmap = plt.get_cmap("terrain")
vmin = -0.25 * maximum * 1.1
vmax = maximum * 1.1
norm = Normalize(vmin, vmax) # Leave extra 10% for interpolation overshoot
colors = ScalarMappable(norm=norm, cmap=cmap)
plt.colorbar(colors, ticks=levels, format="%d m", ax=axes[0], shrink=0.7)
contour_colors = ScalarMappable(
norm=BoundaryNorm(
[
1.5 * contour_levels[0] - 0.5 * contour_levels[1],
*(contour_levels[0:-1] + contour_levels[1:]) / 2,
1.5 * contour_levels[-1] - 0.5 * contour_levels[-2],
],
levels.size,
),
cmap=LinearSegmentedColormap.from_list("", colors.to_rgba(contour_levels), N=levels.size),
)
plt.colorbar(contour_colors, ticks=contour_levels, format="%d m", ax=axes[1], shrink=0.7)

axes[0].pcolormesh(x, y, datagrid, cmap=cmap, norm=norm, rasterized=True)
axes[0].set_title("Zarnovica and Ziar nad Hronom Regions\n50m Resolution Raster")
plot_contours(x, y, datagrid, levels=levels, ax=axes[1], interpolate=True, colors=colors)

try:
os.mkdir(f"images/Slovakia")
except FileExistsError:
pass

plt.savefig("images/Slovakia/2D.png")
plt.show()
# mlab.surf(y, x, np.rot90(datagrid.T), mask=mask, warp_scale=5, colormap="terrain", vmin=vmin, vmax=vmax)
# mlab.view(azimuth=315)
#
# mlab.options.offscreen = True
# mlab.savefig("images/Slovakia/3D.png", magnification=10)
32 changes: 9 additions & 23 deletions comparison_2D_data_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize

from functions_2D import interpolate_low_output_resolution, plot_contours
from functions_2D import interpolate_discretized_data, plot_contours
from helpers.save_figure_position import ShowLastPos

"""
Expand All @@ -24,17 +24,7 @@ def test_epsilons_for_method(xo, yo, original_datagrid, x, y, datagrid, epsilons
for epsilon in epsilons:
mse = mean_square_error(
original_datagrid,
interpolate_low_output_resolution(
x,
y,
datagrid,
xo,
yo,
method="rbf_multiquadric",
epsilon=epsilon,
use_fix_contours=False,
use_clip_to_data=False,
),
interpolate_discretized_data(x, y, datagrid, xo, yo, method="rbf_multiquadric", epsilon=epsilon),
)
mses.append(mse)
print(f"Epsilon: {epsilon}, Mean Square Error: {mse}")
Expand All @@ -44,14 +34,14 @@ def test_epsilons_for_method(xo, yo, original_datagrid, x, y, datagrid, epsilons
plt.show()


def test_methods(xo, yo, original_datagrid, x, y, datagrid, use_fixes, plot):
def test_methods(xo, yo, original_datagrid, x, y, datagrid, plot):
def plot_result():
fig = plt.figure(figsize=(16, 9))
axes = fig.subplots(1, 4, subplot_kw={"aspect": "equal"})
plt.tight_layout()
axes[0].pcolormesh(xo, yo, original_datagrid, cmap=cmap, norm=norm, rasterized=True)
axes[1].pcolormesh(x, y, datagrid, cmap=cmap, norm=norm, rasterized=True)
axes[2].pcolormesh(xo, yo, interpolated_datagrid, cmap=cmap, norm=norm, rasterized=True)
axes[0].pcolormesh(xo, yo, original_datagrid, cmap=cmap, norm=norm)
axes[1].pcolormesh(x, y, datagrid, cmap=cmap, norm=norm)
axes[2].pcolormesh(xo, yo, interpolated_datagrid, cmap=cmap, norm=norm)
plt.colorbar(colors, ticks=levels, ax=axes[0:3].ravel().tolist())

diff = np.nan_to_num(interpolated_datagrid - original_datagrid)
Expand All @@ -70,15 +60,13 @@ def plot_result():
"rbf_cubic",
"rbf_quintic",
]:
interpolated_datagrid = interpolate_low_output_resolution(
interpolated_datagrid = interpolate_discretized_data(
x,
y,
datagrid,
xo,
yo,
method=method,
use_fix_contours=use_fixes,
use_clip_to_data=use_fixes,
)
print(f"Method: {method}, Mean Error: {mean_square_error(original_datagrid, interpolated_datagrid)}.")
if plot:
Expand All @@ -91,16 +79,14 @@ def plot_result():
[10, "rbf_inverse_multiquadric"], # Inverse methods don't work well in sparse places.
[3.5, "rbf_inverse_quadratic"],
]:
interpolated_datagrid = interpolate_low_output_resolution(
interpolated_datagrid = interpolate_discretized_data(
x,
y,
datagrid,
xo,
yo,
method=method,
epsilon=epsilon,
use_fix_contours=use_fixes,
use_clip_to_data=use_fixes,
)
print(
f"Method: {method}, Epsilon: {epsilon}, Mean Error: {mean_square_error(original_datagrid, interpolated_datagrid)}."
Expand Down Expand Up @@ -128,4 +114,4 @@ def plot_result():
datagrid = height_levels * np.floor(original_datagrid[::block_stride, ::block_stride] / height_levels)
x = np.linspace(0, 10, datagrid.shape[1])
y = np.linspace(0, 10, datagrid.shape[0])
test_methods(xo, yo, original_datagrid, x, y, datagrid, use_fixes=True, plot=False)
test_methods(xo, yo, original_datagrid, x, y, datagrid, plot=False)
36 changes: 22 additions & 14 deletions contour_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,38 @@
from matplotlib import pyplot as plt

from external.bezier import evaluate_bezier
from functions_1D import isolate_collinear, smooth_contour
from functions_1D import isolate_from_collinear, smooth_contour

# USE FOR CLOSED CONTOURS
"""
Script interpolates 1D parametric paths in 2D by using Cubic splines.
"""

# Set up Figure
plt.rc("text", usetex=True)
plt.rc("font", family="serif")
size = 0.7
fig = plt.figure(figsize=(16 * size, 9 * size))
fig.tight_layout()
axes = fig.subplots(1, 3, sharex="all", sharey="all", subplot_kw={"frame_on": False, "xticks": [], "yticks": []})

# Load and plot the original contour
contour = np.loadtxt("data/RealContour1A.txt")
# Set last point equal to first to close the curve
if not np.all(contour[0] == contour[-1]):
contour = np.append(contour, [contour[0]], axis=0)

plt.figure(figsize=(11, 8))
plt.plot(contour[:, 0], contour[:, 1])
axes[0].plot(contour[:, 0], contour[:, 1], color=plt.get_cmap("tab10")(0))
axes[0].set_title("Terraced contour")

interpolated_contour = smooth_contour(contour, collinearity_tol=1e-2)
plt.plot(interpolated_contour[:, 0], interpolated_contour[:, 1])
cubic_spline = smooth_contour(contour, collinearity_tol=1e-2)
axes[1].plot(cubic_spline[:, 0], cubic_spline[:, 1], color=plt.get_cmap("tab10")(1))
axes[1].set_title("Cubic spline")

# Bezier
contour_points = isolate_collinear(contour, closed=True, collinearity_tol=1e-2)
path = evaluate_bezier(contour_points, 20)
plt.plot(path[:, 0], path[:, 1])
plt.legend(["Original line", "Cubic spline", "Bezier spline"])
contour_points = isolate_from_collinear(contour, collinearity_tol=1e-2)
bezier_curve = evaluate_bezier(contour_points, 20)
axes[2].plot(bezier_curve[:, 0], bezier_curve[:, 1], color=plt.get_cmap("tab10")(2))
axes[2].set_title("Bezier curve")

# Plot line points and isolated points
# plt.plot(line[:, 0], line[:, 1], "gx", markersize=10)
# plt.plot(isolated_points[:, 0], isolated_points[:, 1], "ro")

plt.savefig("images/2D_Contour.png")
plt.show()
Loading

0 comments on commit c6596bc

Please sign in to comment.