1================================================ 2Veusz command line and embedding interface (API) 3================================================ 4 5.. _Commands: 6 7Introduction 8############ 9 10Veusz uses a common API, or set of commands, to control the program 11via its command line (from the Veusz console; click View, Windows, 12Console Window), the embedding interface (when Veusz is embedded in 13other Python programs), from within plugins, within documents (VSZ 14documents contain commands used to generate the document) or 15externally from the operating system command line (using `veusz 16--listen`). 17 18As Veusz is a a Python application it uses Python as its scripting 19language. You can therefore freely mix Veusz and Python commands on 20the Veusz command line (Click View, Windows, Console Window to get 21access to the command line). Veusz can also read in Python scripts 22from files on the command line (see the :ref:`Load <Command.Load>` 23command). 24 25When commands are entered in the command prompt in the Veusz window, 26Veusz supports a simplified command syntax, whereq brackets following 27commands names, and commas, can replaced by spaces in Veusz commands 28(not Python commands). For example, :command:`Add('graph', 29name='foo')`, may be entered as :command:`Add 'graph' name='foo'`. 30 31The :command:`numpy` package is already imported into the command line 32interface (as `\*`), so you do not need to import it first. 33 34The command prompt supports history (use the up and down cursor keys 35to recall previous commands). 36 37Most of the commands listed below can be used in the in-program 38command line interface, using the embedding interface or using `veusz 39--listen`. Commands specific to particular modes are documented as 40such. 41 42Veusz also includes a new object-oriented version of the API, which is 43documented at new_api_. 44 45Commands and API 46################ 47 48We list the allowed set of commands below 49 50Action 51------ 52 53.. _Command.Action: 54 55:command:`Action('actionname', 56componentpath='.')` 57 58Initiates the specified action on the widget (component) 59given the action name. Actions perform certain automated 60routines. These include "fit" on a fit widget, and 61"zeroMargins" on grids. 62 63Add 64--- 65 66.. _Command.Add: 67 68:command:`Add('widgettype', name='nameforwidget', 69autoadd=True, optionalargs)` 70 71The Add command adds a graph into the current widget (See the :ref:`To 72<Command.To>` command to change the current position). 73 74The first argument is the type of widget to add. These include 75"graph", "page", "axis", "xy" and "grid". :command:`name` is the name 76of the new widget (if not given, it will be generated from the type of 77the widget plus a number). The :command:`autoadd` parameter if set, 78constructs the default sub-widgets this widget has (for example, axes 79in a graph). 80 81Optionally, default values for the graph settings may be given, for 82example :command:`Add('axis', name='y', direction='vertical')`. 83 84Subsettings may be set by using double underscores, for example 85:command:`Add('xy', MarkerFill__color='red', 86ErrorBarLine__hide=True)`. 87 88Returns: Name of widget added. 89 90AddCustom 91--------- 92 93.. _Command.AddCustom: 94 95:command:`AddCustom(type, name, value)` 96 97Add a custom definition for evaluation of expressions. This can define 98a constant (can be in terms of other constants), a function of 1 or 99more variables, or a function imported from an external python module. 100 101ctype is "constant", "function" or "import". 102 103name is name of constant, or "function(x, y, ...)" or module name. 104 105val is definition for constant or function (both are _strings_), or is 106a list of symbols for a module (comma separated items in a string). 107 108If mode is 'appendalways', the custom value is appended to the end of 109the list even if there is one with the same name. If mode is 110'replace', it replaces any existing definition in the same place in 111the list or is appended otherwise. If mode is 'append', then an 112existing definition is deleted, and the new one appended to the end. 113 114AddImportPath 115------------- 116 117.. _Command.AddImportPath: 118 119:command:`AddImportPath(directory)` 120 121Add a directory to the list of directories to try to import data from. 122 123CloneWidget 124----------- 125 126.. _Command.CloneWidget: 127 128:command:`CloneWidget(widget, newparent, 129newname=None)` 130 131Clone the widget given, placing the copy in newparent and the name 132given. newname is an optional new name to give it Returns new widget 133path. 134 135Close 136----- 137 138.. _Command.Close: 139 140:command:`Close()` 141 142Closes the plotwindow. This is only supported in embedded mode. 143 144CreateHistogram 145--------------- 146 147.. _Command.CreateHistogram: 148 149:command:`CreateHistogram(inexpr, outbinsds, 150outvalsds, binparams=None, binmanual=None, 151method='counts', cumulative = 'none', 152errors=False)` 153 154Histogram an input expression. inexpr is input expression. outbinds 155is the name of the dataset to create giving bin positions. outvalsds 156is name of dataset for bin values. binparams is None or (numbins, 157minval, maxval, islogbins). binmanual is None or a list of bin 158values. method is 'counts', 'density', or 'fractions'. cumulative is 159to calculate cumulative distributions which is 'none', 'smalltolarge' 160or 'largetosmall'. errors is to calculate Poisson error bars. 161 162CurrentPath 163----------- 164 165.. _Command.CurrentPath 166 167:command:`CurrentPath()` 168 169Returns current widget path, as set by :ref:`To<Command.To>`. 170 171DatasetPlugin 172------------- 173 174.. _Command.DatasetPlugin: 175 176:command:`DatasetPlugin(pluginname, fields, 177datasetnames={})>` 178 179Use a dataset plugin. pluginname: name of plugin to use fields: dict 180of input values to plugin datasetnames: dict mapping old names to new 181names of datasets if they are renamed. The new name None means dataset 182is deleted 183 184EnableToolbar 185------------- 186 187.. _Command.EnableToolbar: 188 189:command:`EnableToolbar(enable=True)` 190 191Enable/disable the zooming toolbar in the plotwindow. This command is 192only supported in embedded mode or from `veusz --listen`. 193 194Export 195------ 196 197.. _Command.Export: 198 199:command:`Export(filename, color=True, page=0, dpi=100, 200antialias=True, quality=85, backcolor='#ffffff00', pdfdpi=150, 201svgdpi=96, svgtextastext=False)` 202 203Export the page given to the filename given. The :command:`filename` 204must end with the correct extension to get the right sort of output 205file. Currrenly supported extensions are '.eps', '.pdf', '.ps', 206'.svg', '.jpg', '.jpeg', '.bmp' and '.png'. If :command:`color` is 207True, then the output is in colour, else greyscale. :command:`page` is 208the page number of the document to export (starting from 0 for the 209first page!). A list of pages can be given for multipage formats (.pdf 210or .ps). :command:`dpi` is the number of dots per inch for bitmap 211output files. :command:`antialias` - antialiases output if 212True. :command:`quality` is a quality parameter for jpeg 213output. :command:`backcolor` is the background color for bitmap files, 214which is a name or a #RRGGBBAA value (red, green, blue, 215alpha). :command:`pdfdpi` is the dpi to use when exporting EPS or PDF 216files. :command:`svgdpi` is the dpi to use when exporting to SVG files. 217:command:`svgtextastext` says whether to export SVG text as 218text, rather than curves. 219 220FilterDatasets 221-------------- 222 223.. _Command.FilterDatasets: 224 225:command:`FilterDatasets(filterexpr, datasets, prefix="", suffix="", 226invert=False, replaceblanks=False)` 227 228Filter a list of datasets given. Creates new datasets for each with 229prefix and suffix added to input dataset names. filterexpr is an input 230numpy eexpression for filtering the datasets. If invert is set, the 231filter condition is inverted. If replaceblanks is set, filtered values 232are not removed, but replaced with a blank or NaN value. This command 233only works on 1D numeric, date or text datasets. 234 235ForceUpdate 236----------- 237 238.. _Command.ForceUpdate: 239 240:command:`ForceUpdate()` 241 242Force the window to be updated to reflect the current state of the 243document. Often used when periodic updates have been disabled (see 244SetUpdateInterval). This command is only supported in embedded mode or 245from `veusz --listen`. 246 247Get 248--- 249 250.. _Command.Get: 251 252:command:`Get('settingpath')` 253 254Returns: The value of the setting given by the path. 255 256.. code-block:: python 257 258 >>> Get('/page1/graph1/x/min') 259 'Auto' 260 261GetChildren 262----------- 263 264.. _Command.GetChildren: 265 266:command:`GetChildren(where='.')` 267 268Returns: The names of the widgets which are children of 269the path given 270 271GetClick 272-------- 273 274.. _Command.GetClick: 275 276:command:`GetClick()` 277 278Waits for the user to click on a graph and returns the 279position of the click on appropriate axes. Command only works 280in embedded mode. 281 282Returns: A list containing tuples of the form (axispath, 283val) for each axis for which the click was in range. The value 284is the value on the axis for the click. 285 286GetColormap 287----------- 288 289.. _Command.GetColormap: 290 291:command:`GetColormap(name, invert=False, nvals=256)` 292 293Returns a colormap as a numpy array of red, green, blue, alpha values 294(ranging from 0 to 255) with the number of steps given. 295 296GetData 297------- 298 299.. _Command.GetData: 300 301:command:`GetData(name)` 302 303Returns: For a 1D dataset, a tuple containing the dataset with the 304name given. The value is (data, symerr, negerr, poserr), with each a 305numpy array of the same size or None. data are the values of the 306dataset, symerr are the symmetric errors (if set), negerr and poserr 307and negative and positive asymmetric errors (if set). If a text 308dataset, return a list of text elements. If the dataset is a date-time 309dataset, return a list of Python datetime objects. If the dataset is a 3102D dataset return the tuple (data, rangex, rangey), where data is a 2D 311numpy array and rangex/y are tuples giving the range of the x and y 312coordinates of the data. If it is an ND dataset, return an 313n-dimensional array. 314 315.. code-block:: python 316 317 data = GetData('x') 318 SetData('x', data[0]*0.1, \*data[1:]) 319 320GetDataType 321----------- 322 323.. _Command.GetDataType: 324 325:command:`GetDataType(name)` 326 327Get type of dataset with name given. Returns '1d' for a 3281d dataset, '2d' for a 2d dataset, 'text' for a text dataset 329and 'datetime' for a datetime dataset. 330 331GetDatasets 332----------- 333 334.. _Command.GetDatasets: 335 336:command:`GetDatasets()` 337 338Returns: The names of the datasets in the current document. 339 340GPL 341--- 342 343.. _Command.GPL: 344 345:command:`GPL()` 346 347Print out the GNU Public Licence, which Veusz is licenced under. 348 349ImportFile 350---------- 351 352.. _Command.ImportFile: 353 354:command:`ImportFile(comm, filename, descriptor, useblocks=False, linked=False, prefix='', suffix='', ignoretext=False, encoding='utf_8', renames=None)` 355 356Imports data from a file. The arguments are the filename to load data 357from and the descriptor. 358 359The format of the descriptor is a list of variable names representing 360the columns of the data. For more information see :ref:`Descriptors 361<Descriptors>`. 362 363If the linked parameter is set to True, if the document is saved, the 364data imported will not be saved with the document, but will be reread 365from the filename given the next time the document is opened. The 366linked parameter is optional. 367 368If useblocks is set, then blank lines or the word 'no' are used to 369split the data into blocks. Dataset names are appended with an 370underscore and the block number (starting from 1). encoding is the 371name of the text file encoding. renames is a dict mapping existing to 372new names after import. 373 374If prefix and/or suffix are set, then the prefix and suffix are added 375to each dataset name. If set, renames maps imported dataset names to 376final dataset names after import. 377 378Returns: A tuple containing a list of the imported datasets and the 379number of conversions which failed for a dataset. 380 381ImportFile2D 382------------ 383 384.. _Command.ImportFile2D: 385 386:command:`ImportFile2D(filename, datasetnames, xrange=None, yrange=None, invertrows=None, invertcols=None, transpose=None, gridatedge=None, mode='text', csvdelimiter=',', csvtextdelimiter='"', csvlocale='en_US', prefix="", suffix="", encoding='utf_8', linked=False)` 387 388Imports two-dimensional data from a file. The required arguments are 389the filename to load data from and the dataset name, or a list of 390names to use. 391 392In text mode, the file format this command accepts is a 393two-dimensional matrix of numbers, with the columns separated by 394spaces or tabs, and the rows separated by new lines. The X-coordinate 395is taken to be in the direction of the columns. Comments are supported 396(use `#`, `!` or `%`), as are continuation characters (`\\`). Separate 397datasets are deliminated by using blank lines. In csv mode, the csv 398parameters give the type of CSV file sypported. 399 400:: 401 402 xrange is a tuple containing the range of data in x coordinates 403 yrange is a tuple containing the range of data in y coordinates 404 if invertrows=True, then rows are inverted when read 405 if invertcols=True, then cols are inverted when read 406 if transpose=True, then rows and columns are swapped 407 if gridatedge=True, use top row and left column for pixel positions 408 409 mode is either 'text' or 'csv' 410 csvdelimiter is the csv delimiter for csv 411 csvtextdelimiter is the csv text delimiter for csv 412 csvlocale is locale to use when reading csv data 413 414 prefix and suffix are prepended and appended to dataset names 415 416 encoding is encoding character set 417 418 if linked=True then the dataset is linked to the file 419 420 Returns: list of imported datasets 421 422In addition to the matrix of numbers, the various optional parameters 423this command takes can also be specified in the data file. These 424commands should be given on separate lines before the matrix of 425numbers. They are: 426 427#. xrange A B 428 429#. yrange C D 430 431#. invertrows 432 433#. invertcols 434 435#. transpose 436 437ImportFileCSV 438------------- 439 440.. _Command.ImportFileCSV: 441 442:command:`ImportFileCSV('filename', readrows=False, 443delimiter=',', skipwhitespace=False, textdelimiter='"', 444encoding='utf_8', 445headerignore=0, rowsignore=0, 446blanksaredata=False, 447numericlocale='en_US', 448dateformat='YYYY-MM-DD|T|hh:mm:ss', 449headermode='multi', 450dsprefix='', dssuffix='', prefix=None, 451renames=None, 452linked=False)` 453 454This command imports data from a CSV format file. Data are read from 455the file using the dataset names given at the top of the files in 456columns. Please see the reading data section of this manual for more 457information. The options are explained below. 458 459:: 460 461 readrows: if true, data are read across rather than down 462 delimiter: character for delimiting data (usually ',') 463 skipwhitespace: if true, white space following delimiter is ignored 464 textdelimiter: character surrounding text (usually '"') 465 encoding: encoding used in file 466 headerignore: number of lines to ignore after header text 467 rowsignore: number of rows to ignore at top of file 468 blanksaredata: treats blank lines in csv files as blank data values 469 numericlocale: format to use for reading numbers 470 dateformat: format for interpreting dates 471 headermode: 'multi': multiple headers allowed in file 472 '1st': first text found are headers 473 'none': no headers, guess data and use default names 474 475 Dataset names are prepended and appended, by dsprefix and dssuffix, 476 respectively 477 (prefix is backware compatibility only, it adds an underscore 478 relative to dsprefix) 479 480 renames is a map of old names to new names to rename on import 481 482 If linked is True the data are linked with the file. 483 484 Returns: list of imported datasets 485 486ImportFileFITS 487-------------- 488 489.. _Command.ImportFileFITS: 490 491:command:`ImportFileFits(filename, items, namemap={}, 492slices={}, twodranges={}, twod_as_oned=set(\[]), 493wcsmodes={}, prefix='', suffix='', renames={}, 494linked=False)` 495 496Import data from a FITS file. 497 498items is a list of datasets to be imported. items are formatted like 499the following: 500 501:: 502 503 '/': import whole file 504 '/hduname': import whole HDU (image or table) 505 '/hduname/column': import column from table HDU 506 507all values in items should be lower case. 508 509HDU names have to follow a Veusz-specific naming. If the HDU has a 510standard name (e.g. primary or events), then this is used. If the 511HDU has a EXTVER keyword then this number is appended to this 512name. An extra number is appended if this name is not unique. If 513the HDU has no name, then the name used should be 'hduX', where X 514is the HDU number (0 is the primary HDU). 515 516namemap maps an input dataset (using the scheme above for items) 517to a Veusz dataset name. Special suffixes can be used on the Veusz 518dataset name to indicate that the dataset should be imported 519specially. 520 521:: 522 523 'foo (+)': import as +ve error for dataset foo 524 'foo (-)': import as -ve error for dataset foo 525 'foo (+-)': import as symmetric error for dataset foo 526 527slices is an optional dict specifying slices to be selected when 528importing. For each dataset to be sliced, provide a tuple of 529values, one for each dimension. The values should be a single 530integer to select that index, or a tuple (start, stop, step), 531where the entries are integers or None. 532 533twodranges is an optional dict giving data ranges for 2D 534datasets. It maps names to (minx, miny, maxx, maxy). 535 536twod_as_oned: optional set containing 2D datasets to attempt to 537read as 1D, treating extra columns as error bars 538 539wcsmodes is an optional dict specfying the WCS import mode for 2D 540datasets in HDUs. The keys are '/hduname' and the values can be 541'pixel': number pixel range from 0 to maximum (default) 542'pixel_wcs': pixel number relative to WCS reference pixel 543'linear_wcs': linear coordinate system from the WCS keywords 544'fraction': fractional values from 0 to 1. 545 546renames is an optional dict mapping old to new dataset names, to 547be renamed after importing 548 549linked specifies that the dataset is linked to the file. 550 551Values under the VEUSZ header keyword can be used to override defaults: 552 553:: 554 555 'name': override name for dataset 556 'slice': slice on importing (use format "start:stop:step,...") 557 'range': should be 4 item array to specify x and y ranges: 558 [minx, miny, maxx, maxy] 559 'xrange' / 'yrange': individual ranges for x and y 560 'xcent' / 'ycent': arrays giving the centres of pixels 561 'xedge' / 'yedge': arrays giving the edges of pixels 562 'twod_as_oned': treat 2d dataset as 1d dataset with errors 563 'wcsmode': use specific WCS mode for dataset (see values above) 564 These are specified under the VEUSZ header keyword in the form 565 KEY=VALUE 566 or for column-specific values 567 COLUMNNAME: KEY=VALUE 568 569Returns: list of imported datasets 570 571ImportFileHDF5 572-------------- 573 574.. _Command.ImportFileHDF5: 575 576:command:`ImportFileHDF5(filename, items, namemap={}, 577slices={}, twodranges={}, twod_as_oned=set(\[]), 578convert_datetime={}, prefix='', suffix='', renames={}, 579linked=False)` 580 581Import data from a HDF5 file. items is a list of groups and 582datasets which can be imported. If a group is imported, all 583child datasets are imported. namemap maps an input dataset 584to a veusz dataset name. Special suffixes can be used on the 585veusz dataset name to indicate that the dataset should be 586imported specially. 587 588:: 589 590 'foo (+)': import as +ve error for dataset foo 591 'foo (-)': import as -ve error for dataset foo 592 'foo (+-)': import as symmetric error for dataset foo 593 594slices is an optional dict specifying slices to be selected when 595importing. For each dataset to be sliced, provide a tuple of values, 596one for each dimension. The values should be a single integer to 597select that index, or a tuple (start, stop, step), where the entries 598are integers or None. 599 600twodranges is an optional dict giving data ranges for 2d datasets. It 601maps names to (minx, miny, maxx, maxy). twod_as_oned: optional set 602containing 2d datasets to attempt to read as 1d 603 604convert_datetime should be a dict mapping hdf name to specify 605date/time importing. For a 1d numeric dataset: if this is set to 606'veusz', this is the number of seconds since 2009-01-01, if this is 607set to 'unix', this is the number of seconds since 1970-01-01. For a 608text dataset, this should give the format of the date/time, 609e.g. 'YYYY-MM-DD|T|hh:mm:ss' or 'iso' for iso format. 610 611renames is a dict mapping old to new dataset names, to be renamed 612after importing. linked specifies that the dataset is linked to the 613file. 614 615Attributes can be used in datasets to override defaults: 616 617:: 618 619 'vsz_name': set to override name for dataset in veusz 620 'vsz_slice': slice on importing (use format "start:stop:step,...") 621 'vsz_range': should be 4 item array to specify x and y ranges: 622 [minx, miny, maxx, maxy] 623 'vsz_twod_as_oned': treat 2d dataset as 1d dataset with errors 624 'vsz_convert_datetime': treat as date/time, set to one of the values 625 above. 626 627For compound datasets these attributes can be given on a per-column 628basis using attribute names vsz_attributename_columnname. 629 630Returns: list of imported datasets 631 632ImportFileND 633------------ 634 635.. _Command.ImportFileND: 636 637:command:`def ImportFileND(comm, filename, dataset, shape=None, 638transpose=False, mode='text', csvdelimiter=',', csvtextdelimiter='"', 639csvlocale='en_US', prefix="", suffix="", encoding='utf_8', 640linked=False)` 641 642Import an n-dimensional dataset from a file. The file should either be 643in CSV format (mode='csv') or whitespace-separated text (mode='text'). 644A one-dimensional dataset is given as a list of numbers on a single 645line/row. A two-dimensional dataset is given by a set of rows. A 646three-dimensional dataset is given by a set of two-dimensional 647datasets, with blank lines between them. a four-dimensional dataset is 648given by a set of three-dimensional datasets with two blank lines 649between each. Each additional dataset increases the separating number 650of blank lines by one. Alternatively, the numbers can be given in any 651form (number of numbers on each row) and "shape" is included to 652reshape the data into the desired shape. 653 654In the file, or included as parameters above, the command "shape num1 655num2..." can be included to reshape the output dataset to the shape 656given by the numbers in the row after "shape" (these should be in 657separate columns in CSV format). If one of these numbers is -1, then 658this dimension is inferred from the number of values and the other 659dimensions. Also supported is the "transpose" command or optional 660argument which reverses the order of the dimensions. 661 662ImportFilePlugin 663---------------- 664 665.. _Command.ImportFilePlugin: 666 667:command:`ImportFilePlugin('pluginname', 'filename', \**pluginargs, 668linked=False, encoding='utf_8', prefix='', suffix='', renames={})` 669 670Import data from file using import plugin 'pluginname'. The arguments 671to the plugin are given, plus optionally a text encoding, and prefix 672and suffix to prepend or append to dataset names. renames, if set, 673provides new names for datasets after import. 674 675ImportFITSFile 676-------------- 677 678.. _Command.ImportFITSFile: 679 680:command:`ImportFITSFile(datasetname, filename, hdu, datacol='A', 681symerrcol='B', poserrcol='C', negerrcol='D', linked=True/False, 682renames={})` 683 684This command is deprecated. Please do not use in new code, but instead 685use ImportFileFITS. 686 687This command does a simple import from a FITS file. The FITS format is 688used within the astronomical community to transport binary data. For a 689more powerful FITS interface, you can use PyFITS within your scripts. 690 691The datasetname is the name of the dataset to import, the filename is 692the name of the FITS file to import from. The hdu parameter specifies 693the HDU to import data from (numerical or a name). 694 695If the HDU specified is a primary HDU or image extension, then a 696two-dimensional dataset is loaded from the file. The optional 697parameters (other than linked) are ignored. Any WCS information within 698the HDU are used to provide a suitable xrange and yrange. 699 700If the HDU is a table, then the datacol parameter must be specified 701(and optionally symerrcol, poserrcol and negerrcol). The dataset is 702read in from the named column in the table. Any errors are read in 703from the other specified columns. 704 705If linked is True, then the dataset is not saved with a saved 706document, but is reread from the data file each time the document is 707loaded. renames, if set, provides new names for datasets after 708import. 709 710ImportString 711------------ 712 713.. _Command.ImportString: 714 715:command:`ImportString('descriptor', 716'data')` 717 718Like, :ref:`ImportFile <Command.ImportFile>`, but loads the data from 719the specfied string rather than a file. This allows data to be easily 720embedded within a document. The data string is usually a multi-line 721Python string. 722 723Returns: A tuple containing a list of the imported datasets and the 724number of conversions which failed for a dataset. 725 726Changed in version 0.5: A tuple is returned rather than just the 727number of imported variables. 728 729.. code-block:: python 730 731 ImportString('x y', ''' 732 1 2 733 2 5 734 3 10 735 ''') 736 737ImportString2D 738-------------- 739 740.. _Command.ImportString2D: 741 742:command:`ImportString2D(datasets, string, xrange=None, yrange=None, 743invertrows=None, invertcols=None, transpose=None)` 744 745Imports a two-dimensional dataset from the string given. This is 746similar to the :ref:`ImportFile2D <Command.ImportFile2D>` command, 747with the same dataset format within the string. The optional values 748are also listed there. The various controlling parameters can be set 749within the string. See the :ref:`ImportFile2D <Command.ImportFile2D>` 750section for details. 751 752ImportStringND 753-------------- 754 755.. _Command.ImportStringND: 756 757:command:`ImportStringND(dataset, string, shape=None, 758transpose=False)` 759 760Imports a n-dimensional dataset from the string given. This is similar 761to the :ref:`ImportFileND <Command.ImportFileND>` command. Please look 762there for more detail and the description of the optional parameters 763and in-stream allowed parameters. 764 765IsClosed 766-------- 767 768.. _Command.IsClosed: 769 770:command:`IsClosed()` 771 772Returns a boolean value telling the caller whether the plotting window 773has been closed. 774 775Note: this command is only supported in the embedding interface. 776 777List 778---- 779 780.. _Command.List: 781 782:command:`List(where='.')` 783 784List the widgets which are contained within the widget with the path 785given, the type of widgets, and a brief description. 786 787Load 788---- 789 790.. _Command.Load: 791 792:command:`Load('filename.vsz')` 793 794Loads the veusz script file given. The script file can be any Python 795code. The code is executed using the Veusz interpreter. 796 797Note: this command is only supported at the command line and not in a 798script. Scripts may use the python :command:`execfile` function 799instead. 800 801MoveToPage 802---------- 803 804.. _Command.MoveToPage: 805 806:command:`MoveToPage(pagenum)` 807 808Updates window to show the page number given of the document. 809 810Note: this command is only supported in the embedding interface or 811`veusz --listen`. 812 813ReloadData 814---------- 815 816.. _Command.ReloadData: 817 818:command:`ReloadData()` 819 820Reload any datasets which have been linked to files. 821 822Returns: A tuple containing a list of the imported datasets and the 823number of conversions which failed for a dataset. 824 825Rename 826------ 827 828.. _Command.Rename: 829 830:command:`Remove('widgetpath', 'newname')` 831 832Rename the widget at the path given to a new name. This command does 833not move widgets. See :ref:`To <Command.To>` for a description of the 834path syntax. '.' can be used to select the current widget. 835 836Remove 837------ 838 839.. _Command.Remove: 840 841:command:`Remove('widgetpath')` 842 843Remove the widget selected using the path. See :ref:`To <Command.To>` 844for a description of the path syntax. 845 846ResizeWindow 847------------ 848 849.. _Command.ResizeWindow: 850 851:command:`ResizeWindow(width, height)` 852 853Resizes window to be width by height pixels. 854 855Note: this command is only supported in the embedding interface or 856`veusz --listen`. 857 858Save 859---- 860 861.. _Command.Save: 862 863:command:`Save('filename.vsz')` 864 865Save the current document under the filename 866given. 867 868Set 869--- 870 871.. _Command.Set: 872 873:command:`Set('settingpath', val)` 874 875Set the setting given by the path to the value given. If the type of 876:command:`val` is incorrect, an :command:`InvalidType` exception is 877thrown. The path to the setting is the optional path to the widget the 878setting is contained within, an optional subsetting specifier, and the 879setting itself. 880 881.. code-block:: python 882 883 Set('page1/graph1/x/min', -10.) 884 885SetAntiAliasing 886--------------- 887 888.. _Command.SetAntiAliasing: 889 890:command:`SetAntiAliasing(on)` 891 892Enable or disable anti aliasing in the plot window, replotting the 893image. 894 895SetData 896------- 897 898.. _Command.SetData: 899 900:command:`SetData(name, val, symerr=None, negerr=None, poserr=None)` 901 902Set the dataset name with the values given. If None is given for an 903item, it will be left blank. val is the actual data, symerr are the 904symmetric errors, negerr and poserr and the getative and positive 905asymmetric errors. The data can be given as lists or numpys. 906 907SetDataExpression 908----------------- 909 910.. _Command.SetDataExpression: 911 912:command:`SetDataExpression(name, val, symerr=None, negerr=None, 913poserr=None, linked=False, parametric=None)` 914 915Create a new dataset based on the expressions given. The expressions 916are Python syntax expressions based on existing datasets. 917 918If linked is True, the dataset will change as the datasets in the 919expressions change. 920 921Parametric can be set to a tuple of (minval, maxval, 922numitems). :command:`t` in the expression will iterate from minval to 923maxval in numitems values. 924 925SetDataND 926--------- 927 928.. _Command.SetDataND: 929 930:command:`SetDataRange(name, val)` 931 932Set a n-dimensional dataset to be the values given by val. val should 933be an n-dimensional numpy array of values, or a list of lists. 934 935SetDataRange 936------------ 937 938.. _Command.SetDataRange: 939 940:command:`SetDataRange(name, numsteps, val, symerr=None, negerr=None, 941poserr=None, linked=False)` 942 943Set dataset to be a range of values with numsteps steps. val is tuple 944made up of (minimum value, maximum value). symerr, negerr and poserr 945are optional tuples for the error bars. 946 947If linked is True, the dataset can be saved in a document as a 948SetDataRange, otherwise it is expanded to the values which would make 949it up. 950 951SetData2D 952--------- 953 954.. _Command.SetData2D: 955 956:command:`SetData2D('name', val, xrange=(A,B), yrange=(C,D), 957xgrid=[1,2,3...], ygrid=[4,5,6...])` 958 959Creates a two-dimensional dataset with the name given. val is either a 960two-dimensional numpy array, or is a list of lists, with each list in 961the list representing a row. Do not give xrange if xgrid is set and do 962not give yrange if ygrid is set, and vice versa. 963 964xrange and yrange are optional tuples giving the inclusive range of 965the X and Y coordinates of the data. xgrid and ygrid are optional 966lists, tuples or arrays which give the coordinates of the edges of the 967pixels. There should be one more item in each array than pixels. 968 969SetData2DExpression 970------------------- 971 972.. _Command.SetData2DExpression: 973 974:command:`SetData2DExpression('name', expr, linked=False)` 975 976Create a 2D dataset based on expressions. name is the new dataset 977name expr is an expression which should return a 2D array linked 978specifies whether to permanently link the dataset to the expressions. 979 980SetData2DExpressionXYZ 981---------------------- 982 983.. _Command.SetData2DExpressionXYZ: 984 985:command:`SetData2DExpressionXYZ('name', 'xexpr', 'yexpr', 'zexpr', 986linked=False)` 987 988Create a 2D dataset based on three 1D expressions. The x, y 989expressions need to evaluate to a grid of x, y points, with the z 990expression as the 2D value at that point. Currently only linear fixed 991grids are supported. This function is intended to convert calculations 992or measurements at fixed points into a 2D dataset easily. Missing 993values are filled with NaN. 994 995SetData2DXYFunc 996--------------- 997 998.. _Command.SetData2DXYFunc: 999 1000:command:`SetData2DXYFunc('name', xstep, ystep, 'expr', linked=False)` 1001 1002Construct a 2D dataset using a mathematical expression of "x" and 1003"y". The x values are specified as (min, max, step) in xstep as a 1004tuple, the y values similarly. If linked remains as False, then a real 10052D dataset is created, where values can be modified and the data are 1006stored in the saved file. 1007 1008SetDataDateTime 1009--------------- 1010 1011.. _Command.SetDataDateTime: 1012 1013:command:`SetDataDateTime('name', vals)` 1014 1015Creates a datetime dataset of name given. vals is a list of Python 1016datetime objects. 1017 1018SetDataText 1019----------- 1020 1021.. _Command.SetDataText: 1022 1023:command:`SetDataText(name, val)` 1024 1025Set the text dataset name with the values given. :command:`val` must 1026be a type that can be converted into a Python list. 1027 1028.. code-block:: python 1029 1030 SetDataText('mylabel', ['oranges', 'apples', 'pears', 'spam']) 1031 1032SetToReference 1033-------------- 1034 1035.. _Command.SetToReference: 1036 1037:command:`SetToReference(setting, refval)` 1038 1039Link setting given to other setting refval. 1040 1041SetUpdateInterval 1042----------------- 1043 1044.. _Command.SetUpdateInterval: 1045 1046:command:`SetUpdateInterval(interval)` 1047 1048Tells window to update every interval milliseconds at most. The value 10490 disables updates until this function is called with a non-zero. The 1050value -1 tells Veusz to update the window every time the document has 1051changed. This will make things slow if repeated changes are made to 1052the document. Disabling updates and using the ForceUpdate command will 1053allow the user to control updates directly. 1054 1055Note: this command is only supported in the embedding interface or 1056`veusz --listen`. 1057 1058SetVerbose 1059---------- 1060 1061.. _Command.SetVerbose: 1062 1063:command:`SetVerbose(v=True)` 1064 1065If :command:`v` is :command:`True`, then extra information is printed 1066out by commands. 1067 1068StartSecondView 1069--------------- 1070 1071.. _Command.StartSecondView: 1072 1073:command:`StartSecondView(name = 'window title')` 1074 1075In the embedding interface, this method will open a new Embedding 1076interface onto the same document, returning the object. This new 1077window provides a second view onto the document. It can, for instance, 1078show a different page to the primary view. name is a window title for 1079the new window. 1080 1081Note: this command is only supported in the embedding interface. 1082 1083TagDatasets 1084----------- 1085 1086.. _Command.TagDatasets: 1087 1088:command:`TagDatasets('tag', ['ds1', 'ds2'...])` 1089 1090Adds the tag to the list of datasets given.. 1091 1092To 1093-- 1094 1095.. _Command.To: 1096 1097:command:`To('widgetpath')` 1098 1099The To command takes a path to a widget and moves to that widget. For 1100example, this may be "/", the root widget, "graph1", 1101"/page1/graph1/x", "../x". The syntax is designed to mimic Unix paths 1102for files. "/" represents the base widget (where the pages reside), 1103and ".." represents the widget next up the tree. 1104 1105Quit 1106---- 1107 1108.. _Command.Quit: 1109 1110:command:`Quit()` 1111 1112Quits Veusz. This is only supported in `veusz --listen`. 1113 1114WaitForClose 1115------------ 1116 1117.. _Command.WaitForClose: 1118 1119:command:`WaitForClose()` 1120 1121Wait until the plotting window has been closed. 1122 1123Note: this command is only supported in the embedding interface. 1124 1125Zoom 1126---- 1127 1128.. _Command.Zoom: 1129 1130:command:`Zoom(factor)` 1131 1132Sets the plot zoom factor, relative to a 1:1 scaling. factor can also 1133be "width", "height" or "page", to zoom to the page width, height or 1134page, respectively. 1135 1136This is only supported in embedded mode or `veusz --listen`. 1137 1138Security 1139######## 1140 1141With the 1.0 release of Veusz, input scripts and expressions are 1142checked for possible security risks. Only a limited subset of Python 1143functionality is allowed, or a dialog box is opened allowing the user 1144to cancel the operation. Specifically you cannot import modules, get 1145attributes of Python objects, access globals() or locals() or do any 1146sort of file reading or manipulation. Basically anything which might 1147break in Veusz or modify a system is not supported. In addition 1148internal Veusz functions which can modify a system are also warned 1149against, specifically Print(), Save() and Export(). 1150 1151If you are running your own scripts and do not want to be bothered by 1152these dialogs, you can run veusz with the :command:`--unsafe-mode` 1153option. 1154 1155Using Veusz from other programs 1156############################### 1157 1158Non-Qt Python programs 1159---------------------- 1160 1161Veusz can be used as a Python module for plotting data. There are two 1162ways to use the module: (1) with an older path-based Veusz commands, 1163used in Veusz saved document files or (2) using an object-oriented 1164interface. With the old style method the user uses a unix-path 1165inspired API to navigate the widget tree and add or manipulate 1166widgets. With the new style interface, the user navigates the tree 1167with attributes of the ``Root`` object to access Nodes. The new 1168interface is likely to be easier to use unless you are directly 1169translating saved files. 1170 1171Older path-based interface 1172-------------------------- 1173 1174.. code-block:: python 1175 1176 """An example embedding program. Veusz needs to be installed into 1177 the Python path for this to work (use setup.py) 1178 1179 This animates a sin plot, then finishes 1180 """ 1181 1182 import time 1183 import numpy 1184 import veusz.embed as veusz 1185 1186 # construct a Veusz embedded window 1187 # many of these can be opened at any time 1188 g = veusz.Embedded('window title') 1189 g.EnableToolbar() 1190 1191 # construct the plot 1192 g.To( g.Add('page') ) 1193 g.To( g.Add('graph') ) 1194 g.Add('xy', marker='tiehorz', MarkerFill__color='green') 1195 1196 # this stops intelligent axis extending 1197 g.Set('x/autoExtend', False) 1198 g.Set('x/autoExtendZero', False) 1199 1200 # zoom out 1201 g.Zoom(0.8) 1202 1203 # loop, changing the values of the x and y datasets 1204 for i in range(10): 1205 x = numpy.arange(0+i/2., 7.+i/2., 0.05) 1206 y = numpy.sin(x) 1207 g.SetData('x', x) 1208 g.SetData('y', y) 1209 1210 # wait to animate the graph 1211 time.sleep(2) 1212 1213 # let the user see the final result 1214 print "Waiting for 10 seconds" 1215 time.sleep(10) 1216 print "Done!" 1217 1218 # close the window (this is not strictly necessary) 1219 g.Close() 1220 1221The embed interface has the methods listed in the command line 1222interface listed in the Veusz manual 1223https://veusz.github.io/docs/manual.html 1224 1225Multiple Windows are supported by creating more than one ``Embedded`` 1226object. Other useful methods include: 1227 1228- ``WaitForClose()`` - wait until window has closed 1229 1230- ``GetClick()`` - return a list of ``(axis, value)`` tuples where the 1231 user clicks on a graph 1232 1233- ``ResizeWndow(width, height)`` - resize window to be ``width`` x 1234 ``height`` pixels 1235 1236- ``SetUpdateInterval(interval)`` - set update interval in ms or 0 to 1237 disable 1238 1239- ``MoveToPage(page)`` - display page given (starting from 1) 1240 1241- ``IsClosed()`` - has the page been closed 1242 1243- ``Zoom(factor)`` - set zoom level (float) or 'page', 'width', 1244 'height' 1245 1246- ``Close()`` - close window 1247 1248- ``SetAntiAliasing(enable)`` - enable or disable antialiasing 1249 1250- ``EnableToolbar(enable=True)`` - enable plot toolbar 1251 1252- ``StartSecondView(name='Veusz')`` - start a second view onto the 1253 document of the current ``Embedded`` object. Returns a new 1254 ``Embedded`` object. 1255 1256- ``Wipe()`` - wipe the document of all widgets and datasets. 1257 1258.. _new_api: 1259 1260New-style object interface 1261-------------------------- 1262 1263In Veusz 1.9 or late a new style of object interface is present, which 1264makes it easier to construct the widget tree. Each widget, group of 1265settings or setting is stored as a Node object, or its subclass, in a 1266tree. The root document widget can be accessed with the ``Root`` 1267object. The dot operator "." finds children inside other nodes. In 1268Veusz some widgets can contain other widgets (Root, pages, graphs, 1269grids). Widgets contain setting nodes, accessed as attributes. Widgets 1270can also contain groups of settings, again accessed as attributes. 1271 1272An example tree for a document (not complete) might look like this 1273 1274:: 1275 1276 Root 1277 \-- page1 (page widget) 1278 \-- graph1 (graph widget) 1279 \-- x (axis widget) 1280 \-- y (axis widget) 1281 \-- function (function widget) 1282 \-- grid1 (grid widget) 1283 \-- graph2 (graph widget) 1284 \-- xy1 (xy widget) 1285 \-- xData (setting) 1286 \-- yData (setting) 1287 \-- PlotLine (setting group) 1288 \-- width (setting) 1289 ... 1290 ... 1291 \-- x (axis widget) 1292 \-- y (axis widget) 1293 \-- graph3 (graph widget) 1294 \-- contour1 (contour widget) 1295 \-- x (axis widget) 1296 \-- y (axis widget) 1297 1298Here the user could access the xData setting node of the 1299xy1 widget using ``Root.page1.graph2.xy1.xData``. To 1300actually read or modify the value of a setting, you should get 1301or set the ``val`` property of the setting node. The line 1302width could be changed like this 1303 1304.. code-block:: python 1305 1306 graph = embed.Root.page1.graph2 1307 graph.xy1.PlotLine.width.val = '2pt' 1308 1309For instance, this constructs a simple x-squared plot which 1310changes to x-cubed: 1311 1312.. code-block:: python 1313 1314 import veusz.embed as veusz 1315 import time 1316 1317 # open a new window and return a new Embedded object 1318 embed = veusz.Embedded('window title') 1319 # make a new page, but adding a page widget to the root widget 1320 page = embed.Root.Add('page') 1321 # add a new graph widget to the page 1322 graph = page.Add('graph') 1323 # add a function widget to the graph. The Add() method can take a list of settings 1324 # to set after widget creation. Here, "function='x**2'" is equivalent to 1325 # function.function.val = 'x**2' 1326 function = graph.Add('function', function='x**2') 1327 1328 time.sleep(2) 1329 function.function.val = 'x**3' 1330 # this is the same if the widgets have the default names 1331 Root.page1.graph1.function1.function.val = 'x**3' 1332 1333If the document contains a page called "page1" then ``Root.page1`` is 1334the object representing the page. Similarly, ``Root.page1.graph1`` is 1335a graph called ``graph1`` in the page. You can also use 1336dictionary-style indexing to get child widgets, 1337e.g. Root['page1']['graph1']. This style is easier to use if the names 1338of widgets contain spaces or if widget names shadow methods or 1339properties of the Node object, i.e. if you do not control the widget 1340names. 1341 1342Widget nodes can contain as children other widgets, groups of 1343settings, or settings. Groups of settings can contain child 1344settings. Settings cannot contain other nodes. Here are the useful 1345operations of Nodes: 1346 1347.. code-block:: python 1348 1349 class Node(object): 1350 """properties: 1351 path - return path to object in document, e.g. /page1/graph1/function1 1352 type - type of node: "widget", "settinggroup" or "setting" 1353 name - name of this node, e.g. "graph1" 1354 children - a generator to return all the child Nodes of this Node, e.g. 1355 for c in Root.children: 1356 print c.path 1357 children_widgets - generator to return child widget Nodes of this Node 1358 children_settinggroups - generator for child setting groups of this Node 1359 children_settings - a generator to get the child settings 1360 childnames - return a list of the names of the children of this Node 1361 childnames_widgets - return a list of the names of the child widgets 1362 childnames_settinggroups - return a list of the names of the setting groups 1363 childnames_settings - return a list of the names of the settings 1364 parent - return the Node corresponding to the parent widget of this Node 1365 1366 __getattr__ - get a child Node with name given, e.g. Root.page1 1367 __getitem__ - get a child Node with name given, e.g. Root['page1'] 1368 """ 1369 1370 def fromPath(self, path): 1371 """Returns a new Node corresponding to the path given, e.g. '/page1/graph1'""" 1372 1373 class SettingNode(Node): 1374 """A node which corresponds to a setting. Extra properties: 1375 val - get or set the setting value corresponding to this value, e.g. 1376 Root.page1.graph1.leftMargin.val = '2cm' 1377 """ 1378 1379 class SettingGroupNode(Node): 1380 """A node corresponding to a setting group. No extra properties.""" 1381 1382 class WidgetNode(Node): 1383 """A node corresponding to a widget. 1384 1385 property: 1386 widgettype - get Veusz type of widget 1387 1388 Methods are below.""" 1389 1390 def WalkWidgets(self, widgettype=None): 1391 """Generator to walk widget tree and get widgets below this 1392 WidgetNode of type given. 1393 1394 widgettype is a Veusz widget type name or None to get all 1395 widgets.""" 1396 1397 def Add(self, widgettype, *args, **args_opt): 1398 """Add a widget of the type given, returning the Node instance. 1399 """ 1400 1401 def Rename(self, newname): 1402 """Renames widget to name given. 1403 Existing Nodes corresponding to children are no longer valid.""" 1404 1405 def Action(self, action): 1406 """Applies action on widget.""" 1407 1408 def Remove(self): 1409 """Removes a widget and its children. 1410 Existing Nodes corresponding to children are no longer valid.""" 1411 1412Note that Nodes are temporary objects which are created on 1413the fly. A real widget in Veusz can have several different 1414WidgetNode objects. The operators == and != can test whether 1415a Node points to the same widget, setting or setting group. 1416 1417Here is an example to set all functions in the document to 1418be ``x**2``: 1419 1420.. code-block:: python 1421 1422 for n in Root.WalkWidgets(widgettype='function'): 1423 n.function.val = 'x**2' 1424 1425Translating old to new style 1426---------------------------- 1427 1428Here is an example how you might translate the old to new 1429style interface (this is taken from the ``sin.vsz`` 1430example). 1431 1432.. code-block:: python 1433 1434 # old (from saved document file) 1435 Add('page', name='page1') 1436 To('page1') 1437 Add('graph', name='graph1', autoadd=False) 1438 To('graph1') 1439 Add('axis', name='x') 1440 To('x') 1441 Set('label', '\\italic{x}') 1442 To('..') 1443 Add('axis', name='y') 1444 To('y') 1445 Set('label', 'sin \\italic{x}') 1446 Set('direction', 'vertical') 1447 To('..') 1448 Add('xy', name='xy1') 1449 To('xy1') 1450 Set('MarkerFill/color', 'cyan') 1451 To('..') 1452 Add('function', name='function1') 1453 To('function1') 1454 Set('function', 'sin(x)') 1455 Set('Line/color', 'red') 1456 To('..') 1457 To('..') 1458 To('..') 1459 1460.. code-block:: python 1461 1462 # new (in python) 1463 import veusz.embed 1464 embed = veusz.embed.Embedded('window title') 1465 1466 page = embed.Root.Add('page') 1467 # note: autoAdd=False stops graph automatically adding own axes (used in saved files) 1468 graph = page.Add('graph', autoadd=False) 1469 x = graph.Add('axis', name='x') 1470 x.label.val = '\\italic{x}' 1471 y = graph.Add('axis', name='y') 1472 y.label.val = 'sin \\italic{x}' 1473 y.direction.val = 'vertical' 1474 xy = graph.Add('xy') 1475 xy.MarkerFill.color.val = 'cyan' 1476 func = graph.Add('function') 1477 func.function.val = 'sin(x)' 1478 func.Line.color.val = 'red' 1479 1480PyQt programs 1481============= 1482 1483There is no direct PyQt interface. The standard embedding interface 1484should work, however. 1485 1486Non Python programs 1487=================== 1488 1489Support for non Python programs is available in a limited 1490form. External programs may execute Veusz using :command:`veusz 1491--listen`. Veusz will read its input from the standard input, and 1492write output to standard output. This is a full Python execution 1493environment, and supports all the scripting commands mentioned in 1494:ref:`Commands <Commands>`, a :command:`Quit()` command, the 1495:command:`EnableToolbar()` and the :command:`Zoom(factor)` command 1496listed above. Only one window is supported at once, but many 1497:command:`veusz --listen` programs may be started. 1498 1499:command:`veusz --listen` may be used from the shell command line by 1500doing something like: 1501 1502.. code-block:: bash 1503 1504 veusz --listen < in.vsz 1505 1506where :command:`in.vsz` contains: 1507 1508.. code-block:: python 1509 1510 To(Add('page') ) 1511 To(Add('graph') ) 1512 SetData('x', arange(20)) 1513 SetData('y', arange(20)**2) 1514 Add('xy') 1515 Zoom(0.5) 1516 Export("foo.pdf") 1517 Quit() 1518 1519A program may interface with Veusz in this way by using the 1520:command:`popen` C Unix function, which allows a program to be started 1521having control of its standard input and output. Veusz can then be 1522controlled by writing commands to an input pipe. 1523