Ewindow.py 17.8 KB
Newer Older
1
# -*- coding: iso-8859-15 -*-
2 3
import Tkinter as tk
from PTE import *
4
from pylab import *
5
from layers import *
6
from profile import *
7 8
from numpy import zeros
import os
9
import tkFileDialog
10
import shutil
11
import sys
12 13 14
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot
15

16 17
##############################################################################
# Control variables and lists
18
Edict = dict()
19
Ebuttons = list()
20
Labentrys = list()
21
Frames = list()
22
Control = dict(drawing=False, shifting=False, scaling=False, x=0., y=0.)
Matheus Müller's avatar
Matheus Müller committed
23
i = 0
24 25
Econtrol = 0

26
##############################################################################
27
# Element callback
28 29 30
def elem_callback(x, edict , ebutton, t):
    global Labentrys, Econtrol
    PTable(edict[x] , ebutton[x], Labentrys, t)
31 32 33

##############################################################################
# Element selection
34
def elem_select(i, button, grafico, f, a, t):
35

36
    global Econtrol, Edict, Labentrys
37
    button[Econtrol]['relief']='raised'
38
    Econtrol = i
39 40
    button[i]['relief']='sunken'

41 42 43 44 45 46
    Labentrys[0].configure(text = '%s' %Edict[i]['name'])
    Labentrys[1].configure(text = 'Mass - %f' %Edict[i]['mass'])
    Labentrys[2].configure(text = 'Z - %f' %Edict[i]['Z'])
    Labentrys[3].configure(text = 'Symbol - %s' %Edict[i]['symbol'])
    Labentrys[4].configure(text = 'Line Shape α - %f' %Edict[i]['LineShape'])
    Labentrys[5].configure(text = 'Max Depht - %f' %Edict[i]['profundidademax'])
47

48 49
    for j in arange(6,12):
        Labentrys[j].delete (0, "end")
50

51 52 53 54 55 56
    Labentrys[6].insert(0, Edict[int(Econtrol)]['name'])
    Labentrys[7].insert(0, Edict[int(Econtrol)]['mass'])
    Labentrys[8].insert(0, int(Edict[int(Econtrol)]['Z']))
    Labentrys[9].insert(0, Edict[int(Econtrol)]['symbol'])
    Labentrys[10].insert(0, Edict[int(Econtrol)]['LineShape'])
    Labentrys[11].insert(0, Edict[int(Econtrol)]['profundidademax'])
57

58 59
    grafico.set_xdata(Edict[i]['dist'].axisdepth())
    grafico.set_ydata(Edict[i]['dist'].data)
60
    
61
    t.set_text('%s' %Edict[i]['symbol'] + ' Distribution')
62 63
    a.set_ylim(0,1)
    a.set_xlim(0,Edict[int(Econtrol)]['profundidademax'])
64 65
    f.canvas.draw()
    
66
##############################################################################
67
##############################################################################
68
# Init
69
def ewin_build(window, OFlabentries, mainwindow, calcbutton, distvar, modevar, Labelframe, grafico, f, a):
70
    t = f.suptitle('Hf'  + ' Distribution')
71

72 73
##############################################################################
# Element addition
74 75
    def create():
        global i, Edict, Ebuttons
76
        Edict[i]=dict(name="New Element",symbol="Hf",mass=178.,Z=72,dist=profile(200,0.01),LineShape=200.,profundidademax=2.)
77 78
        Ebuttons.insert(i, tk.Button(Eframe, text=i, width=1, height=1, command = lambda i=i : elem_select(i,Ebuttons,grafico,f,a,t)) )
        Ebuttons[i].grid(row = ((len(Ebuttons)-1)%6), column = int(math.floor((len(Ebuttons)-1)/6)))
79
        i = i+1
80

81 82
##############################################################################
# Element deletion
83
    def remove():
84
        global i, Edict, Ebuttons, Econtrol
85
        if i > 1:
86
            i = i-1
87 88 89
            for p in range(Econtrol+1,i+1):
                Edict[p-1] = Edict[p]
                Ebuttons[p-1].configure(text = Ebuttons[p]['text'])
90

91 92 93
            del Edict[i]
            Ebuttons[i].destroy()
            del Ebuttons[i]
94

95 96 97
            if Econtrol == i:
                Econtrol = Econtrol -1
                Ebuttons[Econtrol]['relief']='sunken'
