Converting Input Files to GUIs

Một phần của tài liệu Python scripting for computational science (Trang 621 - 624)

11.4 Simulation and Visualization Scripts

11.4.11 Converting Input Files to GUIs

Theparse_input_filefunction from Chapter 11.4.10 turns an input file (with the special syntax) into a list of dictionaries, which is returned as the hetero- geneous listparsed_lines. With this data structure we can generate a GUI, use the GUI to get new input data from the user, and finally dump the new data back to file again.

A simple way of creating a GUI for input data to a simulator is to use the Parametersclass from thescitools.ParameterInterfacemodule described in Chapter 11.4.2 and exemplified in Chapter 11.4.4. The basic task is more or less to translate the information in the parsed_lines list of dictionaries to appropriate calls to the add method in a Parameters instance. The fol- lowing function, found in theinputfile_wunits module referred to in Chap- ter 11.4.10, does the job:

def lines2prms(parsed_lines, parameters=None):

if parameters is None:

parameters = Parameters(interface=’GUI’) for line in parsed_lines:

if isinstance(line, dict):

comment = line[’comment’]

if line[’ref_unit’] is not None:

# parameter has value with unit:

help = ’unit: ’+line[’ref_unit’]+’; ’+comment[1:]

unit = line[’ref_unit’]

str2type = float # unit conversions -> float else:

help = comment[1:]

unit = None

str2type = line[’value’].__class__

parameters.add(name=line[’parameter’], default=line[’value’], str2type=str2type,

602 11. More Advanced GUI Programming

widget_type=’entry’, help=help, unit=unit) return parameters

All parameter values that have associated units are taken as floating-point numbers, while the rest of the input data are simply strings. All widgets are taken to be text entries since we have not introduced the necessary syntax to deal with sliders, option menus, lists, etc. We could do that in the comment part of each line in the input file, for instance.

Having aParametersinstance, we can use classAutoSimVizGUIto build the GUI. This time we only want widgets for input parameters, i.e., there is no need forSimulateandVisualizebuttons.

def GUI(parameters, root):

gui = AutoSimVizGUI()

gui.make_prmGUI(root, parameters, height=300)

Button(root, text=’Quit’, command=root.destroy).pack() root.mainloop()

return parameters

TheParameters instance with updated values, according to the user input in the GUI, is returned from this function. The next step is to dump the possibly modified contents of parameters back to a file with the syntax required by the simulator:

def prms2lines(new_parameters, parsed_lines):

output_lines = []

for line in parsed_lines:

if isinstance(line, str):

output_lines.append(line) else:

# line is a dictionary; turn it into a line prm = line[’parameter’]

if prm in new_parameters:

value = new_parameters[prm]

else:

value = line[’value’]

comment = line[’comment’]

output_lines.append(’set %s = %s %s\n’ % \ (prm, value, comment)) return output_lines

Note that the new_parameters arguments does not need to be a Parameters object – any plain dictionary-like object holding some parameter names and their new values will work.

A sample main program for calling these functions may look like from inputfile_wunits import *

filename = sys.argv[1] # name of input file with commands f = open(filename, ’r’); lines = f.readlines(); f.close() parsed_lines, dummy = parse_input_file(lines)

root = Tk() # Tk() must have been called before Parameters work p = lines2prms(parsed_lines)

p = GUI(p, root) # read values from a GUI lines = prms2lines(p, parsed_lines) newfile = filename + ’.new’

f = open(newfile, ’w’); f.writelines(lines); f.close()

# commands.getstatusoutput(simulator_prog + ’ < ’ + newfile) A main feature of the GUI is that it works with physical units.

Hopefully, the ideas covered this and the previous section can be used to equip old simulators with more convenient interfaces. The most important idea, however, is that some lines of Python may do things a numerical pro- grammer, familiar with classical languages for scientific computing, has never thought of doing before.

Chapter 12

Tools and Examples

This chapter is devoted to tools and examples that are useful for computa- tional scientists and engineers who want to build their own problem solving environments. The focus is on sketching ideas. Particular application areas and required software functionality will put constraints on which ideas that are fruitful to follow.

Scientific investigations often involve running a simulation program re- peatedly while varying one or more input parameters. Chapter 12.1 presents a module that enables input parameters to take on multiple values. The module computes all combinations of all parameters and sets up the experi- ments. Besides being useful and having significant applications for scientific investigations, the module also demonstrates many nice high-level features of Python.

Mathematical functions are needed in most scientific software, and Chap- ter 12.2 presents some tools for flexible construction and handling of mathe- matical functions. For example, a user can give a string containing a formula, a set of discrete (measured/simulated) data, a drawing in a GUI widget, or a plain Python function as input, and the script can work with all these function representations in a unified way.

More sophisticated simulation problems, involving simple partial differ- ential equations, are addressed in Chapter 12.3. This chapter brings together lots of topics from different parts of the book. We show how problems involv- ing simultaneous computation and visualization can be coded in a Matlab- like style in Python. We also develop a problem solving environment for one-dimensional water wave problems, using high-level GUI tools from Chap- ter 11.4. With this GUI the user can, e.g., draw the initial water surface and the bottom shape, and then watch the time evolution of the surface simulta- neously with the computations. Various optimizations, such as vectorization by slicing and migration of loops to Fortran, are also explained and evaluated.

Một phần của tài liệu Python scripting for computational science (Trang 621 - 624)

Tải bản đầy đủ (PDF)

(769 trang)