maped_polyInt.py 3.49 KB
# -*- coding: utf-8 -*-
title = "Polygon Interpolation"
tip = "selects a part of a map"
onein = -1

import numpy as np
try: from matplotlib.nxutils import points_inside_poly
except: from nod3tools import points_inside_poly

from guidata.qt.QtGui import QMessageBox, QApplication
from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import (IntItem, StringItem, ChoiceItem, FloatItem, BoolItem)
from guidata.qt.QtCore import Qt
from guiqwt.events import setup_standard_tool_filter, KeyEventMatch
from guiqwt.config import _

def nint(x):
    if x > 0: return int(x+0.5)
    else: return int(x-0.5)

class NOD3_App:

    def __init__(self, parent):
        self.parent = parent
        self.parent.activateWindow()

    def Info(self, msg):
        QMessageBox.information(self.parent.parent(), title,
                              #_(u"Info:")+"\n%s" % str(msg))
                              str(msg))

    def Error(self, msg):
        QMessageBox.critical(self.parent.parent(), title,
                              _(u"Error:")+"\n%s" % str(msg))

    def compute_app(self, **args):
        class FuncParam(DataSet):
            posx = IntItem('center x')
            posy = IntItem('center y')
            naxis1 = IntItem('shape x')
            naxis2 = IntItem('shape y')
        self.name = title.replace(" ", "")
        if args == {}:
           param = FuncParam(_(title), "Use box to select a map extraction:\n")
        else:
           param = self.parent.ScriptParameter(name, args)

        # if no parameter needed set param to None. activate next line
        param = None
        msg = str("Usage of Application %s:\n \
             mouse left button creates polygon lines \n \
             keys <Delete> or <Backspace> delete lines one by one \n \
             keys <n> or <Enter> or <Return> setup a new polygon \n \
             keys <Space> or <Esc> finish the application" % self.name)
        self.Info(msg)
        self.parent.get_polyline(self.name, 
                                 lambda m, p, polygon: self.function(m, p, polygon),
                                 param)

    def coordinates2pixel(self, polygon):
        polypix = np.copy(polygon)
        for n in range(len(polypix)):
            for k in range(len(polypix[n])):
                l, b = polypix[n][k]    
                x, y = self.parent.get_pixel_coordinates(l, b)
                polypix[n][k] = [nint(x), nint(y)]
        return polypix

    def pad(self, data):
        bad_mask = np.isnan(data)
        good_mask = ~bad_mask
        good_data = data[good_mask]
        if len(good_mask.nonzero()[0]) == 0:
           return data
        interpolated = np.interp(bad_mask.nonzero()[0], good_mask.nonzero()[0], good_data)
        data[bad_mask] = list(interpolated)
        return data

    def function(self, m, p, polygon):
        polypix = self.coordinates2pixel(polygon) 
        rows, cols = m.data.shape
        x, y = np.meshgrid(np.arange(cols), np.arange(rows))
        x, y = x.flatten(), y.flatten()
        points = np.vstack((x,y)).T
        Mask = np.isnan(m.data)
        mask = []
        for n in range(len(polypix)):
            mask = points_inside_poly(points, polypix[n]).reshape((rows, cols))
            data = np.where(mask, np.nan, m.data)
            m.data = (np.apply_along_axis(self.pad, 0, 1*data) +
                      np.apply_along_axis(self.pad, 1, 1*data)) / 2.0
        m.data = np.where(Mask, np.nan, m.data)
        self.parent.del_poly = True
        self.parent.properties_changed()
        return m, p