98
        elem_select(0, Ebuttons, grafico, f, a, t)
99

100
##############################################################################
101 102
# Element Frames

103
    Labelprop = tk.LabelFrame(window, text = 'Properties', relief='raised', bd=2)
104
    Labelprop.pack(side = 'left')
105
    Label1 = tk.LabelFrame(window, text = 'Elements', relief='raised', bd=2)
106
    Label1.pack(side = 'left') 
107
    # For Button Creation
108 109
    Eframe = tk.Canvas(Label1)
    Eframe.pack(fill='both',expand=0)
110

111 112 113
##############################################################################
# Init
    create()
114
    
115 116 117
##############################################################################
# Properties

118
    global Econtrol, Edict, Labentrys
119
    def update(i):
120 121 122 123 124 125 126 127 128 129 130 131
        Edict[i]['name'] = str(Labentrys[6].get())
        Labentrys[0].configure(text = '%s' %Edict[i]['name'])
        Edict[i]['mass'] = float(Labentrys[7].get())
        Labentrys[1].configure(text = 'Mass - %f' %Edict[i]['mass'])
        Edict[i]['Z'] = float(Labentrys[8].get())
        Labentrys[2].configure(text = 'Z - %f' %Edict[i]['Z'])
        Edict[i]['symbol'] = str(Labentrys[9].get())
        Labentrys[3].configure(text = 'Symbol - %s' %Edict[i]['symbol'])
        Edict[i]['LineShape'] = float(Labentrys[10].get())
        Labentrys[4].configure(text = 'Line Shape α - %f' %Edict[i]['LineShape'])
        Edict[i]['profundidademax'] = float(Labentrys[11].get())
        Labentrys[5].configure(text = 'Max Depht - %f' %Edict[i]['profundidademax'])
132
        Edict[i]['dist'].resize(int(100*Edict[i]['profundidademax']))
133
        elem_select(i,Ebuttons,grafico,f,a,t)
134
        
135 136 137 138 139 140 141 142 143
    for i in range(3):
        Frames.insert(i, tk.Frame(Labelprop) )

    Frames[0].pack(side='left')
    Frames[1].pack(side='top')
    Frames[2].pack(side='right')

    for i in arange(3, 5):
        Frames.insert(i, tk.Frame(Frames[0]) )
144

145 146
    Frames[3].pack(side='left')
    Frames[4].pack(side='right')
147

148 149 150 151 152 153 154 155 156
    for i in arange(5, 7):
        Frames.insert(i, tk.Frame(Frames[1]) )

    Frames[5].pack(side='left')
    Frames[6].pack(side='right')
    Labeldist = tk.LabelFrame(Frames[5], text = 'Distribution', relief='raised', bd=2)
    Labeldist.pack(side = 'bottom') 
    Frames.insert(7, tk.Frame(Labeldist) )
    Frames[7].pack(side='top')
157

158 159 160 161 162 163 164
    # Label // Entries numbers:
    # 0 // 6 = Name
    # 1 // 7 = Mass
    # 2 // 8 = Z (Atomic number)
    # 3 // 9 = Symbol
    # 4 // 10 = Line shape
    # 5 // 11 = Max Depht
Matheus Müller's avatar
Matheus Müller committed
165
    ## 13 // 12 = Resonance energy (For RNA only)
166 167 168 169 170 171
    Labentrys.insert(0, tk.Label(Frames[3], width=23, pady=2, text='%s' %Edict[int(Econtrol)]['name']) )
    Labentrys.insert(1, tk.Label(Frames[3], width=23, pady=2, text='Mass - %f' %Edict[int(Econtrol)]['mass']) )
    Labentrys.insert(2, tk.Label(Frames[3], width=23, pady=2, text='Z - %f' %Edict[int(Econtrol)]['Z']) )
    Labentrys.insert(3, tk.Label(Frames[3], width=23, pady=2, text= 'Symbol - %s' %Edict[int(Econtrol)]['symbol']) )
    Labentrys.insert(4, tk.Label(Frames[3], width=23, pady=2, text='Line Shape α - %f' %Edict[int(Econtrol)]['LineShape']) )
    Labentrys.insert(5, tk.Label(Frames[3], width=23, pady=2, text='Max Depht - %f' %Edict[int(Econtrol)]['profundidademax']) )
172

