Introduction to Python for Vulcan [@Mining_eng]
Introduction to Python for Vulcan [@Mining_eng]
www.maptek.com
Copyright
© 2018 Maptek™
Maptek, Vulcan, I-Site, BlastLogic, Eureka, PerfectDig, and the stylised Maptek M are registered
and unregistered trademarks of Maptek Pty Ltd; Maptek Computación Chile Ltda; Maptek
Computación Chile Ltda, Sucursal Perú; Maptek S de RL de CV; Maptek Informática do Brasil
Ltda and KRJA Systems, Inc. Registered marks are registered in one or more of the following
countries: Australia, Brazil, Canada, Chile, China, Greece, India, Indonesia, Mexico, Peru,
South Africa, Russia, Spain, the United Kingdom, and the United States of America.
ALL RIGHTS RESERVED. No part of this manual shall be reproduced, stored in a retrieval
system, or transmitted by any means - electronic, mechanical, photocopying, recording, or
otherwise - without written permission from Maptek™.
No patent liability is assumed with respect to the use of the information contained herein.
Although every precaution has been taken in the preparation of this manual, the publisher and
author(s) assume no responsibility for errors or omissions. Neither is any liability assumed for
damages resulting from the use of the information contained herein.
Due to the nature of the material, some hardware and software products are mentioned by
name. The companies that manufacture the products claim many of these product names as
trademarks. It is not the intention of Maptek™ to claim these names or trademarks as their own.
[email protected]
www.maptek.com
Revision History
August 31, 2018 – Molly Ison – North America - origin
2
Copyright
About Vulcan Documents
The following conventions are typically used in Vulcan™ training manuals and
guides.
Example Description
Design > Object Edit Text in bold are commands or options selected
from a menu, panel or button.
Top Down or Bottom Up Text in italics are used for emphasis, special
design method terms, tab names, column names, panel group
names, etc.
Designates a warning that, if not followed, can lead to a serious outcome such as
Caution:
data corruption.
www.maptek.com Page 3
Every effort is made to use consistent terminology throughout all Vulcan
documentation. The following terminology is typically used in manuals, guides
and help:
• The terms panel and dialog box may be used interchangeably. Dialog
may also be used as a general term to refer to subpanels and tabs.
• Panels can have tabs but panels with tree navigation can have subpanels
as well as tabs. The two parts of the panel are called panes. The left
pane also referred to as the navigation pane or tree pane, contains the
navigation list and the right pane is the subpanel and contains the details.
• The terms clear box and uncheck box may be used interchangeably.
• The terms context menu, right-click menu, and shortcut menu are used
interchangeably. They refer to task-specific menus that appear when you
right-click.
4
About Vulcan Documents
Contents
1 Introduction 7
2 Python Basics 9
Choose an Editor ......................................................................................................... 9
Highlight Syntax .................................................................................................. 10
Shortcuts ............................................................................................................. 10
Save Python Files ............................................................................................... 10
First Python Script ...................................................................................................... 10
Errors .................................................................................................................. 11
Comments ........................................................................................................... 11
Data Types ................................................................................................................. 11
Variables ............................................................................................................. 11
Numbers ............................................................................................................. 13
Boolean Values ................................................................................................... 16
Characters .......................................................................................................... 18
Data Structures .......................................................................................................... 18
Strings ................................................................................................................. 18
Lists..................................................................................................................... 23
Dictionaries ......................................................................................................... 27
Statements ................................................................................................................. 28
Whitespace and Indentation ................................................................................ 28
Conditional Statements ....................................................................................... 28
Loop Statements ................................................................................................. 33
File IO......................................................................................................................... 38
Reading and Writing Text Data ........................................................................... 38
Reading CSV Files .............................................................................................. 39
Writing CSV Files ................................................................................................ 40
Directory Access ................................................................................................. 44
Functions.................................................................................................................... 44
Python Modules ......................................................................................................... 46
os and pathlib Modules ....................................................................................... 46
Scientific Modules ............................................................................................... 48
3 Vulcan Module 51
Block Models .............................................................................................................. 51
Navigation ........................................................................................................... 51
Queries and Modification .................................................................................... 54
Pandas ................................................................................................................ 58
Executables ........................................................................................................ 60
www.maptek.com Page 5
Triangulations ............................................................................................................. 61
Navigation ........................................................................................................... 61
Building and Modification .................................................................................... 61
Properties ............................................................................................................ 64
Repair ................................................................................................................. 66
Isis Databases ............................................................................................................ 67
Navigation ........................................................................................................... 67
Queries and modification .................................................................................... 69
Design Databases ...................................................................................................... 72
DGD .................................................................................................................... 72
Layers ................................................................................................................. 74
Objects ................................................................................................................ 75
Points .................................................................................................................. 78
4 vulcan_gui Module 81
Selections................................................................................................................... 81
Triangulations...................................................................................................... 81
Pick Points .......................................................................................................... 82
GUI Layers .......................................................................................................... 84
Design Objects .................................................................................................... 84
Panels ........................................................................................................................ 87
Display ................................................................................................................ 87
Methods .............................................................................................................. 87
Data Retrieval ..................................................................................................... 91
6
Contents
Introduction
1
Vulcan contains an installation of Python which includes Vulcan interfacing
modules. Python can automate repetitive processes or perform tasks not possible
with standard Vulcan tools.
The Introduction to Python for Vulcan course introduces fundamental concepts
required to create basic Python scripts. Participants will learn to:
1. Create basic Python scripts.
2. Use Vulcan modules to interact with Vulcan data structures: block models,
Isis databases, triangulations, and design databases.
3. Generate scripts that interact with the Vulcan user interface.
a. Create simple panel interfaces.
b. Select objects from the screen.
c. Construct new design objects for on-screen viewing.
www.maptek.com Page 7
Chapter 1
8
Introduction
Python Basics
2
The first implementation of Python was started in 1989 by Guido van Rossom at
the Centrum Wiskunde & Informatica in Amsterdam. Version 1.0 was released in
1994. Python was named after the BBC television show Monty Python’s Flying
Circus.
Benefits of Python include the use of third party modules. The Vulcan module
allows for easy interface with the Vulcan environment. This chapter covers the
basic tools needed to create scripts in Python, which are required when using the
Vulcan module. Python scripts use the file extension py.
Some of the most common Python functions, variable types, and operators will be
covered in this manual. To discover more about Python functionality, online
documentation is available at http://docs.python-guide.org/en/latest/ as well as
many other sites.
Choose an Editor
The correct text editor can make writing and editing scripts much easier. Editors
can include functionality like colouring key words, advanced find and replace, and
file organization.
Integrated Development Environments (IDEs) include debuggers and tools for
compiling. Free examples include PyCharm® Community Edition and Visual
Studio Code®. Word processors like Microsoft Word® or Google Docs® are not
designed for writing code. No matter which editor is selected, it is key to configure
a few primary items as discussed in the following sections.
www.maptek.com Page 9
Highlight Syntax
Syntax highlighting makes the code easier to read and helps identify errors when
items are coloured incorrectly. Python scripts use the extension py. Most editors
will set the Python default syntax highlighting for these files. Refer to the editor
help guide for instructions.
Shortcuts
Keyboard shortcuts can save a substantial amount of time. The commonly used
shortcuts include:
Some editors may save files with a TXT extension by default, resulting in a file
Note:
named <filename>.py.txt. To avoid this format, select All types or Python
file in the Save as type drop-down list before clicking Save. Rename a file with
an incorrect extension in Windows Explorer.
Class Exercise
1. Open a text editor and enter the following code:
Chapter 2
10
Python Basics
4. The script should output Hello World! to the report window.
5. Repeat running the script using an IDE debugger and using the Vulcan menu
option.
Errors
Python will print an error message when unable to parse or execute a line of
code.
Syntax or parsing errors are often the result of typos or incorrect indentation.
Code with syntax errors usually cannot be executed. The error type is
SyntaxError and the message displays a carat (^) pointing at the earliest point in
the line where the error was detected.
Exceptions are errors detected during execution of the code. There are several
types of exception, such as ZeroDivisionError. The first part of the error message
is a stack traceback. The traceback shows how you got to the error. The last level
of the traceback is the place where the error occurred.
List of exception types: https://docs.python.org/3/library/exceptions.html
Class Exercise
After each step, run the program and read the error message. Restore the code
to its original state.
1. Remove the closing parenthesis from 01_HelloWorld.py.
2. Misspell print as prin.
Comments
Writing comments in the code is good practice. Comments can clarify a section of
code and provide documentation for other users. Single-line comments are
created by beginning a line with the hash character (#) and are automatically
terminated by the end of the line.
Data Types
This section covers the use of Python data types, such as numbers and strings.
Variables
Variables are named assignments between data values and their locations in the
computer memory. Variable names or identifiers must begin with an underscore
or letter. Any amount of alphanumeric characters and underscores can comprise
the identifier, no spaces or special characters.
www.maptek.com Page 11
Choosing an appropriate identifier is extremely important. An appropriate
identifier should describe the values the variable holds.
The type of the variable does not need to be declared before the variable is
created. Variable types are assigned by the type of data the variable contains.
To assign a value to a variable, enter the variable identifier on the left of the
assignment operator (=) and the value on the right. The value can be an
expression.
It is possible to reassign a variable. Upon reassignment, the old value is lost and
the new value is assigned the variable.
In many languages, the variable type is constant throughout the entire program.
As there is no such restriction in Python, the following code is valid:
Chapter 2
12
Python Basics
Exercise: Swap Variable Values
Instructions
Create a file named 02_SwapVariable.py. Use the example code below to
complete a script that will swap two variable values without simultaneous
assignment.
Any number of values can be swapped using tuple unpacking, which performs
simultaneous assignment. The number of variables on one side of the expression
must equal the number of values on the other side.
Numbers
This data type supports numerical values.
Integers
An integer is a positive or negative whole number with no decimal point. Its
Python type is int.
Floats
A floating point number has a decimal point and represents a real number. Its
Python type is float. There are some numbers that cannot be stored as a precise
floating point value. Python stores a close approximation.
For example, printing 0.1 + 0.2 with 18 digits after the decimal will return a
value that is not exactly 0.3. One method of handling the situation is to limit
direct comparisons and use a tolerance value to compare two numbers as shown
in the following example.
www.maptek.com Page 13
When any of the operands in an expression is a float, the result will be a float.
Operators
Python has most standard operators, similar to those seen in tools like Microsoft
Excel®. The following table gives examples of commonly used operators
available in Python.
- Subtraction 2 – 36 -34
% Modulus 617 % 3 2
** Exponentiation 5 ** 3 125
Chapter 2
14
Python Basics
Python also includes built in mathematical functions.
Function Return
divmod(x, y) (x // y, x % y)
Class Exercise
1. Add parentheses to the expression 6 * 1 – 2 to change the value from 4
to -6.
2. Evaluate 15 % 12, then use Python to check the result.
Python supports augmented assignment where the operator takes the left-hand
variable as one of its arguments and assigns the result back to that variable.
Combine a numeric operator with the assignment operator to form the augmented
assignment operator.
www.maptek.com Page 15
Boolean Values
A Boolean value is either True or False. Its Python type is bool.
Comparison Operators
Comparisons operators compare the values on either side of the operator and
return a Boolean value indicating the relation between them.
A list of commonly used comparison operators follows.
== Equality 5 == 3 False
!= Inequality 5 != 3 True
The equality operator (==) is different from the assignment operator (=).
Caution:
Attempting to use the assignment operator in a comparison results in a
SyntaxError.
Chapter 2
16
Python Basics
Exercise: Comparison
Instructions
Create a file named 03_NumberExercises.py.
The following example uses loops and an if statement to print odd or even for
each value of x the loop counts from 0 to 10. Fill in the statement with the correct
expression and comparison.
www.maptek.com Page 17
Characters
A character is a single letter, number, space, or symbol. In Python, characters are
manipulated and accessed as strings. A character delimited by single or double
quotation marks is a one-character string.
Data Structures
This section covers compound data types. These structures are containers for
other objects.
Strings
A string comprises smaller strings, each containing one character. Its Python type
is str. Strings are enclosed in single quotes ('), double quotes ("), or three of
each (''' or """). Triple quoted strings can contain either single or double
quotes without an escape character.
Strings cannot be modified. A single character in a string cannot be changed. A
new string must be created with the desired characters.
Escape Sequences
Escape sequences help represent string values that are difficult to include
directly, such as new lines. They are prefixed with a backslash (\) and escape
the next single character. Some escaped single characters give special meaning
like \n and \t, and others like \“ provide a means of quoting.. The following
table lists some common escape sequences.
Syntax Description
\t Tab
The print function automatically creates a new line at the end of the input.
Note:
Chapter 2
18
Python Basics
Operators
The operators + and * can be used to concatenate and repeat strings to create a
new string.
The Boolean comparison operators can be used to compare two strings. Python
uses the ASCII values of the characters for comparison.
Functions
Strings have several functions which test the characters of the string or return a
copy of the reformatted string.
www.maptek.com Page 19
The following script highlights some of the nuances of string functions.
Substrings
Slicing returns a subset of an original string. Each of the string’s characters
corresponds to an index, starting with number 0. A single index number in square
brackets ([]) returns the character in that position. A slice with syntax
s[start:end] returns the characters of string s from index start to index end
– 1. If the start index is omitted, the default start value is 0. If the end index is
omitted, the default end value is the last index of the string.
There are several methods to search strings and get the indices for substrings.
The membership operators in and not in check the existence of a substring in
a string.
Chapter 2
20
Python Basics
The following string methods find and replace substrings.
Class Exercise
1. Create the following script to experiment with string manipulation.
2. Insert a series of dashes on the line following an input string. The total length
of the dashes should equal the total length of the string.
3. Evaluate the following statements:
a. “apple” > “orange”
b. “pineapple” < “Peach”
c. “pear” not in “grapefruit”
www.maptek.com Page 21
Exercise: Extract Drillhole
Create a file named 04_ExtractDrillhole.py. Modify the file using the code
below to extract a drillhole number from a drillhole name.
Work with the general case rather than tailoring code to a single example.
Caution:
Chapter 2
22
Python Basics
Lists
A list represents an ordered collection of objects. Lists can be changed by adding
and removing objects. Any type of object may be included in a list.
Initialization
A list is created by listing its comma-separated elements in brackets. A list can
contain strings, numbers, Boolean values, or other lists. An empty list has no
elements and is denoted [].
Modification
Lists are mutable, meaning their elements can be changed.
As with strings, each of the list’s objects corresponds to an index, starting with
number 0. Individual elements can be accessed with the slice operator ([]) and
reassigned. list[start:end] returns the sublist from index start to index
end – 1. Attempting to access an element that does not exist results in an
IndexError.
There are several functions to add or remove elements in a list. A common use of
append is to add new values as they are encountered, such as new drillhole
data. The pop method removes an indexed element or sublist from the list. The
method insert(idx, x) inserts element x at index idx.
Class Exercise
Use ls = [1, 2, 4, 7, 16] to evaluate the following list outputs.
1. ls[1, 3]
2. ls[4] = 8
3. ls.append(32)
www.maptek.com Page 23
Table 2-7: Common List Functions
Recall that the split method for strings splits a whitespace delimited string into
a list of individual words. The inverse method is join. Call join on a separator
string with the list of words as a parameter.
Tuples
Tuples are like lists but are immutable. Once a tuple is created, it cannot be
changed. A tuple is created by listing its comma-separated elements in
parentheses. The slice operator, in and not in operators, and the functions
len and sum can be used with tuples.
Chapter 2
24
Python Basics
Exercise: Create and Print List
Create a file named 05_ArrayExercises.py. Generate a list with consecutive
values from a to z. Print the values separated by commas.
www.maptek.com Page 25
Exercise: Remove List Values
Open the script created in the last exercise, 05_ArrayExercises.py. Modify
the existing script using the code below. Remove the first and last names from
the Names list.
Chapter 2
26
Python Basics
Dictionaries
Dictionaries store pairs of data elements. Instead of storing the elements by an
index, dictionaries store a key-value set where the key is a defined identifier
referencing the value.
The following example shows how to construct a dictionary, add and remove a
value, query a value, and loop over all keys:
www.maptek.com Page 27
Statements
Statements control execution of code in a block. Each block limits the scope of a
portion of code.
Tabs and spaces cannot be mixed for indentation. Most editors support
translation of tabs into spaces. When the tab key is pushed, the editor inserts a
set number of spaces.
Conditional Statements
Conditional statements perform a task if a certain condition is met. The most
common conditional statement is the if statement.
If Statement
The if statement will evaluate if the entered expression evaluates as True or
False. The values 0, None, and [] (an empty list) evaluate as False. All other
values evaluate as True.
Values can be compared by their associated comparison operators. The following
examples evaluate grades for destination.
Chapter 2
28
Python Basics
Else and Elif
If else and elif statements allow other options to evaluate or perform if the
initial condition is False. This makes the statement more robust in complex
scenarios by allowing the potential return of more than one correct value.
In the following example, provided conditions evaluate in order. If the first if
condition proves false, the second condition in the elif statement evaluates. If
the elif condition proves false, the else actions perform.
Nested If Statements
More complex scenarios may call for multiple if statements. Note that the
following example using nested if statements returns the same results as the
elif example.
www.maptek.com Page 29
In the following example, conditions are ordered differently. In this case, all
material will route to the heap since the first condition proves true and ends the
statement.
Logical Operators
Logical operators allow testing of two or more conditions at one time. The logical
operators in Python are and, or, and not.
A set of statements joined by and is True if and only if all statements prove true.
A set of statements joined by or is True if any of the statements prove true. The
not operator negates the Boolean value of a statement.
Chapter 2
30
Python Basics
Exercise: Nested If Statements
Create a file named 06_Conditionals.py. Modify the example code below to
create a script using nested if statements to determine the destination of material
based on grade and contaminant values. Ensure that any material that has a
contaminant value greater than the contaminant cutoff is sent to the dump.
Material not sent to the dump is allocated to either the mill or heap based on
grade.
www.maptek.com Page 31
Exercise: Logical Operators
Open the 06_Conditionals.py file created in the last exercise. Create
another if statement that uses logical operators to accomplish the same material
evaluation task.
There are multiple correct solutions. Most scripts can be written in more than one
Note:
way.
Chapter 2
32
Python Basics
Loop Statements
Loop statements repeat a defined task for several times to complete an
operation. Python has two types of loops, for loops and while loops.
For Loops
A for loop processes each item in a list. The variable in the for statement is
called the loop variable. Any variable name can be chosen. The loop variable
iterates through a range, list or other data structure with the keyword in.
The body of the loop is an indented block of code. All the statements within the
block are performed during each iteration of the loop.
To access the index during the iteration, use the built-in function enumerate.
While Loops
A while loop processes only while a condition is True. The loop stops when the
condition evaluates as False. In the following example, the loop repeats until the
counter value reaches 10. The values 1 through 9 will be printed.
The body of the loop should change the value of the loop iterator so that
eventually the condition becomes false. It is easy to forget the iterator, which is
often the last line in the loop. The location of the iterator provides additional ability
to customize how and when tasks are performed inside the loop.
www.maptek.com Page 33
Stopping Loops
It can be necessary to modify the behaviour of a loop during processing to either
end the loop operation entirely or to skip to the next iteration.
The break statement exits a loop when an external condition is met, usually
inside an if statement. Any remaining iterations of the loop are also terminated
and the statement following the loop block is executed.
The continue statement skips the remainder of a specific iteration of a loop.
The loop will invoke the iterator and move to the next iteration.
Chapter 2
34
Python Basics
Exercise: Sums
Create a file named 07_Loops.py. Modify the example code below to create a
script that will sum all values from start to end.
www.maptek.com Page 35
Exercise: Nested Loops
Open the file 07_Loops.py created in the last exercise. Modify the example
code below to loop over two sets of values and print them out. In this example,
there are several geologic domains with a series of variables represented
numerically.
Chapter 2
36
Python Basics
Exercise: Nested Loop Offsets
In the 07_Loops.py file, output several dashed lines as shown below in two
different ways: with a single loop and with a sequence of nested loops.
www.maptek.com Page 37
File IO
Like other languages, Python contains functions to read, process, and evaluate
files and directories.
Similarly, to write to a text file, use open with mode w. In the following example,
use of the with statement automatically closes the file after the code block is
executed.
The filename variable can be just the file name if in the same directory as the
script, or the full path as shown in the preceding example.
The string prefix r or R in the file name treats the path as a raw string so that
string literals like \n and \t will not be treated specially.
The mode variable defines how Python will access the file.
Mode Description
“w” Open a file for writing. Existing file will be overwritten, or a new
file created, if file name does not exist
Chapter 2
38
Python Basics
Reading CSV Files
Python contains a standard csv module with a reader function to read csv
formats. To use this module, enter import csv at the beginning of the script.
The following example opens and prints the contents of sample.csv. The file is
opened in read mode and each line is read by the for loop until there are no
more new lines to read.
www.maptek.com Page 39
Example Script: Query Data
This example illustrates how to put data into a useable format and handle file
headers.
Create a file named 08_CSV_MinMax.py and enter the code below. The script
finds the minimum and maximum copper grade values.
Class Exercise
Explain what each line of code is doing.
The function writerow takes a list as its parameter. Each element of the list
corresponds to a separated output value.
Class Exercise
1. Change the row value from a list to a single string.
row = “The quick red fox jumped over the lazy brown dog”.
2. Remove newline=’’ from the open function parameters.
Chapter 2
40
Python Basics
If the output file is open in Excel when running the script, a PermissionError will
Note:
be thrown.
www.maptek.com Page 41
Exercise: Manipulate Column
Create a file named 09_FileIO_Manipulate.py. Modify the example code to
create a script that reads sample1.csv and creates a new file named
sample2.csv in which gold grades are converted from grams to ounces per ton.
Chapter 2
42
Python Basics
Exercise: Add Column
Modify the example code from the last exercise to read sample1.csv and
calculate gold equivalent grades in a new column. Output the resulting data with
new column to a new file named sample3.csv. Save the script as
10_FileIO_AddColumn.py.
www.maptek.com Page 43
Directory Access
To get a raw directory listing of files in the current working directory, use the
listdir function from the os library. Items can be returned as a list or iterated
in a loop.
Functions
Functions are named blocks of code that can be run multiple times in a script.
Functions are identified with the keyword def and can accept parameters
enclosed in parentheses.
The following function adds the values of an array to a base number.
• The function Add has two parameters, the base number and a list of
integers.
• Variables declared inside a function are called local variables and can
only be used within the function.
• The return call at the end of the function returns specific variables.
• The special variable __name__ evaluates to the name of the current
module. When run as the main program, the file is assigned the string
“__main__”. If the functions in the file are called through a different
module, the if statement will not execute.
Chapter 2
44
Python Basics
Exercise: Limit Input Values
Create a file named 11_Subroutines_Clamp.py. Enter the following code and
modify the commands to limit an input value so that the value falls between a
minimum or maximum value.
www.maptek.com Page 45
Python Modules
A module is a file containing Python definitions and statements.
Python comes with a substantial number of standard modules that cover most
operations. These modules contain functions that simplify the work needed to
create scripts. Python documentation contains a list of standard modules at
https://docs.python.org/3.5/library/.
To use a module, enter import <module>, where <module> is the name of
the required module. This will import all functions from that module. It is
customary to enter all import statements at the beginning of a script.
Individual functions or classes within a module can be imported using from
<module> import <function/class>. When imported in this way, the
module name no longer needs to be referenced.
Chapter 2
46
Python Basics
Class Exercise
1. If line 1, import os, is removed, which functions will no longer be available?
2. If line 2, import csv, is removed, which functions will no longer be
available?
The os module was previously standard practice, but the introduction of the
pathlib module allows paths to be treated as objects which can have attributes
and methods. This simplifies challenges such as moving files to a different
direction.
www.maptek.com Page 47
Scientific Modules
The Vulcan API includes several scientific libraries for Python, as well as
geometric and geospatial tools. A complete list is available in the help menu.
• Scientific:
o Scikit-Learn (Machine learning) http://scikit-learn.org/
o NumPy (fast arrays/matrices) http://www.numpy.org/
o SciPy library (numeric integration/optimization)
http://www.scipy.org/scipylib/index.html
o Pandas (Data analysis tools and structures)
http://pandas.pydata.org/
• Geometry/Geospatial:
o Shapely
o pyclipper
o pyproj
NumPy can also be used as a multi-dimensional data container. The Vulcan
module takes advantage of this functionality to get and set data in Vulcan
structures. A NumPy array is an indexed grid of values of the same type. It can
be initialized using square brackets.
Chapter 2
48
Python Basics
Exercise: Floating Point Tolerance
Create a file named 12_Module_Tolerance.py. Using the floating point
tolerance example, replace line 18 with an equivalent statement using a single
Python function to determine whether the two values are within the desired
tolerance.
www.maptek.com Page 49
Chapter 2
50
Python Basics
Vulcan Module
3
Vulcan provides several modules which integrate with Python. The Vulcan
module covered in this course is named maptek and has submodules vulcan
and vulcan_gui.
The vulcan module allows access to Vulcan data such as block models, Isis
databases, and triangulations. Design database (DGD) layers and objects can be
accessed through the vulcan module without interacting through the graphical
interface.
Refer to the help menu for detailed module documentation. Python help is found
at Vulcan Menu Topics > File > Python.
Scripts or examples in this chapter require the import maptek as vulcan
command at the beginning of the script.
Block Models
A new block model can be created and populated through a Vulcan script. This
course will focus on navigating and reading and writing values within an existing
block model.
Navigation
Traversal
The function vulcan.block_model(model_path, mode) will create a
Vulcan block model object that opens the block model file and stores relevant
information for using the block model class in the Vulcan module. As with file
input/output, the with statement limits the scope of the block model object and
closes the block model when finished.
www.maptek.com Page 51
The following example shows a while loop traverse through the block model. Note
that the blocks have positions defined by sequential order, but this order does not
directly give information regarding either world or model coordinates.
The loop for block in bm will also loop through the block model in
sequential order, giving access to each block’s variables.
Chapter 3
52
Vulcan Module
Coordinates
The find_world_xyz(x, y, z) method moves to the specified block in the
block model using world coordinates. It will return a value of 1 if it fails to find a
block at the specified location. It is best to call this function in an if statement so
an error message can print when a block is not found.
The find_xyz(x, y, z) method moves to the specified block using
coordinates relative to the block model extents.
Selections
Block model selections locate specific blocks based upon provided criteria.
Enter bcalc in the Native TCSH shell to return a list of the provided selection
Tip:
conditions.
www.maptek.com Page 53
Queries and Modification
The method field_list() returns a list of all variables. Methods
is_field(), is_number(), and is_string() verify the existence and type
of a specified variable.
When navigating individual blocks, the variable values can be accessed through
the index, where the index value is the variable name. Values accessed in this
way can be set via assignment.
The method get(variable) returns the value of the variable for the current
block, and get_multiple(vars) can be used to return a list of values for
multiple variables.
The method get_data(variable, selection) gets the values of a set of
blocks, or all blocks if no selection is provided. The return value is a NumPy
array. The data can be batch modified through the fill method or by applying an
equation to the entire selection. The modified data is pushed back to the model
via put_data(variable, data, selection).
A new variable may be added with add_variable(name, type, default,
description). It is also possible to delete variables, add blocks, and move
blocks. These operations should be done with great care.
Deleted and modified data cannot be easily undone if at all. Create a backup of
Caution:
the block model before making significant changes.
Chapter 3
54
Vulcan Module
Example Script: Inquire
Using the example code below, create a script named 13_BM_Inquire.py
www.maptek.com Page 55
Exercise: Block Calculation
Create a script named 14_BCalc.py. Modify the example code below to flag a
block model with a value using a selection. The selection to flag blocks in a plane
is “-p 0.3 0.3 0.3 -200”. Include the quotes in the selection.
Chapter 3
56
Vulcan Module
Exercise: Spatial Block Calculation
Create a script named 15_BCalc_Spatial.py. Modify the example code below
to create a script that will look at blocks at some vertical offset and set the value
of the variable flag2 to 2 if the flag variable has a value of 1.
www.maptek.com Page 57
Pandas
The Pandas library provides access to data analysis tools and structures. Block
models can be easily manipulated using Pandas structures.
The function get_pandas(variables, selection) returns the block model
data as a pandas.DataFrame. The data can be queried and manipulated using
Pandas library functions and saved back to the block model with
put_pandas().
The following example shows some of the flexibility in manipulating and viewing
data with Pandas.
Pandas can also be used to read and manipulate csv files, time series data, and
other relational data.
Chapter 3
58
Vulcan Module
Exercise: Model Path
Earlier, methods for looping through the model were discussed. It is beneficial to
see the path taken by Vulcan to move through the model.
Create a new script and name it 16_ModelPath.py. Use one or more methods
to create a CSV file which reports the coordinates of every block in model.bmf.
www.maptek.com Page 59
Executables
Vulcan executables that take a block model as an input parameter can be run
through a Python script. The os module is used to run the desired command
string.
Chapter 3
60
Vulcan Module
Triangulations
Triangulations can be built, queried, modified and repaired through a script.
Navigation
Initialize the triangulation object using the constructor
vulcan.triangulation(name, mode). Iterate through each node or each
facet using the generators nodes and faces as seen in the following example.
www.maptek.com Page 61
Chapter 3
62
Vulcan Module
Exercise: Creation
Create a new script named 17_Triangle.py. Modify the following code to
create a triangulation with two triangles at the coordinates below.
www.maptek.com Page 63
Properties
Many functions give information about triangulation properties.
Chapter 3
64
Vulcan Module
Exercise: Elevation and Intersections
Create a script named 18_Triangulations.py. Find the elevation of the given
coordinate on the topography, topo.00t. Determine the intersection of the given
line segment as points.
www.maptek.com Page 65
Repair
The methods to repair a triangulation are close(), which attempts to close an
open triangulation, and clean(), which tries to remove consistency and crossing
errors.
As with Vulcan menu options, the resultant triangulation after a repair is not
Caution:
guaranteed. Triangulations should be backed up before attempting repair
functions.
Chapter 3
66
Vulcan Module
Isis Databases
The Isis database class allows access to any Vulcan Isis database, including
drillholes, composites and samples.
Navigation
The triangulation object opens with the constructor vulcan.isisdb(name,
mode, env). The mode is ‘r’ for reading and ‘w’ for writing. Env is the project
environment, such as krj or std.
Isis databases consist of keys. Each key has records stored in predefined tables,
and each table has predefined fields. The methods key_list, table_list,
and field_list return lists of all keys, all tables, and all fields for the current
table, respectively.
Databases use for loops to move from one key or record to the next. There are
also functions for going directly to a specific key or a specific table of the current
key. The following example shows how different generators work:
www.maptek.com Page 67
Exercise: Read Database Tables and Fields
Using the following code to access the database, print out all the tables and fields
in the database. Save the script as 19_IsisTables.py.
Chapter 3
68
Vulcan Module
Queries and modification
The following methods read database information such as the current table or
field values. The following list includes methods for modifying values in the
database.
www.maptek.com Page 69
Exercise: Read Database
Create a new file named 20_IsisDB.py. Modify the following example code to
create a script that reads through a database and prints out the survey
information for hole LK177 in the lavdrill_holds.dhd.isis database.
Chapter 3
70
Vulcan Module
Exercise: Manipulate Database
Modify the code below to create a script that will set the value of the FLAG field in
the database to 1 if the rocktype field RT is 101 and the gold grade is above 1.5.
Use the lavcmp_data.cmp.isis composite database. Save the script as
21_IsisDB_Manip.py.
www.maptek.com Page 71
Design Databases
The layers and objects in design databases can be directly queried and modified
through their entries in the DGD database. It is no longer necessary to open
Vulcan or use the graphical user interface to work with design data coordinates,
colours, and other attributes.
DGD
All design data is contained in dgd.isis files. The vulcan.dgd(filename,
mode) class allows the database to be opened and closed and queried for lock
status.
Layers exist inside the dgd.isis file and are not independent files. Dgd methods
can take objects of the layer class and save or delete them in the database.
Chapter 3
72
Vulcan Module
Exercise: Copy Layer
Create a script named 22_CopyLayer.py. In the database
lgdscratch.dgd.isis, make a copy of the layer FOO under the new name
MORE_FOO.
www.maptek.com Page 73
Layers
Each design object belongs to a layer. The layer class, vulcan.layer(name),
allows get/set access to layer names, descriptions, and other properties. A
named object can be found or a list of objects returned from a layer.
The Vulcan object types that can be returned from a layer are arrow,
dimension, polyline, text, and text3d.
Chapter 3
74
Vulcan Module
Objects
The object class vulcan.obj() is the base class that is shared to all object
types. Instance variables listed here are available to every type of object. All
instance variables have getters which return the variable, and most of them have
setters that assign a new value to the variable.
• type (get_)
• layer (get_)
The following example shows the equivalence between getters and setters and
instance variables.
Polyline
A polyline can be either an open line or a closed polygon.
The vulcan.polyline(point_list) class has the following instance
variables:
• closed (is_closed())
• clockwise (is_clockwise())
www.maptek.com Page 75
Functions to modify coordinates and perform some common actions and
calculations are listed in the following table.
Chapter 3
76
Vulcan Module
Class Exercise
Describe what the two polygons look like before running the script.
Text
The vulcan.text() class handles 2D text. It has the following instance
variables:
www.maptek.com Page 77
Text3d
As with 2D text, the vulcan.text3d() class can modify 3D text by line and
change its properties.
Text3d uses the same functions as 2D text in Table 3.6.
Its instance variables are as follows:
• origin
• direction
• normal
• scale
• height
• width
• font
• italic
• horizontal_align
• vertical_align
Points
The vulcan.point class is used to get point coordinates, point name, and
connection value.
The class has one method, distance(point2), that calculates the distance
between the point object and a second point.
The class has the following instance variables:
Chapter 3
78
Vulcan Module
Exercise: Calculate Polyline Center Average
Create a script named 23_PolylineAverage.py. Modify the example code to
access the layer AVERAGE and the object named AAA.
Calculate the center average (the average x, y, and z of all points) using point
values. Test that you get the same value as the center_average() function
within a reasonable tolerance.
www.maptek.com Page 79
Chapter 3
80
Vulcan Module
vulcan_gui
4
Module
The vulcan_gui module allows access to the user interface. Design data
loaded in Vulcan can be selected and user created panels can be generated.
This functionality gives the scripter the ability to create reusable workflows where
other users can easily make selections and enter parameters.
Scripts using the vulcan_gui module require interaction with an open Vulcan
design database.
Selections
Selections allow the user to pick objects from the screen.
Triangulations
Triangulations can be selected, loaded, and removed from the screen.
Triangulations selections return the name of the triangulation as a string. To
access the triangulation properties, it is necessary to create an instance of the
triangulation.
www.maptek.com Page 81
Table 4-1: Triangulation Selection Functions
Pick Points
This class picks points inside the Vulcan GUI. The points do not need to be
associated with an existing object. A click anywhere on the screen will record the
point.
Chapter 4
82
vulcan_gui Module
Exercise: Create Circle
Create a script named 24_Stamps.py using the code below as a base. The
script should create a circle at a location interactively chosen in the GUI.
www.maptek.com Page 83
GUI Layers
Vulcan GUI functions can load a layer and save loaded layers. The class will
attempt to use any open instance of Vulcan and its open design database. It is
not necessary to specify the database name.
Mode Definition
Design Objects
The object selection class is initialized with
vulcan_gui.selection(prompt). Objects are returned as their vulcan
type. Each selected object creates an instance of the selection class.
Selections are made using the following instance variables:
Chapter 4
84
vulcan_gui Module
Criteria options determine which types of objects can be picked, and include
• ‘ALL’
• ‘LINE’
• ‘POLYGON’
• ‘TEXT’
• ‘3DTEXT’
Selection types determine which groupings of objects can be picked, and include
• ‘NOTYPE’
• ‘BYLAYER’
• ‘BYNAME’
• ‘BYGROUP’
• ‘BYFEATURE’
• ‘BYALL’
Display mode determines how the object is shown on the screen. Shadowing or
highlighting selected objects prevents the user from attempting to select them
twice. Modes include
• ‘VISIBLE’
• ‘INVISIBLE’
• ‘SHADOW’
• ‘HIGHLIGHT’
• ‘VISIBLE_AND_POINTS’
• ‘SHADOW_AND_POINTS’
• ‘HIGHLIGHT_AND_POINTS’
The instance variable objects contains a list of selected objects. The function
num_obj() returns the number of objects in the selection. The function next()
moves from the current to the next object in the selection and is used to loop
through the objects.
To initiate the selection, use the function pick(layername=None,
group=None, feature=None).
www.maptek.com Page 85
Example Script: Modify Selected Object Color
The example script below modifies the colour of a selected object in Vulcan. Save
the code to a script named 25_Selection_Recolour.py.
TODO: FIX THIS
Chapter 4
86
vulcan_gui Module
Panels
The python_gui module contains two classes for creating panels, the panel
class and the gpan class. The section covers the panel class. Details regarding
gpan dialog boxes can be found in the Vulcan help menu under Vulcan Menu
Topics > File > Python > Vulcan GUI Classes > gpan.
The panel class creates panels with a wide range of methods including basic
input, check boxes, file lists, and colour pickers. Panels provide the ability to build
robust scripts with an intuitive input interface for the end user.
Display
Create an instance of the panel class with vulcan_gui.panel(). Display the
panel with the method display().
A block on the panel with an option border and title can be created using
begin_block(border=False, title) and end_block().
Methods
Each of the following methods can be used to add a component to the panel for
the required input.
Static Text
The statictext(prompt, bold=False) method creates plain text on the
panel used for instructions or information regarding input parameters. This text is
not modifiable.
The staticline() method creates a horizontal line on the panel.
Edit Box
The editbox(tag, prompt, defaultVal=None, width=None) method
generates a box on the panel which can receive either string or numeric values.
For more specialized input, numberbox(tag, prompt, defaultVal=None,
width=None) and integerbox(tag, prompt, defaultVal=None,
width=None) accept numeric and integer values only.
www.maptek.com Page 87
The accepted parameters are
Check Box
The checkbox(tag, prompt, checked=False) method creates a check box
on the panel which sets the value of the return variable to True or False.
Chapter 4
88
vulcan_gui Module
Radio Button
The radio button allows the user to choose exactly one of a set of selection
options. Its method is radiobutton(tag, prompt, initial=False,
bank=0). All radio button options in the same bank will be logically grouped
together so that exactly one of them must be chosen. It is good practice to set a
default value where one button option is True and the rest are False.
Object Attributes
The panel class contains built in selectors for colour, line style, and pattern, as
defined by Vulcan indices.
The colour selector method is colour(tag, prompt,
defaultVal:int=None).
The line style selector method is linestyle(tag, prompt,
style:int=None, thickness:int=None).
The pattern selector method is pattern(tag, prompt,
defaultVal:int=None).
www.maptek.com Page 89
Exercise: Create Panel Controls
Create a panel with at least three different controls and one file selector. Save the
script as 26_Panel_Exercise.py.
Chapter 4
90
vulcan_gui Module
Data Retrieval
After the panel has been displayed and returned, the panel data can be retrieved
as a dictionary of key/value pairs, where the key is the tag for each element.
The instance variable values returns the dictionary and has the getter and setter
get_values() and set_values(values).
The values can also be saved and loaded as a specification file using
save_spec(filename) and load_spec(filename).
www.maptek.com Page 91
Exercise: Modify Object Colour in Panel
Open 25_Selection_Recolour.py. Modify the script to pick the new object
colour using a panel.
Chapter 4
92
vulcan_gui Module