misc_Plot.py 21.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 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 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 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 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
# -*- coding: utf-8 -*-

title = "PlotMap"
tip = "plots final map with grid and overlay"
onein = True

import numpy as np
import copy as cp

from guidata.qt.QtGui import QMessageBox, QApplication, QFileDialog
from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import (IntItem, StringItem, ChoiceItem, FloatItem, BoolItem)
from guiqwt.config import _
from guiqwt.histogram import hist_range_threshold
import guiqwt.colormap as cm

from kapteyn import maputils, mplutil, wcs
from matplotlib import pylab as plt

from guiqwt.transitional import QwtLinearColorMap, QwtDoubleInterval
FULLRANGE = QwtDoubleInterval(0.0, 1.0)

RAD = np.pi/180.0

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

def deg2dms(x, round=False, dx=1.0/36000.0):
    if x > 180.0: x -= 360.0 
    if x < 0: ds = "-"
    elif x == 0: ds = " "
    else: ds = "+"
    xD = int(x)
    xM = int(abs(x-xD)*60+dx)
    if round:
       xS = int((abs((x-xD)*60)-xM)*60)
    else:
       xS = (abs((x-xD)*60)-xM)*60
    return "%c%d^{\circ}%2.2d^{\prime}" % (ds, abs(xD), xM)

def append_color_bar(fshape, scale=12, size=0.05, pad=0.05, orientation='horizontal'):
    rows, cols = fshape
    x = scale
    y = scale * float(rows)/float(cols)
    f = scale / max(x, y)
    x *= f
    y *= f
    plt.close()
    fig = plt.figure(figsize=(x, y), facecolor='w')
    if orientation == 'horizontal':
       frame = fig.add_axes([0.1,0.2, 0.8,0.7], axisbg='w')
       cbframe = fig.add_axes((0.15, 0.15-pad-size, 0.7, size))
    else:
       frame = fig.add_axes([0.1,0.15, 0.75,0.7], axisbg='w')
       cbframe = fig.add_axes((0.825+pad, 0.15, size, 0.7))
    return frame, cbframe