173 174
    for j in arange(6, 13):
        Labentrys.insert(j, tk.Entry(Frames[4], width=17) )
Matheus Müller's avatar
Matheus Müller committed
175 176 177

    Labentrys.insert(13, tk.Label(Frames[3], width=23, pady=2, text='Resonance energy') )

178 179
    for j in range(14):
        Labentrys[j].pack()
180

181
    # Declaration of interpolation and distribution method variables
182
    methodvar = tk.StringVar()
183
    methodvar.set('step')
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
##############################################################################
# Distribution Hotkeys                                                       #
##############################################################################

    def cursor_draw_click(event):
        global Econtrol
        if event.inaxes != a.axes: return
        if event.button == 1:
            Control['drawing']=True
        elif event.button == 2:
            Control['scaling']=True
        elif event.button == 3:
            Control['shifting']=True
        Control['x'] = float(event.xdata)
        Control['y'] = float(event.ydata)
        if Control['y'] > 1:
            Control['y'] = 1.

    def cursor_draw_motion(event):
        global Econtrol
        if event.inaxes != a.axes: return
        if Control['drawing']:
            Edict[Econtrol]['dist'].drawline(Control['x'], float(event.xdata), Control['y'], float(event.ydata))
            Control['x'] = float(event.xdata)
            Control['y'] = float(event.ydata)
        elif Control['scaling']:
            Edict[Econtrol]['dist'].soma(float(event.ydata) - Control['y'])
            Control['y'] = float(event.ydata)
        elif Control['shifting']:
            Edict[Econtrol]['dist'].shiftx(Control['x'],float(event.xdata))
            Control['x'] = float(event.xdata)

        grafico.set_xdata(Edict[Econtrol]['dist'].axisdepth())
        grafico.set_ydata(Edict[Econtrol]['dist'].data)
        f.canvas.draw()

    def cursor_draw_release(event):
        Control['drawing']=False
        Control['scaling']=False
        Control['shifting']=False

    def abrupt(event):pass

    def smooth(event): # N funciona
        global Econtrol
        Edict[Econtrol]['dist'].smooth(5)
        f.canvas.draw()

    def normalize(event):
        global Econtrol, i 
        Normalizator = list()
        for j in range(i):
            for k in range(Edict[j]['dist'].size):
                if k >= len(Normalizator):
                    Normalizator.insert(k,0.)
                Normalizator[k] = Normalizator[k] + Edict[j]['dist'].data[k]
        
        for j in range(i):
            for k in range(Edict[j]['dist'].size):
                if Normalizator [k] > 0:
                    Edict[j]['dist'].data[k] = Edict[j]['dist'].data[k]/Normalizator[k]
        f.canvas.draw()
        del Normalizator

    def clear(event):
        global Econtrol
        Edict[Econtrol]['dist'].clear()
        f.canvas.draw()

    f.canvas.mpl_connect('button_press_event', cursor_draw_click)
    f.canvas.mpl_connect('motion_notify_event', cursor_draw_motion)
    f.canvas.mpl_connect('button_release_event', cursor_draw_release)

    mainwindow.bind_all("<Alt-KeyPress-a>", abrupt)
    mainwindow.bind_all("<Alt-KeyPress-s>", smooth)
    mainwindow.bind_all("<Alt-KeyPress-n>", normalize)
    mainwindow.bind_all("<Alt-KeyPress-c>", clear)

263

264 265
##############################################################################
#                                                                            #
266 267 268
##############################################################################
# Load/Save sample
    def LOADSAMPLE():
269 270 271
        global i, Econtrol
        arquivo = tkFileDialog.askopenfile()
        for n in arange(9,18):
272
            OFlabentries[n].delete(0,'end')
273
            OFlabentries[n].insert(0,float(arquivo.readline()))
274 275
        for n in arange(21,25):
            OFlabentries[n].delete(0,'end')
276
            OFlabentries[n].insert(0,float(arquivo.readline()))
277 278 279 280 281 282 283
        fil = loadtxt(arquivo.name + '.elm', dtype="string")
        els = fil[:, 0]
        eln = fil[:, 1]
        elm = fil[:, 2]
        elz = fil[:, 3]
        LSs = fil[:, 4]
        eld = fil[:, 5]
