galaxy_boxint4.py 34.5 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 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
title = "BoxModels"
tip = "Box integration on edge-on galaxies"
onein = 1

import numpy as np
import copy as cp
from scipy.integrate import quad
from scipy import stats
try:
   from nodfitting import curve_fit
except:
   from scipy.optimize import curve_fit
from nodmath import map_rotate, map_interpolate, map_zoom, extract
from scipy.special import erfc
from scipy.stats import chisquare

from guiqwt import pyplot
from guiqwt.tools import SelectPointTool
from guidata.qt.QtGui import QMessageBox, QListView, QStandardItemModel, QStandardItem, QFont
from guidata.dataset.datatypes import DataSet
from guidata.dataset.dataitems import (IntItem, StringItem, ChoiceItem, FloatItem, BoolItem)
from guiqwt.config import _
from guiqwt.curve import PolygonMapItem

RAD = np.pi/180
from nodmath import nanmean

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 Error(self, msg):
        QMessageBox.critical(self.parent.parent(), title,
                              _(u"Error:")+"\n%s" % str(msg))

    def getparams(self):
        class SetParam(DataSet):
              BMAJ = FloatItem('BMAJ ["]:', min=1)
              BMIN = FloatItem('BMIN ["]:', min=1)
        name = self.title.replace(" ", "")
        k = SetParam(_(self.title), "Give FWHM in arcsec:")
        if k is not None:
            if not k.edit(parent=self.parent.parent()):
                return
        return k.BMAJ, k.BMIN

    def compute_app(self, **args):
        Weight = ('No', 'Both', 'Lower', 'Upper')
        Model = ("Exponential", "Gaussian", "SecHsq", "Hybrid")
        base = ('Full', 'Slope', 'Offset', 'None')
        self.Model = Model
        class FuncParam(DataSet):
            #s = StringItem('s', default="string")
            #i = IntItem('i', default=0, max=100, min=0)
            incl = FloatItem('Inclination [degree]', default=90.0)
            posang = FloatItem('Position angle [degree]', min=-90.0, max=90.0)
            #stdir = ChoiceItem("Stripes direction", (("parallel", "parallel"),
            #                                       (("rectangular", "rectangular"))))
            rms = FloatItem("RMS", min=0.0)
            dimgal = FloatItem("Galaxy diameter [arcsec]", min=-1.0)
            boxwidth = FloatItem("BoxWidth [arcsec]")
            boxheight = FloatItem("BoxHeight [arcsec]")
            xnum = IntItem("#Boxes in X")
            ynum = IntItem("#Boxes in Y")
            noise_model = ChoiceItem(_(u"Noise model"), (("Standard", "Standard"), ("RMS", "RMS")))
            #rebin = IntItem("Rebin", default=1, min=1, max=20)
            #boxcenter = BoolItem("BoxCenter", default=True)
            #cursor = BoolItem("Cursor", default=False)
            twocomp = BoolItem("Two Components", default=False)
            log = BoolItem("Log Plot", default=False)
            ngraph = IntItem("#Graphs per row", default=3)
            weight = ChoiceItem(_(u"Weighted fit"), zip(Weight, Weight), default=Weight[0])
            model = ChoiceItem(_(u"Scale height model"), zip(Model, Model), default=Model[0])
            #weight = BoolItem("Weighted fit", default=False)
            baseline = ChoiceItem(_(u"Baseline"), zip(base, base), default=base[1])
            outfile = StringItem('Outfile', default="boxint.out")
            #inclin = FloatItem('Inclination', default=31., min=0, max=89.0)
            #rms = FloatItem('Noise', default=5., min=0, max=10.0)
            #overl = BoolItem("Overlay", default=True)
            #choice = ChoiceItem("Unit", ("Degree", "Arcmin", "Arcsec"), default=2)
        name = title.replace(" ", "")
        self.title = title
        if args == {}:
           param = FuncParam(_(title), "Setup parameters for box integration:")
        else:
           param = self.parent.ScriptParameter(name, args)

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

    def rotate(self, m, angle):
        q = {'angle': angle, 'mode': 'constant', 'reshape': False, 'prefilter': True, 'order': 3}
        #if abs(angle) > 0.1:
        #   q['angle'] = angle+90
        #else:
        #   q['angle'] = 0
	if angle > 0: q['angle'] = -(90-angle)
	else: q['angle'] = (90+angle)
        param = self.parent.ScriptParameter("Rotation", q)
        rows, cols = m.data.shape
        if 'TMPROT' not in m.header:
           rows1 = (rows+1)/2 * 2 - 1
           cols1 = (cols+1)/2 * 2 - 1
           posy, posx = m.header['CRPIX2'], m.header['CRPIX1']
           m.data = extract(m.data, shape=(rows1, cols1), position=(nint(posy-1), nint(posx-1)))
        if 'TMPROT' in m.header:
           if abs(m.header['TMPROT'] - angle) > 0.1:
              m.data = map_rotate(m.data, param) 
              self.update = True
           else:
              self.update = False
        else:
           m.data = map_rotate(m.data, param) 
           self.update = True
        m.header['TMPROT'] = angle
        m.header['CRVAL1'] = m.header['CRVAL2'] = 0.0
        m.header['CTYPE1'] = m.header['CTYPE1'][:-3] + "DES"
        m.header['CTYPE2'] = m.header['CTYPE2'][:-3] + "DES"
        if 'LONPOLE' in m.header:
           del m.header['LONPOLE'] 
        if 'LATPOLE' in m.header:
           del m.header['LATPOLE'] 
        rows, cols = m.data.shape
        #m.header['CRVAL1'] = x
        #m.header['CRVAL1'] = y
        m.header['CRPIX1'] = (cols+1)/2.0
        m.header['CRPIX2'] = (rows+1)/2.0
        #m = self.parent.removeNANedges(m)
        return m

    def yintpn(self, a, b, c, d, y):
        e = b-a
        f = b-c
        g = e+f+f+d-c
        g = g*y-e-f-g
        g = g*y-a+c
        return 0.5*g*y+b

    def gaussian(self, x, a, sigma, a0, b0):
	return a0 + b0*x + a*np.exp(-x**2/(2*sigma**2))

    def deincl(self, m, incl, rms, dimgal):
        rows, cols = m.data.shape
        row2 = int(m.header['CRPIX2'])
	#nrows = max(2, 1+int(m.header['BMAJ'] / m.header['CDELT1']))
	nrows = max(3, int(3*m.header['BMAJ'] / abs(m.header['CDELT1'])))
	p2 = nrows/2
        y = 0.0*m.data[row2]
	for i in range(nrows):
	    y += m.data[row2-p2+i] 
	y /= nrows
        x = 3600*(np.arange(float(cols)) - m.header['CRPIX1'])*m.header['CDELT1']
        ymax100 = 2*rms
        xmin = 999999999999999999999.0
        xmax = -xmin
	imax = cols
        dxm = 1.5*self.p.boxwidth/3600.0 * self.p.xnum / 2 / abs(m.header['CDELT1'])
        dxm = min(dxm, cols/2)-1
        for i in range(cols/2, cols/2+nint(dxm), 1):
            #if y[i] > ymax100 and not np.isnan(y[i]):
            if y[i] > ymax100:
               xmin = x[i]
	       imax = i
	imin = 0
        for i in range(cols/2, cols/2-nint(dxm), -1):
            #if y[i] > ymax100 and not np.isnan(y[i]):
            if y[i] > ymax100:
               xmax = x[i]
	       imin = i
        xm = (abs(xmax) + abs(xmin))/2.0
        dy = ymax100/np.nanmax(y)
        if dimgal > 0:
           xm = dimgal/2.0
        sigma = 3600*m.header['BMAJ'] / (2.0*np.sqrt(2.0*np.log(2.0)))
        #sigma1 = np.cos(RAD*incl)*xm / np.sqrt(2*np.pi)
        sigma1 = np.cos(RAD*incl)*xm / (2.0*np.sqrt(2.0*np.log(2.0)))
        sigma_new = np.sqrt(sigma**2 + sigma1**2)
        self.galaxy_radius = xm
        return sigma_new/3600.0 * 2.0*np.sqrt(2.0*np.log(2.0))

    def copy(self, m):
        mx = cp.copy(m)
        mx.header = m.header.copy()
        mx.data = 1*m.data
        return mx

    def overlay(self, m, p):
        g = self.parent.vu
        f = 3600.0
        rows, cols = m.data.shape
        pixw = 3600*np.sqrt(m.header['CDELT1']**2 + m.header['CDELT2']**2) / np.sqrt(2.0)
        if p.cursor:
           l0, b0 = self.l/g, self.b/g
        else:
           l0, b0 = 0.0, 0.0
        l1, b1 = self.parent.get_plot_coordinates(0, 0)
        l2, b2 = self.parent.get_plot_coordinates(cols, rows)
        points = []
        offsets = []
        colors = []
        COLORS = [0xffffffff, 0x00000000]
        dpix = p.boxwidth / pixw 
        if dpix < 0.9*np.sqrt(2.):
           self.Error("Stripewidth too small")
           return [], p 
        nanz = p.xnum+1
        manz = p.ynum+1
        xbox = 1 - nanz%2
        ybox = 1 - manz%2
        n = 0
        wpix = nint(p.boxwidth/(f*m.header['CDELT2']))
        p.boxwidth = int(1000*wpix*m.header['CDELT2']*f)/1000.0
        hpix = nint(p.boxheight/(f*m.header['CDELT2']))
        p.boxheight = int(1000*hpix*m.header['CDELT2']*f)/1000.0
        l1 = l0 + (-p.boxwidth/2.0*xbox + (xbox-nanz/2)*p.boxwidth)/f
        l2 = l0 + (-p.boxwidth/2.0*xbox + (nanz/2)*p.boxwidth)/f
        b1 = b0 + (-p.boxheight/2.0*ybox + (ybox-manz/2)*p.boxheight)/f
        b2 = b0 + (-p.boxheight/2.0*ybox + (manz/2)*p.boxheight)/f
        print l0, b0, l1,l2,b1,b2
        self.bw = []
        for j in range(nanz): 
            dp = (-p.boxwidth/2.0*xbox + (j-nanz/2+xbox)*p.boxwidth)/f
            l = l0 + dp
            points.append(([l*g,b1*g], [l*g,b2*g]))
            offsets.append([n, 2*n])
            colors.append(COLORS)
            n += 1
            #x = int(m.header['CRPIX1'] + l / m.header['CDELT1'])
            x, y = self.parent.get_pixel_coordinates(l*f, 0.0)
            self.bw.append(x)
        self.bh = []
        for i in range(manz):
            dp = (-p.boxheight/2.0*ybox + (i-manz/2+ybox)*p.boxheight)/f
            b = dp
            points.append(([l1*g,b*g], [l2*g,b*g]))
            offsets.append([n, 2*n])
            colors.append(COLORS)
            n += 1
            #y = int(m.header['CRPIX2'] + b / m.header['CDELT2'])
            x, y = self.parent.get_pixel_coordinates(0.0, b*f)
            self.bh.append(y)
        positions = cp.copy(points)
        points = np.concatenate(points)
        crv = PolygonMapItem()
        crv.set_data(points, offsets, colors)
        crv.Name = "Polygons"
        crv.Positions = positions
        crv.Color = 'white'
        crv.Linewidth = 1.0
        crv.Factor = self.parent.vu
        self.parent.plot.add_item(crv)
        self.parent.plot.replot()

    def rebin(self, m, rbin, order=4, prefilter=True):
        m.data = map_zoom(m.data, rbin, order=4, prefilter=True)
        m.header['NAXIS2'], m.header['NAXIS1'] = m.data.shape
        m.header['CRPIX1'] = (m.header['CRPIX1']-0.5) * rbin
        m.header['CRPIX2'] = (m.header['CRPIX2']-0.5) * rbin
        m.header['CDELT1'] /= rbin
        m.header['CDELT2'] /= rbin
        return m

    def read_cursor(self, tool):
        self.l, self.b = tool.get_coordinates()
        #x, y = self.parent.get_pixel_coordinates(self.l, self.b)
        self.parent.cursor_activ = True
        self.overlay(self.m1, self.p)
        self.statistics(self.m1.data)
        self.scalefit(self.p.weight)
        self.printout(self.p.outfile, p.dimgal)
        self.parent.cursor_activ = False
        self.parent.plot.canvas_pointer = False
        self.selpos.end_callback = None
        del self.selpos
        self.parent.imagewidget.activate_default_tool()

    def get_cursor(self):
        self.cursor_activ = True
        row = self.parent.listwidget.currentRow()
        if row < 0: return
        self.selpos = self.parent.get_tool(SelectPointTool)
        self.selpos.TIP = "click on left button"
        self.selpos.mode = "reuse"
        self.selpos.marker = self.parent.plot.cross_marker
        self.selpos.end_callback = self.read_cursor
        self.selpos.activate()
        #self.parent.setup_KeyEvent(self.selpos, 'SingleClick')
        self.parent.setup_KeyEvent(self.selpos, 'Cursor')
        if hasattr(self.selpos, 'get_active_plot'):
           self.selpos.win = self.selpos.get_active_plot()
           self.selpos.win.set_pointer("canvas")

    def create_output_list(self):
        # add source list box
        self.sourcelist = QListView()
        self.sourcelist.setWindowTitle('Galaxy scale height fit results')
        self.sourcelist.setMinimumSize(800, 300)
        self.sourcelist.setFont(QFont('Monospace'))
        self.model = QStandardItemModel(self.sourcelist)
        self.sourcelist.setModel(self.model)
        self.parent.LView = self.sourcelist
        #self.model.appendRow(QStandardItem(header))
        self.N = 0
        self.parent.N = True

    def printout(self, filename, dimgal):
        try:
           f = open(filename, 'w')
           filename1 = filename + ".results"
           filename2 = filename + ".fitvalues"
           f1 = open(filename1, 'w')
           f2 = open(filename2, 'w')
        except:
           self.Error("no permisson to write on disk")
           return
        boxwidth = self.p.boxwidth
        boxheight = self.p.boxheight
        f.write('# Edge-on galaxy box integation:  box=(%0.1f"x%.1f",x%0.1f"), effective beam=%0.4f"\n' % (boxwidth, boxheight, 3600*self.BEAM, dimgal))
        f.write('\n# l["]   b["]    Int,   Mean,   Std     \n')
        for m in range(len(self.sum)):
            for n in range(len(self.sum[m])):
                l, b = self.center[m][n]
                if self.noise_model == "Standard":
                   x = str("%.2f %.2f  %.4f %.4f %.4f \n" % (l*3600, b*3600, self.sum[m][n], self.mean[m][n], self.std[m][n]))
                else:
                   x = str("%.2f %.2f  %.4f %.4f %.4f \n" % (l*3600, b*3600, self.sum[m][n], self.mean[m][n], self.RMS))
                f.write(x)
            f.write("\n")
        f.close()
        #f.write("\n")
        #f.write("\n")
        if hasattr(self, 'p'):
           attrDic = vars(self.p)
           attrNames = attrDic.keys()
           attrNames.sort()
           #for key in attrDic.keys():
           for key in attrNames:
               if key[1:8] != "DataSet":
                  if key[0] == "_":
                     Key = key[1:]
                     tmp = str("%s = %s\n" % (Key, attrDic[key]))
                     f1.write(tmp) 
        f1.write("\n# Results of scalefit (%s)\n" % self.fname)
	f1.write(str("# effective Beam = %0.3f\"    Beam(map) = %0.3f\"  Diameter = %.1f\" \n" % (3600*self.BEAM, 3600*self.oBEAM, dimgal)))
        f1.write("\n")
        for n in range(len(self.ScaleFunct)):
            l1, func, func_err = self.ScaleFunct[n]
            l1 = nint(l1)
            f1.write(str("l = %5d   w0(%s) = %9.6g +/- %9.6g      z0(%s) = %9.6g +/- %9.6g  chi2 = %9.6g\n" % (l1, self.fname, abs(func[0]), func_err[0], self.fname, abs(func[1]), func_err[1], self.chi2[n])))

            if self.p.twocomp:
               f1.write(str("l = %5d   w1(%s) = %9.6g +/- %9.6g      z1(%s) = %9.6g +/- %9.6g  chi2 = %9.6g\n" % (l1, self.fname, abs(func[3]), func_err[3], self.fname, abs(func[4]), func_err[4], self.chi2[n])))

	    self.n = n
            self.PrintListBox(l1, func, func_err, self.chi2[n], self.p.twocomp, self.p.dimgal)
        f1.write("\n")
        f1.close()
        f2.write("\n# Fit values (%s)\n" % self.fname)
        if self.p.twocomp or self.model == "Hybrid":
	   f2.write(str("# w0,  z0, x0, w1, z1, x1, [off, slope]" ))
        else:
	   f2.write(str("# w0,  z0, x0, [off, slope]"))
        f2.write("\n")
        for n in range(len(self.FitFunct)):
            p0 = tuple(self.FitFunct[n])
            try:
               f2.write(str(len(p0)*"%g  " % p0))
               f2.write("\n")
            except:
               f2.write("bad fit data \n")
        f2.write("\n")
        f2.close()

    def PrintListBox(self, l, wfunct, wfunct_err, chi2, twocomp, dimgal):
        if not hasattr(self.parent, 'N'):
           self.create_output_list()
	text = str("# effective Beam = %0.3f\"    Beam(map) = %0.3f\"   Diameter = %.1f\"\n" % (3600*self.BEAM, 3600*self.oBEAM, dimgal)) 
	if self.n == 0: self.model.appendRow(QStandardItem(text))
        text = str("l = %-4d   w0(%s) = %-9.4g+/- %-9.4g   z0(%s) = %-9.4g+/- %-9.4g  chi2 = %-9.4g" % (l, self.fname, abs(wfunct[0]), wfunct_err[0], self.fname, abs(wfunct[1]), wfunct_err[1], chi2))
        self.model.appendRow(QStandardItem(text))
        if self.p.twocomp:
           text = str("l = %-4d   w1(%s) = %-9.4g+/- %-9.4g   z1(%s) = %-9.4g+/- %-9.4g  chi2 = %-9.4g" % (l, self.fname, abs(wfunct[3]), wfunct_err[3], self.fname, abs(wfunct[4]), wfunct_err[4], chi2))
           self.model.appendRow(QStandardItem(text))
        self.model.appendRow(QStandardItem(" "))
        self.sourcelist.scrollToBottom()
        self.sourcelist.show()

    def statistics(self, data, ldir):
        if self.bw == []:
           self.Error("no box-data available")
           return end
        self.sum = []
        self.mean = []
        self.std = []
        self.center = []
        if ldir > 0:
           lrange = range(len(self.bw)-1)
        else:
           lrange = range(len(self.bw)-2, -1, -1)
        #for i in range(len(self.bw)-1):
        for i in lrange:
            i1 = nint(min(self.bw[i], self.bw[i+1]))
            i2 = nint(max(self.bw[i], self.bw[i+1]))
            x = (i1+i2-1)/2.0
            asum = []
            mean = []
            std = []
            center = []
            for j in range(len(self.bh)-1):
                j1 = nint(min(self.bh[j], self.bh[j+1]))
                j2 = nint(max(self.bh[j], self.bh[j+1]))
                y = (j1+j2-1)/2.0 
                box = data[j1:j2, i1:i2]
                mask = ~np.isnan(box)
                if list(mask.ravel()).count(True) > 5:
                   asum.append(np.sum(box[mask])/self.beam)
                   mean.append(np.mean(box[mask]))
                   #mean.append(np.median(box[mask]))
                   mean_width = nanmean(box, axis=0)
                   msk = ~np.isnan(mean_width)
                   std.append(np.std(mean_width[msk]))
                   #std.append(np.std(box[mask]))
                   center.append(self.parent.get_plot_coordinates(x, y))
            self.sum.append(asum)
            self.mean.append(mean)
            self.std.append(std)
            self.center.append(center)
        try:
           self.RMS = np.nanmin(np.ravel(self.std))
        except:
           self.RMS = self.p.rms
 
    def fwhm2sigma(self, beam):
        return 3600*beam/(2.0*np.sqrt(2.0*np.log(2.0)))
        
    def fwhm2sigma_old(self, header):
        fwhm = 3600*np.sqrt(header['BMAJ']*header['BMIN'])
        return fwhm/(2.0*np.sqrt(2.0*np.log(2.0)))
        
    def scalefit(self, weight, model, baseline):
        def integrand(x, x0, sig, h):
            return np.exp(-((x-x0)**2)/sig) / np.cosh(x/h)**2

        def convolv(x0, sig, h):
            return quad(integrand, -5*h, 5*h, args=(x0, sig, h))[0]

        def SecHsq(Z, w0, z0, Z0, off=0.0, slope=0.0):
            if self.iter % 10 == 0: 
               self.progress.showMessage(_(str("Interation %d of stripe %d" % (self.iter, self.stripe))))
            self.iter += 1
            if self.iter > 1200 or self.parent.STOP:
               self.stop_text = "program stopped, no solution found"
               self.progress.showMessage(_(self.stop_text), 5000)
               self.parent.STOP = True
               return 0
            z = Z - Z0
            s = 1.0*self.sigma
            sf = s*np.sqrt(2.0*np.pi)
            if self.ioff and self.islope:
               return off + slope*z + w0/sf*sech2(z, 2*s*s, z0)
            elif self.islope:
               return off*z + w0/sf*sech2(z, 2*s*s, z0)
            elif self.ioff:
               return off + w0/sf*sech2(z, 2*s*s, z0)
            else:
               return w0/sf*sech2(z, 2*s*s, z0)

        def SecHsq2(Z, w0, z0, Z0, w1, z1, off=0.0, slope=0.0):
            if self.iter % 10 == 0: 
               self.progress.showMessage(_(str("Interation %d of stripe %d" % (self.iter, self.stripe))))
            self.iter += 1
            if self.iter > 1200 or self.parent.STOP:
               self.stop_text = "program stopped, no solution found"
               self.progress.showMessage(_(self.stop_text), 5000)
               self.parent.STOP = True
               return 0
            z = Z - Z0
            s = 1.0*self.sigma
            sf = s*np.sqrt(2.0*np.pi)
            if self.ioff and self.islope:
               return off + slope*z + w0/sf*sech2(z, 2*s*s, z0) + w1/sf*sech2(z, 2*s*s, z1)
            elif self.islope:
               return off*z + w0/sf*sech2(z, 2*s*s, z0) + w1/sf*sech2(z, 2*s*s, z1)
            elif self.ioff:
               return off + w0/sf*sech2(z, 2*s*s, z0) + w1/sf*sech2(z, 2*s*s, z1)
            else:
               return w0/sf*sech2(z, 2*s*s, z0) + w1/sf*sech2(z, 2*s*s, z1)

        def Exponential(Z, w0, z0, Z0, off=0.0, slope=0.0):
            z = Z - Z0
            s = 1.0*self.sigma
            sz = z*z / (2.0*s*s)
            szp = (s*s + z*z0) / (np.sqrt(2.0)*s*z0)
            szm = (s*s - z*z0) / (np.sqrt(2.0)*s*z0)
            if self.ioff and self.islope:
               return off + slope*z + w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
            elif self.islope:
               return off*z + w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
            elif self.ioff:
               return off + w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
            else:
               return w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))

        def Exponential2(Z, w0, z0, Z0, w1, z1, off=0.0, slope=0.0):
            z = Z - Z0
            s = 1.0*self.sigma
            sz = z*z / (2.0*s*s)
            szp = (s*s + z*z0) / (np.sqrt(2.0)*s*z0)
            szm = (s*s - z*z0) / (np.sqrt(2.0)*s*z0)
            szp1 = (s*s + z*z1) / (np.sqrt(2.0)*s*z1)
            szm1 = (s*s - z*z1) / (np.sqrt(2.0)*s*z1)
            if self.ioff and self.islope:
               return off + slope*z + w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp)) + w1/2.0 * np.exp(-sz) * (np.exp(szm1*szm1)*erfc(szm1) + np.exp(szp1*szp1)*erfc(szp1))
            elif self.islope:
               return off*z + w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp)) + w1/2.0 * np.exp(-sz) * (np.exp(szm1*szm1)*erfc(szm1) + np.exp(szp1*szp1)*erfc(szp1))
            elif self.ioff:
               return off + w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp)) + w1/2.0 * np.exp(-sz) * (np.exp(szm1*szm1)*erfc(szm1) + np.exp(szp1*szp1)*erfc(szp1))
            else:
               return w0/2.0 * np.exp(-sz) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp)) + w1/2.0 * np.exp(-sz) * (np.exp(szm1*szm1)*erfc(szm1) + np.exp(szp1*szp1)*erfc(szp1))

        def Gaussian(Z, w0, z0, Z0, off=0.0, slope=0.0):
            z = Z - Z0
            s = 1.0*self.sigma
            sz = 2*s*s + z0*z0
            if self.ioff and self.islope:
               return off + slope*z + w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz)
            elif self.islope:
               return off*z + w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz)
            elif self.ioff:
               return off + w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz)
            else:
               return w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz)

        def Gaussian2(Z, w0, z0, Z0, w1, z1, off=0.0, slope=0.0):
            z = Z - Z0
            s = 1.0*self.sigma
            sz = 2*s*s + z0*z0
            sz1 = 2*s*s + z1*z1
            if self.ioff and self.islope:
               return off + slope*z + w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz) + w1*(z1/np.sqrt(sz1)) * np.exp(-(z*z)/sz1)
            elif self.islope:
               return off*z + w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz) + w1*(z1/np.sqrt(sz1)) * np.exp(-(z*z)/sz1)
            elif self.ioff:
               return off + w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz) + w1*(z1/np.sqrt(sz1)) * np.exp(-(z*z)/sz1)
            else:
               return w0*(z0/np.sqrt(sz)) * np.exp(-(z*z)/sz) + w1*(z1/np.sqrt(sz1)) * np.exp(-(z*z)/sz1)

        def Hybrid2(Z, wg, zg, Z0, we, ze, off=0.0, slope=0.0):
            z = Z - Z0
            s = 1.0*self.sigma
            sze = z*z / (2.0*s*s)
            szp = (s*s + z*ze) / (np.sqrt(2.0)*s*ze)
            szm = (s*s - z*ze) / (np.sqrt(2.0)*s*ze)
            szg = 2*s*s + zg*zg
            if self.ioff and self.islope:
               return off + slope*z + wg*(zg/np.sqrt(szg)) * np.exp(-(z*z)/szg) + we/2.0 * np.exp(-sze) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
            elif self.islope:
               return off*z + wg*(zg/np.sqrt(szg)) * np.exp(-(z*z)/szg) + we/2.0 * np.exp(-sze) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
            elif self.ioff:
               return off + wg*(zg/np.sqrt(szg)) * np.exp(-(z*z)/szg) + we/2.0 * np.exp(-sze) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
            else:
               return wg*(zg/np.sqrt(szg)) * np.exp(-(z*z)/szg) + we/2.0 * np.exp(-sze) * (np.exp(szm*szm)*erfc(szm) + np.exp(szp*szp)*erfc(szp))
   

        def scale_fit(f, x, y, p0, sig):
            xtol = 1.49012e-08
            Error = True
            #self.chi2 = 99999999999999.0
            self.iter = 0
            while Error:
                  self.progress.showMessage(_("stop program with ^C"), 5000)
                  #if 1:
                  try:
                     result = curve_fit(f, x, y, p0=p0, sigma=sig, xtol=xtol, full_output=True)
                     (popt, pcov, infodict, errmsg, ier) = result
                     Error = False
                  except:
                  #else:
                     Error = True
                     xtol *= 2.0
                     if xtol > self.RMS:
                        return
            if self.parent.STOP:
               self.progress.showMessage(_(self.stop_text), 5000)
               self.parent.STOP = False
               return [], [], self.stop_text
            return popt, pcov, infodict

        if baseline == "Full":
           self.ioff = True
           self.islope = True
        elif baseline == "Slope":
           self.ioff = False
           self.islope = True
        elif baseline == "Offset":
           self.ioff = True
           self.islope = False
        else:
           self.ioff = False
           self.islope = False
        Hybrid = Hybrid2
        if model == "Hybrid": self.p.twocomp = True
        self.fname = model
        wfunct = eval(model)
        wfunct2 = eval(model + "2")
        sech2 = np.vectorize(convolv)
        l = 0.0
        self.ScaleFunct = []
        self.FitFunct = []
        self.dy = []
        self.chi2 = []
        self.parent.fig = pyplot.figure("Galaxy scale fit")
        if hasattr(self, 'Nplots'): del self.Nplots
        self.progress = self.parent.imagewidget.Progress
        self.progress.showMessage(_("stop program with ^C"), 5000)
        for m in range(len(self.sum)):
            self.stripe = m+1
            xdata = []
            ydata = []
            sigma = []
            for n in range(len(self.sum[m])):
                l, b = self.center[m][n]
                if l > 180.0: l -= 360.0
                if np.abs(self.mean[m][n]) > self.rms:
                   xdata.append(b)
                   ydata.append(self.mean[m][n])
                   if self.noise_model == "Standard":
                      sigma.append(self.std[m][n])
                   else:
                      sigma.append(self.RMS)
            dy = np.array(sigma)
            if weight == "Both":
               #sig = np.log(np.array(sigma)) / np.log(np.nanmax(sigma))
               sig = np.array(sigma) / np.nanmax(sigma)
            elif weight == "Lower":
               sig = np.where(np.array(xdata) >= 0.0, 10.0, 1.0)
            elif weight == "Upper":
               sig = np.where(np.array(xdata) <= 0.0, 10.0, 1.0)
            elif weight == "No":
               sig = None
            xdata = 3600*np.array(xdata)
            ydata = np.array(ydata)
            # calculate beam with respect to geometrical projection
	    if hasattr(self, "galaxy_radius"):
               d = self.center[m][0][0]
               if d > 180: d -= 360.0
               dd = np.sqrt(max(0.0, self.galaxy_radius**2 - (3600*d)**2)) / self.galaxy_radius
               self.sigma = self.sigmabeam + (self.sigmaIncl - self.sigmabeam)* dd
	    else:
	       self.sigma = self.sigmabeam
            try:
            #if 1:
               if self.p.twocomp or model == "Hybrid":
                  if self.ioff and self.islope:
                     pg = (max(ydata), self.sigma, 0.0, max(ydata)/2., 15*self.sigma, 0.0, 0.0)
                  elif self.ioff or self.islope:
                     pg = (max(ydata), self.sigma, 0.0, max(ydata)/2., 15*self.sigma, 0.0)
                  else:
                     pg = (max(ydata), self.sigma, 0.0, max(ydata)/2., 15*self.sigma)
                  popt, pcov, info = scale_fit(wfunct2, xdata, ydata, pg, sig)
               else:
                  if self.ioff and self.islope:
                     pg = (max(ydata), self.sigma, 0.0, 0.0, 0.0)
                  elif self.ioff or self.islope:
                     pg = (max(ydata), self.sigma, 0.0, 0.0)
                  else:
                     pg = (max(ydata), self.sigma, 0.0)
                  popt, pcov, info = scale_fit(wfunct, xdata, ydata, pg, sig)
               if type(info) == type(" "):
                  self.Error(info)
                  return
               perr = np.sqrt(abs(np.diag(pcov)))
            except:
            #else:
               self.Error("no fit result,\nchange input values")
               popt = []
               self.show = True
               if hasattr(self, 'Nplots'): del self.Nplots
               #self.plot(xdata, ydata, dy, popt, nint(l*3600), self.p)
               return
            self.wfunct = wfunct
            self.wfunct2 = wfunct2
            self.ScaleFunct.append((3600*l, popt, perr))
            self.FitFunct.append([nint(3600*l)] + popt)
            self.chi2.append(self.reduced_chi_sq(info, sigma, len(ydata)-len(popt)))
            ############print self.reduced_chi_sq(info, sigma, len(ydata)-len(popt)),
            if self.p.twocomp:
               yfunc = self.wfunct2(xdata, *popt)
            else:
               yfunc = self.wfunct(xdata, *popt)
            #self.chi2.append(chisquare(ydata, yfunc, ddof=(len(ydata)-len(popt)))[0])
            if m == len(self.sum)-1: self.show = True
            else: self.show = False
            self.plot(xdata, ydata, dy, popt, nint(l*3600), self.p)
 
    def reduced_chi_sq(self, info, sigma, N):
        res = info['fvec']
        chi2 = (res/sigma)**2
        return chi2.sum() / max(1, N)

    def plot(self, x, y, dy, pg, l, p):
        plog = p.log
        if pg == []:
           pyplot.figure(1)
           try:
              del self.Nplots
              pyplot.show(mainloop=False)
           except: pass
           return
        if not hasattr(self, 'Nplots'):
           self.Nplots = 1
        else:
           self.Nplots += 1
        N = 1*self.Nplots
        #N1 = int(self.p.xnum+1)/2
        N1 = p.ngraph
        pyplot.subplot(1, N1, self.Nplots)
        xx = np.arange(float(x[0]), float(x[-1]), 1.0)
        if self.p.twocomp:
           yg = self.wfunct2(xx, *pg)
        else:
           yg = self.wfunct(xx, *pg)
        #pyplot.plot(x, y, "r+", label="Data")
        if plog:
           dy = np.where(y-dy > self.RMS, dy, y-0.1) # cut extreme error values
           pyplot.errorbar(x, y, dy, "k+", label="Data")
	   #try:
           #   maskg = yg > np.nanmin(y[mask])
	   #except:
           #   maskg = mask
           #pyplot.semilogy(xx[maskg], yg[maskg], "r-", label=self.fname)
           pyplot.semilogy(xx, yg, "r-", label=self.fname)
        else:
           pyplot.errorbar(x, y, dy, "k+", label="Data")
           pyplot.plot(xx, yg, "r-", label=self.fname)
        if self.Nplots == 1:
           #pyplot.legend(pos="TR") 
           try:
              pyplot.title(str("Scale-Fit: %s@%.2fGHz" % (self.m1.header['OBJECT'], self.m1.header['CRVAL3']*1.e-9)))
           except:
              pyplot.title(str("Scale-Fit: %s" % (self.m1.header['OBJECT'])))
        #pyplot.xlabel(str('z-distance ["] at lon=%d"' % l))
        pyplot.xlabel(str('z["] at x=%d"' % l))
        pyplot.ylabel("intensity")

        if self.show: 
           if hasattr(self, 'Nplots'): del self.Nplots
           pyplot.show(mainloop=False)
        return

        sig= -1
        f = open(str("box%2.2d" % N), "w")
        for i in range(len(x)):
            #r = abs(x[i])
            r = x[i]
            text = ""
            if np.sign(r) != sig:
               text = "\n"
               sig = np.sign(r)
            if self.p.twocomp:
               yg = self.wfunct2(r, *pg)
            else:
               yg = self.wfunct(r, *pg)
            if y[i] > self.RMS and yg > self.RMS and ye > self.RMS:
               text += str("%f  %f  %f  %f  %f  %f\n" % (r, np.log(y[i]), np.log(yg), np.log(ye), yg-y[i], ye-y[i]))
               #print r, pg[0]*np.exp(-r*r/(2*pg[1]*pg[1])) + pg[3]*np.exp(-r*r/(2*pg[4]*pg[4])),\
               #         pe[0]*np.exp(-abs(r)/pe[1]) + pe[2]*np.exp(-abs(r)/pe[3])
               f.write(text)
        f.close()
 
    def function(self, m, p):
        self.p = p
	if not hasattr(p, 'rms'):
           p.rms = 0.0
        if not hasattr(p, 'noise_model'):
           self.noise_model = "Standard"
        else:
           self.noise_model = p.noise_model
        if not hasattr(p, 'incl'):
           p.incl = 90.0
        if p.incl < 70.0:
           self.Error(str("Inclination < 70.0 degree will not work!"))
           return [], p
        if not hasattr(p, 'weight'):
           p.weight = 'No'
        if not hasattr(p, 'cursor'):
           p.cursor = False
        p.factor = 1000.0
        if np.nanmax(m.data) < 0.1:
           m.data *= p.factor
        if not 'BMAJ' in m.header or not 'BMIN' in m.header:
           self.Error("BMAJ and BMIN not found in header, please define the FWHM")
           if hasattr(self, 'Nplots'): del self.Nplots
           return [], p
        self.beam = 2*np.pi/(8*np.log(2.0)) * (m.header['BMAJ'] * m.header['BMIN']) / abs(m.header['CDELT1'] * m.header['CDELT2'])
        rows, cols = m.data.shape
        m1 = self.rotate(m, p.posang)
        #l = (len(range(25,rows-25))/2.0)
        if m1.data == []:
           return [], p
        if p.incl < 90.0:
           self.BEAM = self.deincl(m1, p.incl, p.rms, p.dimgal)
        else:
           self.BEAM = m1.header['BMAJ']
	self.oBEAM = m1.header['BMAJ']
        m1.header["BEAM"] = (self.BEAM, "inclination corrected beam")
	#return m1, p
        #if p.rebin > 1: 
        #   m1 = self.rebin(m1, p.rebin)
        self.parent.del_polygon()
        self.parent.poly_visible = True
        if self.update:
           self.parent.add_object(m1)
           self.parent.refresh_plot()
        self.m1 = m1
        self.sigmabeam = self.fwhm2sigma(m.header['BMAJ'])
        self.sigmaIncl = self.fwhm2sigma(self.BEAM)
        if p.cursor:
           self.get_cursor()
           return [], p
        self.rms = p.rms
        self.overlay(m1, p)
        self.statistics(m1.data, m1.header['CDELT1'])
        self.scalefit(p.weight, p.model, p.baseline)
        self.printout(p.outfile, p.dimgal)
        return [], p