class NOD3_App:

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

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

    def compute_app(self, **args):
        self.Units = ("Hour/Degree", "Min/Arcmin", "Sec/Arcsec")
        class FuncParam(DataSet):
              scale = FloatItem("Scale plot:", default=10, min=3, max=12)
              #ticks = IntItem("ticks[arcmin]:", default=-1, min=-1)
              numticks = IntItem("number of ticks:", default=5, min=2, max=12)
              cbar  = ChoiceItem("Colorbar:", (('horizontal', 'horizontal'), ('vertical', 'vertical')), default='Vertical')
              relcoord = BoolItem("Relative coordinates", default=False)
              ngrid = BoolItem("native grid", default=True)
              #deltax = IntItem("Increment Longitude:", min=1)
              #deltay = IntItem("Increment Latitude:", min=1)
              #unit = ChoiceItem("Unit:", zip(self.Units, self.Units), default=self.Units[1])
              overcolor = ChoiceItem("Overlay color:", (('default', 'default'),('black', 'black'),
                                                ('white', 'white')), default='default')
              gridcolor = ChoiceItem("Grid color:", (('black', 'black'), ('white', 'white')),
                                                default='black')
              beam = ChoiceItem("Beam position:", (('No', 'No'), ('BL', 'BL'), ('BR', 'BR'),
                                                ('TL', 'TL'), ('TR', 'TR')),
                                                default='No')
              plot = BoolItem("save as PDF", default=False)
        name = title.replace(" ", "")
        if args == {}:
           param = FuncParam(_(title), "Setup your plot:")
        else:
           param = self.parent.ScriptParameter(name, args)

        # if no parameter needed set param to None. activate next line
        #param = None
        self.parent.compute_11(name, lambda m, p: self.function(m, p), param, onein) 

    def setColor(self, a, f=255.0):
        y = hex(a)[2:-1]
        x = [ord(c) for c in y.decode('hex')]
        r = (float(x[1])/f)
        g = (float(x[2])/f)
        b = (float(x[3])/f)
        return r, g, b

    def setup_lut(self, cmap, f=255.0):
        lut = [[], [], []]
        for i in range(len(cmap)):
            r, g, b = self.setColor(cmap[i])
            lut[0].append(r)
            lut[1].append(g)
            lut[2].append(b)
        return np.array(lut).T
        
    def get_axes_style(self):
        """Get axis styles from NOD3 main setups"""
        axes = {0: 'left', 1: 'right', 2: 'bottom', 3: 'top'}
        self.left = {'Tstyle': 'normal', 'style': 'normal', 'style_bold': 'normal'}
        self.right = {'Tstyle': 'normal', 'style': 'normal', 'style_bold': 'normal'}
        self.bottom = {'Tstyle': 'normal', 'style': 'normal', 'style_bold': 'normal'}
        self.top = {'Tstyle': 'normal', 'style': 'normal', 'style_bold': 'normal'}
        styles = ('title', 'color', 'family', 'size', 'bold', 'italic')
        for axis in range(4):
            if nint(self.equinox) == 2000: ex = " (J2000)"
            elif nint(self.equinox) == 1950: ex = " (B1950)"
            else: ex = str(" (%f)" % self.equinox)
            unit = self.parent.plot.axes_styles[axis].unit
            title = self.parent.plot.axes_styles[axis].title.replace("dRA", "RA"+ex).replace("dDEC", "DEC"+ex)
            if unit != None and unit.strip() != "": title += " (" + unit + ")"
            
            color = self.parent.plot.axes_styles[axis].color
            exec("self." + axes[axis] + "['title'] =  title")
            exec("self." + axes[axis] + "['color'] =  color")
            for style in styles[styles.index('family'):]:
                val1 = eval("self.parent.plot.axes_styles[axis].ticks_font."+ style)
                exec("self." + axes[axis] + "[style] =  val1")
                if style == 'italic' and val1: exec("self." + axes[axis] + "['style'] = 'italic'")
                if style == 'bold' and val1: exec("self." + axes[axis] + "['style_bold'] = 'bold'")
                val2 = eval("self.parent.plot.axes_styles[axis].title_font."+ style)
                exec("self." + axes[axis] + "['T'+style] =  val2")
                if style == 'italic' and val2: exec("self." + axes[axis] + "['Tstyle'] = 'italic'")
                if style == 'bold' and val2: exec("self." + axes[axis] + "['Tstyle_bold'] = 'bold'")

    def getCoord(self, positions, mat):
        newpos = []
        for pos in positions:
            newp = []
            for p in pos:
                l, b = p
                x = np.cos(RAD*b)*np.cos(RAD*l)
                y = np.cos(RAD*b)*np.sin(RAD*l)
                z = np.sin(RAD*b)
                xyz = np.dot(np.array(mat), np.array([x,y,z]))
                l1 = np.arctan2(xyz[1], xyz[0])
                b1 = np.arctan2(xyz[2], np.sqrt(xyz[1]**2 + xyz[0]**2))
                newp.append((l1/RAD, b1/RAD))
            newpos.append(newp)
        return newpos

    def rotmat_x(self, a):
        xrot = [[1.0, 0.0, 0.0], \
                [0.0, np.cos(a*RAD), -np.sin(a*RAD)], \
                [0.0, np.sin(a*RAD),  np.cos(a*RAD)]]
        return xrot

    def function(self, m, p):
        found = False
        visible = True
        for item in self.parent.items:
            if item.isVisible():
               m.data = item.data
               m.header = item.header
               if 'EQUINOX' in m.header:
                  self.equinox = m.header['EQUINOX']
               elif 'EPOCH' in m.header:
                  self.equinox = m.header['EPOCH']
               found = True
        #if not found: return [], p
        if not found:
           image = self.parent.items[self.parent.row]
           visible = False
        # check if image is allready plotted (onein = True)!!
        if hasattr(self.parent, 'isPlotted'): return [], p
        self.parent.isPlotted = True

        self.get_axes_style() 
        fs = 0.15 * p.scale
        desc = False
        #orientation = 'horizontal'
        #orientation = 'vertical'
        orientation = p.cbar
        if 'SCANDIR' in m.header: scandir = m.header['SCANDIR']
        else: scandir = None
        offsetx = False
        if not p.relcoord:
           m.header['CTYPE1'] = m.header['CTYPE1'].replace("DES", "CAR")
           m.header['CTYPE2'] = m.header['CTYPE2'].replace("DES", "CAR")
           if m.header['CTYPE1'][:4] == "GLON":
              self.bottom['title'] = "Galactic Longitude"
              self.left['title'] = "Galactic Latitude"
           if 'CROTA1' in m.header:
              if abs(m.header['CROTA1']) > 1.0:
                 self.bottom['title'] = "Longitude"
                 self.left['title'] = "Latitude"
                 m.header['CROTA1'] = 0.0
           if 'CROTA2' in m.header:
              if abs(m.header['CROTA2']) > 1.0:
                 self.bottom['title'] = "Longitude"
                 self.left['title'] = "Latitude"
                 m.header['CROTA2'] = 0.0
           if self.parent.descript:
              xoff = m.header['CRVAL1']
              yoff = m.header['CRVAL2']
           else:
              xoff = 0.0
              yoff = 0.0
           f1 = 1./np.cos(np.pi/180 * yoff)
        else:
           desc = True
           xoff = 0.0
           yoff = 0.0
           f1 = 1.0
        if m.header['CTYPE1'].endswith("DES") or scandir == "ALON" or p.relcoord:
           offsetx = True
           m.header['CTYPE1'] = m.header['CTYPE1'].replace("DES", "CAR")
           m.header['CTYPE2'] = m.header['CTYPE2'].replace("DES", "CAR")
           m.header['CRVAL1'] = 0.0
           m.header['CRVAL2'] = 0.0
           m.header['CRPIX1'] = m.header['NAXIS1']/2.0
           m.header['CRPIX2'] = m.header['NAXIS2']/2.0
           if m.header['CTYPE1'][:4] == "GLON":
              self.bottom['title'] = "Galactic Longitude"
              self.left['title'] = "Galactic Latitude"
           if 'CROTA1' in m.header:
              if abs(m.header['CROTA1']) > 1.0:
                 self.bottom['title'] = "Longitude"
                 self.left['title'] = "Latitude"
                 m.header['CROTA1'] = 0.0
           if 'CROTA2' in m.header:
              if abs(m.header['CROTA2']) > 1.0:
                 self.bottom['title'] = "Longitude"
                 self.left['title'] = "Latitude"
                 m.header['CROTA2'] = 0.0
        if 'SCANDIR' in m.header and m.header['SCANDIR'][:2] == "AL":
           m.header['CTYPE1'] = "ALON-SFL"
           m.header['CTYPE2'] = "ALAT-SFL"
           self.bottom['title'] = "Azimuth"
           self.left['title'] = "Elevation"
           m.header['CRVAL1'] = 0.0
           m.header['CRVAL2'] = 0.0
           desc = True
           
        coord = m.header['CTYPE1'][:4].replace("-", "")
        proj = m.header['CTYPE1'][-3:]
        rows, cols = m.data.shape
        m.header['NAXIS'] = 2
        m.header['NAXIS1'] = cols
        m.header['NAXIS2'] = rows
        sizex, sizey = abs(m.header['CDELT1']*(cols-1)), m.header['CDELT2']*(rows-1)
        b0 = m.header['CRVAL2'] + m.header['CDELT2'] * m.header['NAXIS2']/2
        sizex = sizex/np.cos(np.pi/180.0 * b0)
        numticks = float(p.numticks)
        deltax = max(sizex, sizey) / numticks
        deltay = deltax*np.cos(np.pi/180*m.header['CRVAL2'])

        #fscal = 60.0**self.Units.index(p.unit)
        #deltax = p.deltax/fscal
        #deltay = p.deltay/fscal

        def smart_ticks(delta, unit):
            sign = np.sign(delta)
            delta = abs(delta)
            delta = int(delta*unit + 1.0e-6)
            if delta > 4 and delta < 8:
               delta = 5
            elif delta > 7 and delta < 13:
               delta = 10
            elif delta > 12 and delta < 18:
               delta = 15
            elif delta > 17 and delta < 26:
               delta = 20
            elif delta > 25:
               delta = 30
            else:
               delta = max(1, int(delta))
            return sign*delta/unit

        if int(abs(deltay)) > 0:
           deltay = int(deltay)
           self.DMS = "Dms"
        elif int(abs(deltay*60)) > 0:
           deltay = smart_ticks(deltay, 60.0)
           self.DMS = "DMs"
        elif int(abs(deltay*3600)) >= 0:
           deltay = smart_ticks(deltay, 3600.0)
           self.DMS = "DMS"
        if m.header['CTYPE1'][:2].upper() == "RA":
           fra = 15.0
        else:
           fra = 1
        deltax = deltax/fra
        if int(abs(deltax)) > 0:
           deltax = int(deltax)
           self.HMS = "Hms"
        elif int(abs(deltax*60)) > 0:
           deltax = smart_ticks(deltax, 60)
           self.HMS = "HMs"
        elif int(abs(deltax*3600)) >= 0:
           deltax = smart_ticks(deltax, 3600.0)
           self.HMS = "HMS"
        deltax = deltax*fra

        # stop app if number of tickmarks extends 15
        if max(sizex, sizey) / max(deltax, deltay) > 15:
           self.Error("too many tickmarks: %d" % int(max(sizex, sizey) / max(deltax, deltay)))
           return [], p

        overlays = []
        for item in self.parent.plot.itemList():
            if item.isVisible():
               if str(item).find("image") > 0:
                  image = item
               else:
                  overlays.append(item)

        cmap = image.get_color_map().colorTable(FULLRANGE)
        lut = self.setup_lut(cmap)
        lut_name = mplutil.VariableColormap(lut)
        title = self.top['title']
        calunit = self.right['title']

        f = maputils.FITSimage(externalheader=m.header, externaldata=m.data)
        frame, cbframe = append_color_bar(m.data.shape, scale=p.scale, 
                                          size=0.015, pad=0.01, orientation=orientation)
        frame.set_title(title, fontsize=fs*self.top['Tsize'])
        mplim = f.Annotatedimage(frame, cmap=lut_name, clipmin=image.min, clipmax=image.max)
        if self.parent.InterpolationMode:
           im = mplim.Image(interpolation='bicubic', visible=visible)
        else:
           im = mplim.Image(interpolation='nearest', visible=visible)
        #cunit = str("\n%s" % calunit)
        cunit = str("%s" % calunit)
        colbar = mplim.Colorbar(fontsize=fs*self.right['Tsize'], orientation=orientation, 
                                clines=True, frame=cbframe)
        if orientation == "horizontal":
           colbar.set_label(label=cunit, fontsize=fs*self.right['Tsize'], rotation=0.0, style=self.right['Tstyle'])
        else:
           colbar.set_label(label=cunit, fontsize=fs*self.right['Tsize'], rotation=90.0, style=self.right['Tstyle'])
        gr = mplim.Graticule(deltax=deltax, deltay=deltay, offsetx=offsetx)
        if self.bottom['title'].lower() == "pixel":
           def wsc2pix(x):
               #if x > 180.0: x -= 360.0
               pix = (x - m.header['CRVAL1'])/m.header['CDELT1'] + m.header['CRPIX1'] - 1
               return int(pix+0.5)
           def wsc2piy(x):
               piy = (x - m.header['CRVAL2'])/m.header['CDELT2'] + m.header['CRPIX2'] - 1
               return int(piy+0.5)
           gr.setp_ticklabel(fmt='%d', fun=wsc2pix, plotaxis='bottom')
           gr.setp_ticklabel(fmt='%d', fun=wsc2piy, plotaxis='left')
        elif coord == "GLON":
           gr.setp_ticklabel(fmt="%.2f^{\circ}", tol=1.e-6)
        elif desc:
           gr.setp_ticklabel(fmt='%s', fun=deg2dms) # Suppress the seconds in all labels
        else:
           if sizex < 1.5 and m.header['CTYPE1'][:2] == "RA":
              gr.setp_ticklabel(fmt=self.HMS, plotaxis='bottom') # Suppress the seconds in all labels
              gr.setp_ticklabel(fmt=self.DMS, plotaxis='left') # Suppress the seconds in all labels
           else:
              gr.setp_ticklabel(fmt=self.HMS, plotaxis='bottom') # Suppress the seconds in all labels
              gr.setp_ticklabel(fmt=self.DMS, plotaxis='left') # Suppress the seconds in all labels

        gr.setp_gratline(color='red')
        if p.ngrid:
           gr.setp_gratline(visible=True, linewidth=0.5, linestyle='solid', color=p.gridcolor)
           #gr.setp_tickmark(markersize=-6, markeredgewidth=1.5, color=p.gridcolor, alpha=1.0)
           gr.setp_tickmark(markersize=-4, markeredgewidth=0.8, color='black', alpha=1.0)
        else:
           gr.setp_gratline(visible=False)
           #gr.setp_tickmark(markersize=-6, markeredgewidth=1.5, color=p.gridcolor, alpha=1.0)
           gr.setp_tickmark(markersize=-4, markeredgewidth=0.8, color='black', alpha=1.0)

        # Beam:
        if p.beam != "No" and 'BMAJ' in m.header:
           bx = m.header['BMAJ']
           by = m.header['BMIN']
           dx = abs(m.header['CDELT1'])
           dy = abs(m.header['CDELT2'])
           rows, cols = m.data.shape
	   bdx = max(0.05*cols, 0.75*max(bx/dx, by/dy))
	   bdy = max(0.05*rows, 0.75*max(bx/dx, by/dy))
           if p.beam == "BL":
              px = bdx
              py = bdy
           elif p.beam == "TL":
              px = bdx
              py = rows - bdy
           elif p.beam == "BR":
              px = cols - bdx
              py = bdy
           elif p.beam == "TR":
              px = cols - bdx
              py = rows - bdy
           if 'BPA' in m.header:
              pa = m.header['BPA']
           else:
              pa = 0.0
           pos = str("%d %d" % (px, py))
           fc = p.gridcolor[0]
           beam = mplim.Beam(bx, by, pa=pa, pos=pos, fc=fc, fill=True, alpha=0.75)

        # Overlays:
        proj = wcs.Projection(m.header) 
        for overlay in overlays:
            if hasattr(overlay, 'Factor'):
               f = overlay.Factor
            else:
               f = 1.0
            if p.overcolor != 'default':
               overlay.Color = p.overcolor
            if hasattr(overlay, 'Name'):
               if overlay.Name == "Contours":
                  mplim.data = overlay.Data
                  cont = mplim.Contours(levels=overlay.Levels, colors=overlay.Color,
                                        linewidth=overlay.Linewidth)
               elif overlay.Name == 'Lines':
                  # rotate map first if CROTA != 0.0
                  if 'CROTA2' in m.header:
                     rotang = m.header['CROTA2']
                  else:
                     rotang = 0.0
                  if rotang != 0.0:
                     mat = self.rotmat_x(rotang)
                     Positions = self.getCoord(overlay.Positions, mat)
                  else:
                     Positions = overlay.Positions
                  for pos1, pos2 in Positions:
                      if hasattr(overlay, 'Pixel') and overlay.Pixel:
                         pos1 = proj.toworld(pos1)
                         pos2 = proj.toworld(pos2)
                      lons = ((xoff+f1*pos1[0])/f, (xoff+f1*pos2[0])/f)
                      lats = ((yoff+pos1[1])/f, (yoff+pos2[1])/f)
                      line = mplim.Skypolygon(prescription=None, lons=lons, lats=lats,
                                              color=overlay.Color, linewidth=overlay.Linewidth)
               elif overlay.Name == 'Polygons':
                  for polygon in overlay.Positions:
                      n1, n2 = np.shape(polygon)
                      lons = []
                      lats = []
                      for pos in polygon:
                          if hasattr(overlay, 'Pixel') and overlay.Pixel: 
                             pos = proj.toworld(pos)
                          lons.append((xoff+f1*pos[0])/f)
                          lats.append((yoff+pos[1])/f)
                      line = mplim.Skypolygon(prescription=None, lons=lons, lats=lats, fill=False,
                                              color=overlay.Color, linewidth=overlay.Linewidth)

        # set NOD3 style setup:
        gr.setp_axislabel("bottom", label= self.bottom['title'], fontsize=fs*self.bottom['Tsize'],
                        fontstyle=self.bottom['Tstyle'], color=self.bottom['color'])
        gr.setp_axislabel("left", label= self.left['title'], fontsize=fs*self.left['Tsize'],
                        fontstyle=self.left['Tstyle'], color=self.left['color'])
        gr.setp_axislabel("right", label= self.right['title'], fontsize=fs*self.right['Tsize'],
                        fontstyle=self.right['Tstyle'], color=self.right['color'])

        gr.setp_ticklabel(plotaxis='bottom', color=self.bottom['color'], rotation=0.0, 
                       fontsize=fs*self.bottom['size'], fontweight=self.bottom['style_bold'],
                       style=self.bottom['style'])
        gr.setp_ticklabel(plotaxis='left', color=self.left['color'], rotation=90.0, 
                       fontsize=fs*self.left['size'], fontweight=self.left['style_bold'], 
                       style=self.left['style'])
        gr.setp_ticklabel(plotaxis='right', color=self.right['color'], rotation=0.0, 
                       fontsize=fs*self.right['size'], fontweight=self.right['style_bold'], 
                       style=self.right['style'])

        mplim.plot()
        QApplication.restoreOverrideCursor()

        if not p.plot:
           plt.show()
           return [], p
        files_types = "Portable Document Format (PDF) (*.pdf);;Postscript (PS) (*.ps);;\
Encapsulated Postscript (EPS) (*.eps);;\
Portable Network Graphics (PNG) (*.png);;\
Joint Photographic Experts Group (JPG) (*.jpg);;\
Tagged Image File Format (TIFF) (*.tif);;\
Raw RGBA bitmap (*.raw);;\
Scalable Vector Graphics (SVG) (*.svg)"
        filename = image.header['FILENAME']
        if filename.lower().endswith(".fits"):
           filename = filename[:-4] + "pdf"
        plot_file = QFileDialog.getSaveFileName(self.parent, 'Save file', filename, files_types)
        plt.savefig(str(plot_file))

        return [], p