284 285 286 287 288 289
        Edict.clear()
        for n in range(len(Ebuttons)):
            Ebuttons[n].destroy()
        del Ebuttons[:]
        i = 0
        Econtrol = 0
290
        for n in range(len(els)):
291
            create()           
292 293 294 295 296 297
            Edict[n]['LineShape'] = float(LSs[n])
            Edict[n]['symbol'] = str(els[n])
            Edict[n]['name'] = str(eln[n])
            Edict[n]['mass'] = float(elm[n])
            Edict[n]['Z'] = float(elz[n])
            Edict[n]['profundidademax'] = float(eld[n])
298
            Edict[n]['dist'].data = list(loadtxt(arquivo.name + '-' + Edict[n]['symbol']+'.prof', dtype="float"))
299
            Ebuttons[n]['text'] = str(els[n])
300 301
            #shutil.copy(arquivo.name + '-' + Edict[n]['symbol'] + '.dat' , Edict[n]['symbol']+'.dat')
            #shutil.copy(arquivo.name + '-' + Edict[n]['symbol'] + '.prof' , Edict[n]['symbol']+'.prof')
302
        elem_select(0,Ebuttons,grafico, f, a, t)
303
        arquivo.close()
304 305

    def SAVESAMPLE():
306 307 308 309
        config = tkFileDialog.asksaveasfile(mode='w')
        elist = open(config.name + '.elm', 'w+')
        for k in arange(9,18):
            config.write( (OFlabentries[k].get())+'\n' )
310
        for j in arange(21,25):
311 312
            config.write( (OFlabentries[j].get())+'\n' )
        config.write( '##############################################################################\n' )
313
        config.write( '# dƐ/dx\n# dω²/dx\n# θ out\n# θ in\n# FWHM\n# E min\n# E max\n# E step\n# Depth step\n# Ion energy\n# Ion mass\n# Ion Z\n # Dose\n' )
314
        for n in range(len(Edict)):
315 316 317 318
            elist.write(Edict[n]['symbol']+' ')
            elist.write(Edict[n]['name']+' ')
            elist.write(str(Edict[n]['mass'])+' ')
            elist.write(str(Edict[n]['Z'])+' ')
319
            elist.write(str(Edict[n]['LineShape'])+' ')
320
            elist.write(str(Edict[n]['profundidademax'])+'\n')
321 322 323 324 325 326
            temp = open(config.name  + '-' + Edict[n]['symbol']+'.prof', 'w+')
            for j in range(len(Edict[n]['dist'].data)):
                temp.write(str(Edict[n]['dist'].data[j])+'\n')
            temp.close()
            #shutil.copy(Edict[n]['symbol']+'.prof', config.name  + '-' + Edict[n]['symbol'] + '.prof')
            #shutil.copy(Edict[n]['symbol']+'.dat', config.name  + '-' + Edict[n]['symbol'] + '.dat')
327
            shutil.copy('temp.sim', config.name  + '.sim')
328
        elist.close()
329
        config.close()
330

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
##############################################################################
# Menu
    def donothing():
        return 0

    menubar = tk.Menu(mainwindow, bg='grey', relief='flat', bd=0)
    filemenu = tk.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Simulate", command=lambda i=int(Econtrol) :calcbutton.invoke())
    filemenu.add_separator()
    filemenu.add_command(label="Exit", command=sys.exit)
    menubar.add_cascade(label="File", menu=filemenu)

    samplemenu = tk.Menu(menubar, tearoff=0)
    samplemenu.add_command(label="Load Sample", command=lambda i=int(Econtrol) :LOADSAMPLE())
    samplemenu.add_command(label="Save Sample", command=lambda i=int(Econtrol) :SAVESAMPLE())
    menubar.add_cascade(label="Samples", menu=samplemenu)

    helpmenu = tk.Menu(menubar, tearoff=0)
    helpmenu.add_command(label="Help!", command=donothing)
    helpmenu.add_command(label="About...", command=donothing)
    menubar.add_cascade(label="Help", menu=helpmenu)
    mainwindow.config(menu=menubar)

354 355 356
##############################################################################
# Buttons

357
    butPTE = tk.Button(Frames[5], text='Select from PTE', bd=1, width=15, command=lambda i=i :elem_callback(Econtrol,Edict,Ebuttons,t), pady='1' )
358
    butPTE.pack()
359
    BUpdate = tk.Button(Frames[5], text ='Update properties', command=lambda i=int(Econtrol) :update(Econtrol), width=15)
360
    BUpdate.pack()
361 362 363 364
    but = tk.Button(Frames[5], command=create, text='Add element ->', bd=1, height=1,width=15, pady='1')
    but.pack()
    butrmv = tk.Button(Frames[5], command=remove, text='<- Remove element', bd=1, height=1,width=15, pady='1')
    butrmv.pack()
365

366
##############################################################################
367 368 369
# Distribution
 
    def changestate():
370 371 372 373 374 375 376 377 378 379 380
        BLayer['state']='normal'
        OFlabentries[9]['state']='disabled'
        OFlabentries[10]['state']='disabled'
        for i in arange(6, 12):
            Labentrys[i]['state']='disabled'
        but['state']='disabled'
        butrmv['state']='disabled'
        butPTE['state']='disabled'
        BUpdate['state']='disabled'
        for n in arange(0, len(Ebuttons)):
            Ebuttons[n]['state'] = 'disabled'
Matheus Müller's avatar
Matheus Müller committed
381
        distvar.set(0)   # Foi preciso forcar isso pois o radiobutton nao o fazia
382 383 384 385 386 387 388 389 390 391 392 393 394

    def changestate2():
        BLayer['state']='disabled'
        OFlabentries[9]['state']='normal'
        OFlabentries[10]['state']='normal'
        for i in arange(6, 12):
            Labentrys[i]['state']='normal'
        but['state']='normal'
        butrmv['state']='normal'
        butPTE['state']='normal'
        BUpdate['state']='normal'
        for n in arange(0, len(Ebuttons)):
            Ebuttons[n]['state'] = 'normal'
Matheus Müller's avatar
Matheus Müller committed
395
        distvar.set(1)    # Foi preciso forcar isso pois o radiobutton nao o fazia
396 397

    def call_layers():
Matheus Müller's avatar
Matheus Müller committed
398
        layers()    # funcao de layers.py
399 400

    # By Layers
401
    BLayer = tk.Button(Labeldist, text ='Open Layers', command = lambda i = int(Econtrol) : call_layers(), width=15, pady='1')
402 403
    BLayer.pack()
    # Distribution methods
404
    RLay = tk.Radiobutton(Frames[7], text="Layers", command=lambda i=int(Econtrol) :changestate(), variable=distvar, value=0)
405
    RLay.pack(side='left')
406
    RDra = tk.Radiobutton(Frames[7], text="Drawing", command=lambda i=int(Econtrol) :changestate2(), variable=distvar, value=1)
407
    RDra.pack(side='right')
408

409 410 411 412
##############################################################################
# Experiment variations

    def changemode():
413 414 415 416 417 418 419
        for n in range(len(Ebuttons)):
            Ebuttons[n]['state']='normal'
        but['state'] = 'normal'
        butrmv['state'] = 'normal'
        butPTE['state'] = 'normal'
        RLay['state'] = 'normal'
        Labentrys[12]['state'] = 'disabled'
Matheus Müller's avatar
Matheus Müller committed
420
        modevar.set(0)   # Foi preciso forcar isso pois o radiobutton nao o fazia
421 422 423

    def changemode2():
        RDra.invoke()
424
        elem_select(0,Ebuttons,grafico, f, a, t)
425 426 427 428 429 430
        but['state'] = 'disabled'
        butrmv['state'] = 'disabled'
        RLay['state'] = 'disabled'
        Labentrys[12]['state'] = 'normal'
        for n in arange(1, len(Ebuttons)):
            Ebuttons[n]['state'] = 'disabled'
Matheus Müller's avatar
Matheus Müller committed
431
        modevar.set(1)   # Foi preciso forcar isso pois o radiobutton nao o fazia
432

433
    Rions = tk.Radiobutton(Labelframe, text="Ion Scattering", variable=modevar, value=0, width=20, command=lambda i=i :changemode())
434
    Rions.pack()
435
    Rrrna = tk.Radiobutton(Labelframe, text="Resonant RNA", variable=modevar, value=1, width=20, command=lambda i=i :changemode2())
436 437
    Rrrna.pack()

438
##############################################################################
439
##############################################################################
440
# Init
441

442
    Rions.invoke()
443
    RDra.invoke()
444
    elem_select(0,Ebuttons,grafico, f, a, t)
445

446
##############################################################################
447