Auxiliary Tcl and Python Commands

Beside the listed commands for manipulating chemical and non-chemical objects, the standard Tcl scripting interface is enhanced with a collection of additional commands which do not belong to one of the two big groups. This is a list of these commands:

Mathematical expression enhancements

The Cactvs toolkit adds a number of commonly used mathematical functions to the interpreters. For Tcl , this means they are implemented as extensions to the math expression engine. The mathematics enhancements are implemented as normal module functions in Python . Python does not distinguish between normal and math functions.

The following functions are available:

avg

avg arg ...
avg(arg,...)

Interpret the arguments as numeric values and compute their average.

bitvector

bitvector and vector ?vector?...
bitvector cmp vector1 vector2
bitvector cmpall vector1 vector2
bitvector count0 vector1 ?vector2?...
bitvector count1 vector1 ?vector2?...
bitvector create length ?basevalue? ?togglepositions?
bitvector distance vector1 vector2
bitvector or vector ?vector?...
bitvector nand vector ?vector?...
bitvector nor vector ?vector?...
bitvector not vector
bitvector parse vector
bitvector record0 vector ?offset? ?length?
bitvector record1 vector ?offset? ?length?
bitvector screen vector1 vector2
bitvector screenall vector1 vector2
bitvector size vector1 ?vector2?...
bitvector test0 vector ?offset? ?lengt?
bitvector test1 vector ?offset? ?lengt?
bitvector xor vector ?vector?...
Bitvector(length=,?basevalue=?,?togglepositions=?)
Bitvector.Create(length=,?basevalue=?,?togglepositions=?)
Bitvector.Parse(data)
bv.cmp(vector)
bv.cmpall(vector)
bv.compare(vector,?cmpflags?,?c1?,?c2?)
bv.count0()
bv.count1()
bv.distance(vector)
bv.m_and(?vector=?,...)
bv.m_not()
bv.m_or(?vector=?,...)
bv.nand(?vector=?,...)
bv.nor(?vector=?,...)
bv.record0(?offset=?,?length=?)
bv.record1(?offset=?,?length=?)
bv.screen(vector)
bv.screenall(vector)
Bitvector.Size(?vector?,...)
bv.test0(?offset=?,?length=?)
bv.test1(?offset=?,?length=?)
bv.xor(?vector=?,...)

This command provides basic functionality for the processing of bit vectors on a string level, or as binary pre-parsed objects. String representations of bit vectors understood by this command consist of 0 and 1 characters, optionally prefixed by a percent or B character. Bitvectors with this encoding style can, for example, be obtained from a Tcl data recall command on chemistry object bitvector data items.

In both the Tcl and Python interfaces, decoded bitvectors are internally represented as binary custom language interface objects. This avoids re-parsing strings if the objects are used in multiple processing commands.

Example:

set vector [ens get $ehandle E_SCREEN]

The following subcommands are available:

bitvector and vector ?vector?...
bitvector or vector ?vector?...
bitvector xor vector ?vector?...
bitvector nand vector ?vector?...
bitvector nor vector ?vector?...

These are the standard boolean operations. nand and nor yields the inverted result of the and and or operations. If no arguments beyond the first are given, the result is the input vector for and, or, xor , and the inverted input vector for the rest. In case the vectors are of different lengths, they are virtually padded with zero bits to the size of the largest vector. eor is an alias name for the xor operation.

bitvector not vector

Invert the vector in bit-wise fashion.

bitvector test1 vector ?offset? ?len?
bitvector test0 vector ?offset? ?len?

Return a list of the vector index positions (starting with zero) which have a set or unset bit. Optionally, an offset for the first bit to be tested, and the maximum number of bits to be tested may be specified. By default, testing begins with the first vector position (index 0) and continues until the end of the vector. The subcommand test1 may be abbreviated to test . bitvector index0 and bitvector index1 are aliases for this command.

bitvector record1 vector ?offset? ?len?
bitvector record0 vector ?offset? ?len?

These commands are equivalent to the test0/index0 and test1/index1 commands above, except that they report the selected bit positions starting with one instead of zero, in the customary fashion of file record counting.

bitvector create length ?basevalue? ?togglepositions?

Generated a new bitvector of the specified length. By default, it is set to all zeros. The base value parameter, which may be 0 or 1, can be used to generate a vector with all set bits instead. If the toggle positions argument is used, it is expected to be an integer list with 0-based vector indices were the bit value in the new vector should be flipped.

bitvector parse vector

This command parses a vector representation (which can be a string representation, or already a bitvector object, in which case no real work is performed) and creates a new pre-parsed bitvector object.

bitvector screen vector1 vector2

Perform a screening operation on the first bitvector. The command returns the first 0-based index position where a bit is set in the second vector, but not in the first. If all set bits in the second vector have counterparts in the first vector, minus one is returned. The bitvectors may be of different length. The shorter vector is assumed to be filled up with zero bits. In a standard application, the first argument is a feature vector of a structure, and the second vector a feature vector of a substructure.

bitvector screenall vector1 vector2

Perform a screening operation on the first bitvector. The command returns a list of all 0-based bit positions where a bit is set in the second vector, but not in the first. If all set bits in the second vector have counterparts in the first vector, an empty list is returned. The bitvectors may be of different length. The shorter vector is assumed to be filled up with zero bits. In a standard application, the first argument is a feature vector of a structure, and the second vector a feature vector of a substructure.

bitvector count1 vector1 ?vector2?...
bitvector count0 vector1 ?vector2?...

Count the total number of set or unset bits in all the specified vectors. bitvector count is an alias for bitvector count1 .

bitvector distance vector1 vector2

Compute the Hamming distance between the vectors.

bitvector cmp vector1 vector2

Compare the two bitvectors and return the 1-based position of the first bit which disagrees. If the bit is set in the first vector, a the position is returned as a positive number, and as a negative number when the bit is set in the second vector. If both vectors are identical, or are identical if the shorter vector is assumed to be filled up with zero bits, the return value is zero. The alternative subcommand name compare is an alias.

bitvector cmpall vector1 vector2

Compare the two bitvectors and return a list of the 1-based bit positions where the two vectors disagree. If at any such position the first vector has a set bit, the position is listed as a positive number. In the opposite case, the position is entered as a negative number. If the vectors are identical, or are identical if the shorter vector is assumed to be filled up with zero bits, the return value is an empty list. The alternative subcommand name compareall is an alias.

bitvector size vector1 ?vector2?...

Returns the size of the largest bit vector in the argument set.

The Python implementation additionally supports standard copy and pickle methods, with-clause, and overloaded numeric operators ~ , & , ^ , | as well as &= , |= , ^= . The len() method returns the vector length. A bitvector has a boolean true value if any of its bits are set. Setting and retrieving individual bits via indices is also supported:

b[0] = b[1]

Due to syntactic limitations in the generic Python parser, the and , or and not methods cannot be named such - these are reserved words. Instead, they are accessible as m_and , m_or and m_not . The other bit methods ( nand , nor , xor ) are implemented with their normal name, but also accessible with the same prefix. The Python -only method compare is equivalent to a prop compare statement, except that it is an instance method, not a class method.

bread

bread tcl_filehandle format ?var..?

This command reads formatted binary data from an output channel. The specified Tcl channel is automatically configured for binary data for the duration of the command and then restored to the original state.

The command is complementary to the bwrite command described below and uses the same formatting specifications.

Multiple values sharing the same format can be read in one statement with a set of recipient variables is specified. The return value is the value of the last item read. If no variables are used, one item is read and returned, but not stored in a variable.

This is a Tcl -only command.

Example;

set s [bread $channel string16]

bwrite

bwrite tcl_filehandle format data ?data?...

This command writes formatted binary data to an output channel. The specified Tcl channel is automatically configured for binary data for the duration of the command and then restored to the original state.

This is a Tcl -only command.

If more than one data item is specified, the same format is used for all the data items. For most formats, the binary data layout is not changed and it thus platform-dependent. The exception are those formats which are prefixed with an X: These follow the platform-independent XDR encoding standard (RFC 1014) in their layout (network byte order, MSB first), but not in the stored item size (the byte size of smaller objects is not expanded to multiples of four). The following formats are supported:

The string format may contain additional length and pad character specifications. If a pad character is used, it must be supplied as its ISO Latin code. This makes it simple to use zero bytes as filler.

Example:

bwrite stdout string16:[ctype ord x]

writes a string which always occupies exactly 16 bytes. If it is longer, the extra characters are ignored. If it is shorter, it is padded with “x“ characters. A zero byte is not written, because this string has an explicit length.

The bread command provides the complementary functionality to read binary data into variables using the same format specifications as template.

color

color ?-alpha? ?-depth n? ?-hex? ?-javaint ?-name? ?-shade delta? ?-tuple?		colorname/colorspec
color(color=,?format=?,?depth=?,?alpha=?,?shade=?)

Decode a color name. On Unix systems, color names are looked up in the local X11 color database. On the PC platform, a representative X11 color database dump is compiled into the application. In addition to English color names, the standard hex color notation, such as #rrggbb or #rgb, may be used, with or without alpha channel data. If a hex color notation has 4, 8 or 16 hex digits, the value is interpreted as # rgba , # rrggbbaa and # rrrrggggbbbbaaaa , respectively. In case of 12 hex digits (12 is both divisible by 3 and 4), the interpretation # rrrrggggbbbb takes precedence. Color names are case-insensitive.

By default, a color depth of 16 bits is assumed, and the returned color component values are thus in the range 0..65535. Smaller or larger color component value ranges may be specified by an explicit depth value, which must be in the range between 2 and 24. Depth 8 is used for the commonly used format with 8 bits per channel.

If the - shade option is used, the decoded color value is darkened or brightened by the specified amount by component-wise addition before it is output in the selected format. The shading value is scaled according to the selected color depth, i.e. with a color depth of 8, the useful minimum and maximum scale values are -255 and +255, while with a color depth of 16 the limits are -65525 and +65535. The transformed color values are automatically clamped to the white and black extremes, so the output will always be a valid color representation. Shading is not applied to the alpha/opacity channel. A shading value of zero has no effect in any color depth.

The default return format is a list with the decimal RGB values of the decoded color. This corresponds to the explicit mode -tuple. If the - hex option is set, the output is formatted as a single hex-encoded color value, and - javaint returns a standard Java color signed int color value. If the - alpha option is set, the format of the output includes the opacity value as the fourth component in RGBA order, either as an additional list element or appended to the hex string. The - javaint value always includes an alpha component.

With the - name option the command attempts to find the most closely matching color name in the database for the decoded and transformed color values and return that name instead of a color component list or hex encoding.

The Python version uses a single format argument. It can be set to either tuple , hex , name or javaint .

The command may also be spelled colour instead of color .

Example:

color -depth 8 -hex Red

returns #FF0000.

color -depth 8 -shade -0x10 -hex #808080

returns #707070

creverse

creverse string
creverse(string)

Reverse a string.

Example:

creverse abc

returns cba .

daemonize

daemonize ?priority? ?closefiles?
daemonize(?priority=?,?closefiles=?)

Transform the current process into a daemon process which is decoupled from all control terminals and runs in the background until finished or terminated. The current process is forked, and the old foreground process exited.

By default, the background process priority is unchanged. Alternatively, a new priority may be specified as the first optional argument. If it not an empty string, an attempt is made to set the process priority to the new value. No error message is generated when the attempt fails. Useful priority values depend on the platform. On Linux, the range is 0...20, with 20 being the lowest priority. Increasing the priority, by using a value lower than the current process value, requires non-standard permissions, usually an effective application user ID of root.

By default, all open file handles are closed. If the optional closefiles parameter is set to 0, most file handles are kept open. An exception are the standard input, output and error channels. These are always redirected to /dev/null, regardless of the option value. Note that the closing of the file descriptors does not automatically invalidate any Tcl scripting language references to these, such as standard Tcl file or socket handles, or toolkit molfile handles. These should be explicitly closed by the application script before this function is called. Otherwise, any use of these stale handles results in errors.

This command is only available on Unix-based platforms.

decode

decode mode data ?extra?
decode(mode=,data=,?extra=?)

This command decodes a number of commonly encountered encoding formats for string and binary data. The decoded data is returned as command result. The mode parameter decides which decoding scheme is used. For the Python version, the mode is usually specified without the leading -, but this is not required. The following modes are available:

The decoded data may contain zero-bytes and other special characters and may thus need special care in further processing. The counterpart of the decode command is the encode command, which can be used to encode data in all recognized decoder formats.

For historical reasons, the - zlib* variants can also be invoked as the same command starting with - zip* .

encode

encode mode data ?mode_arg?
encode(mode=,data=,?extra=?)

This command is the counterpart to the decode command. It is not completely identical, though . There are encoding schemes for which no corresponding decoding method has been implemented. Additionally, the decoder automatically recognizes certain variants of encoding schemes, which need to be selected explicitly on the encoder side. The encoded data, which may be binary, is returned as command result. In the Python version , the mode is usually specified without a leading -, but this is not required. The recognized encoding modes are:

The - zlib* encoding variants can also be invoked as the same command starting with - zip* .

fcgi

fcgi subcommand ?args?

This command manages I/O when running an application script as an FastCGI ( FCGI ) Web application. Only selected interpreters provide this command, for example the standard tclcactvs and the stand-alone csweb variant.

There is currently no Python interface for this command.

In addition to providing the fcgi command, these interpreters also register additional pre-opened Tcl channels f cgi-stdin , fcgi-stdout and fcgi-stderr. Reading from or writing to these channels with the normal Tcl I/O commands directly moves the data to or from the FCGI server communication channels.

The following subcommands are supported:

fcgi accept ?redirect? ?autoexit?

This command enables FCGI -style socket communication with the Web server controlling this application and is usually the first command in an FCGI application.

If the redirect argument flag is set (it is on by default), the stdout , stderr and stdin Tcl channels are redirected to the corresponding FCGI multiplex socket. All normal Tcl I/O commands automatically use the multiplex socket instead of the standard channels if they are referring implicitly or explicitly to the standard channels. In addition, Web-typical properties like E_GIF , E_VRML , E_PICT_IMAGE , E_EPS_IMAGE , E_SVG_IMAGE , E_EMF_IMAGE and X_GIF are aware of this redirection and also send their output to the socket in case it is sent to one of the standard channels instead of a disk file. The current redirection status is mirrored in the read-only control variable ::cactvs(fcgi_redirect) .

The standard output is sent to the remote browser. For normal Web applications, the output is typically HTML or some image format. Output must be started with a standard HTTP header (but no status code), which ends with an empty line. After that, the HTML or other content is added. Standard error gets sent to the Web server error log. This is simple text. Standard input contains form field data if the CGI call was from a form page. It can be decoded with the uncgi command. Query data specified as part of the URL (after a question mark) can be read from the environment variable ::env(QUERY_STRING) .

If the autoexit flag is set (it is also set by default), the application automatically exits if the socket communication results in an error or EOF . The return value is a status code and zero in case a normal communication was initiated. In case automatic exiting is disabled, a negative status code is returned if there is an error.

The process can be terminated by the FCGI Web server module after some time of inactivity, or a fixed count of invocations. In addition, multiple processes with the same script may be started by the module in parallel. In case there is a load balancer, subsequent requests may even be sent to different physical hosts. For these reasons, it is generally not reliable to store global data in the script which should still be available in the next invocation. Instead, internal state like temporary objects should be cleaned up when a request has been executed and data which may be needed in a later processing step offloaded to storage using a lightweight session key or cookie as identifier - typically either to a disk file, or some distributed caching mechanism like memcached (see the memcached command).

Since FCGI scripts remain running after processing a request, edits to the script file are not immediately recognized. In order to pick up changes, all running interpreter processes with the script must be killed. They are automatically restarted by the FCGI Web server module on the next invocation.

fcgi finish ?redirect?

This command finishes the processing of a request. All buffered output is flushed to the server. The next request can then be waited for by a new call to fcgi accept .

If the redirect flag is set (it is set by default), any existing stdout , stderr and stdin redirections to the FCGI socket are canceled. All standard channels as seen by the script interpreter and certain image properties (see description of fcgi accept command) are reconnected to their original streams. The current redirection status is mirrored in the read-only control variable ::cactvs(fcgi_redirect).

fcgi puts ?-nonewline? ?channel? data

This command is the same as the standard Tcl puts command, except that it operates on the stdout and stderr equivalents of the FCGI communication model. In case a channel is specified, only stdout and stderr are possible argument values. The command is primarily useful in case the automatic redirection feature of the fcgi accept command was not used. Output is only possible after the invocation of an fcgi accept command and before the issue of a closing fcgi finish command.

fcgi read

This command reads the FCGI equivalent of stdin until EOF is encountered and returns the data as a byte vector. In case FCGI redirection is active, the standard Tcl read command can be used as an equivalent.

fcgi redirect ?on/off?

This command may be used to explicitly invoke or cancel the redirection of the standard Tcl channels stdin , stdout and stderr to the FCGI equivalents. In case no boolean redirection argument is given, the current redirection status is reported. In case a new status is set, the command returns the previous status. The current redirection status is also mirrored in the read-only control variable ::cactvs(fcgi_redirect).

fcgi status code

This command can be used to set the exit status when the automatic exiting feature of the fcgi accept command is used. This command may be called any time.

Example:

while {[fcgi accept]>=0} {
			set data [read stdin]
			if {$data==””} { set data $env(QUERY_STRING) }
			uncgi $data params
			do_something $params(form_url_arg1) $params(form_url_arg2)
			fcgi finish
}

This code snippet shows a typical main loop in an FCGI application. Standard I/O redirection is used for convenience, and in case there are any communication errors with the Web server, or shutdown instructions, like closing of the stdin channel, are received from the server, the application exists. If the application scripts exits, it is (in a typical set-up, this depends on the Web server configuration) be restarted by the Web server at a later time when the next request comes in.

fetch

fetch ?-agent agent? ?-cookie cookie? ?-cookielist cookielist? 			?-csrftoken token? ?-debug 0/1? ?-filename name? ?-header no/yes/exclusive? 			?-modified time_in_secs? ?-password password? ?-referer referer? 			?-setcookie cookie? ?-timeout nsecs? ?-tofile 0/1? ?-user username? 			?-verification 0/1? ?-xheader1 header? ?-xheader2 header?			?-xheader3 header? url ?statusvar?
fetch(url=,?statusvariable=?,?agent=?,?cookie=?,?cookielist=?,?csrftoken=?			?filename=?,?header=?,?modified=?,?password=?,?referer=?,?setcookie=?,			?timeout=?,?tofile=?,?user=?,?verification=?,?xheader1=?,?xheader2=?,			?xheader3=?)

This command is used to retrieved data from network locations identified by URL s. The default action is to fetch the data and return is as uninterpreted byte data, but without protocol header information. The following options can be used to modify the command action:

The url argument is a standard Internet URL . All standard protocol drivers also support the transport of user id and password information. Internally, this command uses the CURL library.

If a status variable parameter is specified, it is interpreted as the name of a Tcl array variable or Python dictionary which is created if necessary, reset and filled with status information. Its elements are size (the download data size, without header), lastmodified (the remote file modification date), location (the last download URL , which can be different from the original retrieval URL in case of redirects), mimetype (the Mime type of the data, as perceived by the remote server), various cookie data variants (see below) and finally status for the integer return status code.

The elements for the cookie data element encoding variants are named cookies (a list/tuple of all received cookies in Netscape format), cookiedicts (the same as list/tuple of dictionaries, with dictionary keys identifying the cookie field data components), and individual per-cookie elements cookie%d and cookiedict%d, where the placeholder is the cookie index starting with zero. The Netscape cookie format is a tab-separated string of six elements encoding the cookie domain, its domain access flag, the path, secure access flag, expiration date, cookie name and value. Splitting these strings to access individual data items should be done explicitly on the tab character since implicit list conversion is not reliable for this encoding. In the dictionary list and individual cookie dictionary encoding variants, the dictionaries contain the same information properly isolated under the keys domain , domainaccess , path , secureconnection , expiration , name and value . The individual cookie strings are simplified data representations pre-formatted in the style “name=value” or “ name=value; Path=path” (the latter only if an explicitly path was specified) which is usually the proper form to use when constructing a custom MIME header with a Cookie: or SetCookie: tag.

If the program is run in -header exclusive mode, the command result is a list of the status variable values size , lastmodified , mimetype , code , location and cookies , in the order listed, instead of the fetched data.

The modification time as well as cookie expiration dates in the status are returned as an integer (seconds since midnight, Jan 1 st , 1970, epoch ), suitable for formatting by means of the standard Tcl clock format command. If a modification or expiration date could not be determined, the reported time value is minus one.

The mime type information may contain, after a semicolon separator, additional encoding information if reported in this fashion by the server.

When the command is executed, the thread-local ::cactvs(lookup_timeout_occurred) flag is reset. If the command fails because of a server timeout, but no other causes, the flag is set.

Example:

set data [fetch -timeout 10 ftp://$user:$passwd@$host/$path/$file v_status]
set mimetype $v_status(mimetype)

filecheck

filecheck type filename
filecheck(type=,filename=)

This command is used to check formats and attributes of files. The result is either boolean 1, if the file is of the checked type, or 0 if it is not. In case of errors, such as a non-existing file, a standard error condition is raised. These file type checks are currently supported:

These tests operate by examining the first bytes of a file, not by a simple match of suffixes. File checks which rely on platform-specific binary data layout information only work for the current platform. On a Sun, a OSX bundle will not be recognized, and vice versa.

insidepolygon

insidepolygon {x y} {{x1 y1} {x2 y2} {x3 y3}...}
insidepolygon x y {{x1 y1} {x2 y2} {x3 y3}...}
insidepolygon x y x1 y x2 y2 x3 y3...
insidepolygon((x,y),((x1,y1),(x2,y2),(x3,y3),...))
insidepolygon(x,y,((x1,y1),(x2,y2),(x3,y3),...))
insidepolygon(x,y,x1,y1,x2,y2,x3,y3,...)

A boolean test to determine whether the test point is on the inside of the polygon defined by the points {x1 y1}. .. The first and last points of the polygon are assumed to be connected, so one should not supply a start and end point duplicate. The minimum polygon size is three points, and there is no upper limit. The point encoding is determined by the number of arguments (2,3, or more).

ldelete

ldelete ?mode? list pattern ?pattern?...

Delete elements from a list. The first optional parameter selects the match mode for the patterns. If can be one of - exact , - nocase , - substring , - regexp , - glob or - index . The standard option list terminator “--” may also be used. The default mode is exact . The index mode expects element indices starting with 0 as pattern arguments.

All list elements which match any of the patterns are removed. The command returns the shortened list, preserving the order of the surviving elements.

This command is not directly supported in the Python interface - the function can easily be implemented with standard list comprehensions (see for example https://stackoverflow.com/questions/20349125/removing-a-pattern-from-a-list-items-in-python)

Example:

ldelete -regexp [list a aa ad] {a[abc]+} 

returns “a ad”.

lineintersect

lineintersect x1 y1 x2 y2 x3 y3 x4 y4
lineintersect {x1 y1} {x2 y2} {x3 y3} {x4 y4}
lineintersect(x1,y1,x2,y2,x3,y3,x4,y4)
lineintersect((x1,y1),(x2,y2),(x3,y3),(x4,y4))

Test whether the line segments from x1/y1 to x2/y2 crosses the line segment from x3/y3 to x4/y4.

The return value is a simple boolean value. It does not report the intersection coordinates.

lsearch

lsearch ?modeflags? list pattern

This is an extended, but compatible version of the standard Tcl lsearch command.

The mode flags may be any combination of - exact , - nocase , - substring , - regexp , - glob , - first , - all and the option terminator “--”. The default mode is the combination of glob and first , the same as for the standard lsearch command.

Just as the standard command, matching list indices are returned. In mode first, which corresponds to the default behavior, the result is the list index >= 0 of the first matching element, or -1 if the pattern cannot be found. In mode all, a list of the indices of all matching list elements is returned, or an empty list if no element matches.

The command is not directly supported in the Python interface - use the standard list comprehension and pattern match functions for this functionality.

Example:

lsearch -exact -all {a b c a b c} a

returns “0 3”.

lsum

lsum nmbers...
lsum(?number,...)

Sum up all number arguments and return the result. All arguments must be numbers.

sum is an command alias.

lvardelete

lvardelete ?mode? listvar pattern ?pattern?...

Delete elements from a list variable. The first optional parameter selects the match mode for the patterns. If can be one of - exact , - nocase , - substring , - regexp , - glob or - index . The standard option list terminator “--” may also be used. The default mode is exact . The index mode expects element indices starting with 0 as pattern arguments.

All list elements which match any of the patterns are removed from the variable. Additionally, the command returns the shortened list, preserving the order of the surviving elements.

The command is not directly supported in the Python interface - use the standard list comprehension and pattern match functions for for this functionality.

Example:

set mylvar [list a b c d]; lvardelete myar b d

returns “a c” and sets the variable to the same value.

mail

mail ?-attachment filename? ?-debug 0/1? ?-file filename? 			?-from address? ?-secure 0/1? 										?-smtphost hostname? ?-smptpassword password? ?-stmpport port?			?-smptuser userid? addresslist ?subject? ?message?
mail(addresses=,?subject=?,?message=?,?attachments=?,?debug=?,?filename=?,			?from=?,?secure=?,?smtphost=?,?smtppassword=?,?smtpport=?,?smtpuser=?)

Send a simple iso-encoded plain-text email message to one or more recipients. The only required argument is the recipient email address list. Without subject and body arguments, an empty message is sent. If the recipient address list is an empty list, or only contains empty elements, the command silently does nothing. Address list elements which are not empty strings and ignored must pass a simple email address pattern test before a mail delivery attempt is made.

The optional smtp* arguments specify the access parameters to the mail host. If these options are not set, they are read from the corresponding control variable elements, i.e. ::cactvs(smpt_host) , ::cactvs(smpt_port) , etc. If the - secure option is set, an attempt is made to use encrypted smpts communication instead of the plain smtp protocol, though the initial protocol negotiation still uses plain smtp if the smtp port is not explicitly set to 465. In absence of an - from argument, the sender address is copied from ::cactvs(user_email) . There is no required relationship between the from address and the mail host access parameters. The default smtp port used by this command is 587, not the old standard 25.

Experience teaches that talking to mail servers can be tricky. When the - debug option is set, trace output from the communication attempts is printed on standard error. This is highly useful to pinpoint connection problems.

Finally, the - file option allows the direct upload of an existing, readable file as the message. The file contents are sent as message data, not as an attachment. If both an upload file and a body argument are specified, the file is inserted first.

The message content is sent as plain Latin1 (ISO8859-1) encoded message. The nature of line-break characters in the message is not preserved, and additional line breaks are inserted if any line is longer than 998 characters, the maximum line length in a standard smtp message.

This command currently neither supports pop-before-smtp authorization, nor the sending of attachments, though they are accepted as arguments. In the Tcl command version, multiple attachments are specified by repeating the -attachment command. In Python , an attachment file name tuple is expected, because named function arguments cannot be repeated.

The argument order of the Python command is intentionally different to allow sending of messages without setting more exotic options. All arguments after the first three must be specified as named arguments.

Example:

mail -smtphost smtp.gmail.com -smtpuser $user -smtppassword $pw \
			-secure 1 wdi@xemistry.com “Hi” "This\nis a message\n"

Above sample command sends a message via Google mail. Of course, a Gmail account bound to the user and password variables must exist for this command to succeed.

mailcap

mailcap mimetype
mailcap(mimetype)

Return the standard opener/viewer for files of the specified MIME type. The result is dependent of the local configuration.On Windows, the command attempts to find a suitable opener in the registry, and if it is found, the return value usually contains Windows-specific placeholder tags.

Example:

mailcap chemical/pdb

might return something like “rasmol -pdb %s”

parse

parse base64 arg
parse binary arg
parse casrn arg
parse color arg
parse datauri arg
parse date arg
parse dictionary arg
parse doi arg
parse domain arg
parse element arg
parse elementlist arg
parse email arg
parse formula arg
parse hash arg
parse hex arg
parse inchi arg
parse inchikey arg
parse ipaddr arg
parse jme arg
parse json arg
parse lillyrule arg
parse linenotation arg
parse list arg
parse minimol arg
pasre nativequery arg
parse orcid arg
parse propertyname arg
parse propertylist arg
parse query arg
parse queryformula arg
parse retrievallist arg
parse sln arg
parse smarts arg
parse smiles arg
parse superatom arg
parse unii arg
parse uuid arg
parse xml arg
parse(class=,data=) 

This command checks whether the argument can be parsed as the data type indicated. The result is a boolean value. No error is raised if the parsing fails, and the parsed data structure is discarded. The following data types are currently understood:

passwd

passwd encode cleartext_pw ?salt?
passwd decode encrypted_pw cleartext_pw
passwd(mode=”encode”,password=,?salt=?)
passwd(mode=”decode”,password=,cleartext=)

The first command variant encodes a clear-text password with the standard Unix crypt() algorithm. A salt value for the password generation may be specified as exactly two letters from the set “a-zA-Z0-9./”. If no salt is specified, a random value is used. The command returns the encoded version of the clear text.

The second variant returns 0 or 1, depending on whether the clear text password matches the encrypted version or not.

This command is supported on Windows, the crypt() function is provided by a compatibility function compiled into the library code.

Example:

passwd encode topsecret XX

yields something like “XX9Kadd0cpq.o”.

passwd decode XX9 topsecret

returns 0, while

passwd decode XX9Kadd0cpq.o topsecret

returns 1. Note that without the specification of a salt parameter the encoded result is different each time in a random fashion. However, the password check works without knowing the salt with encrypted passwords encoded with each possible salt.

post

post ?-agent agent? ?-boundary text? ?-cookie cookietext? 			?-contenttype mimetype? ?-cookie cookietext? ?-csrftoken token? 			?-debug 0/1? ?-fieldcontenttype type? ?-host hostname?			?-language languagecode? ?-password pwd? 			?-raw? ?-referer referer? ?-setcookie cookie? ?-timeout secs? 			?-uploads uploaddictionary? ?-user username? ?-verifyhost 0/1			?-xheader1 headerline? ?-xheader2 headerline? ?-xheader3 headerline? 			url ?fielddictionary/rawdata? ?statusvariable?
post(url=,?data=?,?agent=?,?boundary=?,?cookie=?,?contenttype=?,			?csrftoken=?,?debug=?,?fieldcontenttype=?,?host=?,?languate=?,			?password=?,?raw=?,?referer=?,?setcookie=?,?timeout=?,?uploads=?,?user=?,			?verifyhost=?,?xheader1=?,?xheader2=?,?xheader3=?,?statusvariable=?)

Assemble the code for a HTTP or HTTPS POST message in (by default) multipart/form-data encoding, transmit it to a remote server and read the response.

In the standard command mode, the field dictionary parameter is a list of field names and their contents to include in the POST message. The transfer format is binary, so it is possible to send byte array data. The default individual field mime format is text/plain , but PNG and GIF images as field data are automatically recognized and sent as image/png and image/gif, respectively. In order to mirror the data encoding characteristics of file upload HTML form elements faithfully, an optional uploads dictionary can be provided. It is a key/value collection where the keys are field names that are file upload elements in the emulated Web form. They also need to be contained in the field dictionary as field name / field data pair. Field names only present in the uploads directory are ignored. The upload dictionary values are the filename attribute of the transmitted fields. The encoding of transmitted data for fields in this dictionary is modified so that the content type is always set to application/octet-stream instead of text/plain . Whether the configuration of the upload dictionary is required or not when emulating the submission of forms with upload fields depends on the extent of the data analysis performed on the side of the contacted server, but its use does not potentially introduce new problems. File contents are not automatically opened and read. Their contents must be provided in the field dictionary.

If the - raw flag is set, no interpretation of the field dictionary parameter takes place. Instead, the value of this parameter is transmitted verbatim as byte sequence in the message body. In this mode, it is assumed that it already contains all field formatting and only needs to be augmented with the HTTP header data. The Tcl version of the command uses this flag as a stand-alone parameter, while in the Python version it requires a boolean value specification.

The other optional parameters allow the setting of additional fields in the header of the POST command. The -boundary attribute is the MIME separator string. Its default value is a random string that is highly unlikely to occur in any transmitted data. The default content type for the form submission is multipart/form-data , but this may be adjusted with the - contenttype parameter. The short argument forms multipart (or formdata ) and urlencoded select the standard encodings multipart/form-data and application/x-www-form-urlencoded . Other values of this option are sent verbatim to the server after a Content-Type: keyword. The additional attributes of file upload fields are ignored in urlencoded mode.

The argument of the - language option is passed to the Accept-Language: HTTP header field. By default the Host: HTTP header is extracted from the destination URL , but a custom value can be set with the - host option. The - xheader[123] parameters allow the injection of custom lines into the HTTP header. The line data should be provided without linefeeds, and must contain the header field name. The - csrftoken option simplifies the handling of CSRF tokens. A token specified here is added to the HTTP header in a X-CSRF-Token: header line.

Field content is normally posted with a “ text/plain; charset=utf8 ” type header, except for data which is recognized to be in another well-known format (like GIF or PNG images), where the proper standard type is substituted. The -fieldcontenttype attribute can be used to override this default typing. If it is set to an empty string (or Python None ), the fields are posted without type information. Individual typing of fields is currently not supported.

If the -verifyhost option is set to false , and the connection uses SSL encryption, the remote host identity is not rigorously checked against its SSL certificate. This allows interaction with hosts which used mis-configured SSL certificates, but this lenient approach is obviously a potential security issue and should only be used when necessary. The other parameters have the same meaning as in the related fetch command.

If the name of a status variable is specified, it is created or reset in the local namespace, and filled with the elements status (the HTTP server error code, 200 for normal retrieval), size (the length of the received content in bytes), cookies (a list of all cookies received in Netscape string format), cookiedicts (a list of cookies in dictionary form), location (the response URL , which can be different from the command argument in case of server redirection), lastmodified (the modification time stamp of the result data, if available, -1 otherwise) and contenttype and mimetype (the MIME type of the response). In addition, every cookie is individually stored as element cookiedict%d , starting with index zero and with the seven elements domain , domainaccess , path , secureconnection , expiration , name and value that are contained in the standard Netscape cookie encoding. The variable element names are compatible to those used in the fetch command.

It is possible to omit the field dictionary argument if an empty message is to be sent. The URL may also contain field arguments in URL encoding, but whether these are recognized in addition to the data in the field dictionary depends on the destination server configuration.

When the command is executed, the thread-local ::cactvs(lookup_timeout_occurred) flag is reset. If the command fails because of a server timeout, but no other error causes, the flag is set.

The argument order is intentionally different for Python in order to allow simple submissions without named arguments. All arguments after the data item must be set as named arguments.

Example:

set data [post -contenttype urlencoded -cookie $c -debug 0 \
-csrftoken [dict get $dcsrf value] \
-referer https://mcule.com/search/ \
https://mcule.com/search/post \
[dict create csrfmiddlewaretoken [dict get $dcsrf value] mode exact structure_2 $mdata
]]

prod

prod args...
prod(?arg?,...)

Interpret the arguments as numeric values and compute their product. If called without arguments, the function returns one.

python

python eval expression
python exec statements

Execute a Python command or expression from Tcl . This command is only available in interpreters which include a Python subsystem. This command is not supported in Python , but on that side, comparable tcl() and tcl1() method exist.

For the eval variant, only a single statement may be processed, and the result of that statement is returned to Tcl . Longer statement blocks can be processed with the exec command variant, but in that case the result is always an empty string if no error occurs. This is a limitation of the Python API . In case an error is raised, its description is transferred back as Tcl result string, and the command also reports an error.

The Python interpreter version is currently 3.6. It is fully featured with access to the complete Python standard library, and can be instructed to import additional modules.

At this time, only a single primary Python interpreter exists in Python -enabled toolkit applications. It is mutex-protected and can be called from multiple Tcl threads, but not simultaneously. Property computation Python sub-interpreters are internally used, but not accessible via this command.

The Python interpreter in the standard toolkit context (but not when loaded as Python module) has already imported the pycactvs and sys Python modules. All pycactvs functions and other objects are explicitly imported and can by used without a module prefix. The pycactvs.tcl() and pycactvs.tcl1() functions allow scripts to double back and execute a Tcl command in the main Tcl interpreter from within Python .

Examples:

set five [python eval “2+3”]
python exec “print(‘hello world’)”
set eh [python eval “tcl(‘ens create CCC’)”]

The first example computes a simple expression in Python and returns the result. It is automatically efficiently encoded as a Tcl integer object.

The last example executes a command in the Python interpreter, which itself turns back to the Tcl interpreter to execute an ens create statement. Toolkit objects are shared between the Python and Tcl interpreters. The newly created ensemble object is known and accessible in both languages simultaneously.

quote

quote arg

Perform an efficient string quoting operation of a Latin1 string. The result is a string which contains only 7-bit printable characters. Characters outside this range are encoded as backslash-encoded octets or standard backslash escape sequences such as ’\t’ or ’\\’. The code for this command was copied from the Tcl Netscape plug-in.

The command is not supported in the Python interface because of the different string handling semantics in that language.

random

random limitval ?sequencesize ?seedval|reset?
random seed ?seedval?
random reset
random hex32 ?seedval/reset?
random hex64 ?seedval/reset?
random hex128 ?seedval/reset?
random uuid
random(limitval,?sequencesize?,?seedval|”reset”?)
random(“seed”,?seedval?)
random(“reset”)
random(“hex32”,?seedval|”reset”?)
random(“hex642”,?seedval|”reset”?)
random(“hex128”,?seedval|”reset”?)
random(“uuid”)

Generate integer pseudo-random numbers. In the simplest command variant, the limitval parameter is an upper exclusive bound. The returned pseudo-random number is in the range 0 to limit-1 . By default, only a single number is returned. If a non-empty sequencesize parameter is added, the specified number of pseudo-random numbers is returned as a list. If the third optional parameter is the string reset , the random number generator is reset to its default start state. Alternatively, a numerical seed value can is used to initialize it to a different initial state before computing the random numbers..The random numbers are always the same sequence for a given initial state. If this is not desired, some pseudo-random seed, such as the current clock click value, should be used.

The random seed and random reset command variants can be used to manipulate the state without starting the random number generation. The seed subcommand without a seed argument uses a combination of a high-resolution timer and the process ID as seed value and is the recommended method to set up the generator for non-repeatable randomness.

The random hexxx variants directly return hex string encodings of 32, 64 or 128 bit integers, which possess fixed string lengths of 8, 16 and 32 characters, respectively. Optionally, this operation again can be combined with a reset operation or a seed value.

The uuid subcommand generates a new UUID . This function is independent of the normal random state.

This command is thread-aware. Every script thread has its own random state, and random number generation or state manipulation in one thread has no effect on any other interpreter thread. The uuid subcommand is the sole exception - it is not thread-aware, and not coupled to the thread-local random state of the other commands.

This random number command overrides the standard TclX command of the same name and provides a superset of its functionality, in addition to thread-awareness.

Example:

random seed
foreach r [random 16 8] {...}

rpc

rpc bynumber servicenumber
rpc byname servicename
rpc(mode=’bynumber’,arg=)
rpc(mode=’byname’,arg=)

Look up RPC services by name or service number. If the service can be found, the result is a list consisting of the service name, the service number, and a list of all name aliases.

This command is supported on Linux/Unix only, and only in special builds.

screen

screen ?-aromatch lenient|normal|strict? ?-frags? 			?-hydrogens ignore|match|mark? ?-mode ligands|smarts? ?-nobondorder? 			?-tauto? ehandle patternlist ?exactmatchvar?
screen(ens=,patterns=,?aromatch=?,?frags=?,?hydrogens=?,?matchvariable=?,			?mode=?,?nobondorder=?,?tauto=?)

Perform fragment-based bit screening on an ensemble object. If the - frags option is not set, he result is a bit vector of the same length as the pattern list, with bits set to zero or one depending on whether a pattern fragment matches or not. If - frags option is set, the return value is a list of the patterns which match, copied verbatim from the pattern list argument.

If the optional exact match variable parameter is given, it is the name of a Tcl or Python variable which is set to one if the input ensemble is of exactly the same connectivity (without stereochemistry or isotopes) as one of the pattern fragments. If no pattern is an exact match, it is set to zero.

The expected format of the pattern list depends on the match mode. The default match mode is ligands , which can be explicitly set by supplying the argument to - mode . The other possible match mode is smarts , set by -mode smarts .

In smarts mode, the patterns are normal SMARTS strings. These are cached internally, so if patterns are reused, and the total number of patterns is not too large for the cache, they are not decoded anew for every command invocation.

In ligands mode, a simpler pattern language which is faster to decode and match is used. The patterns are either two element symbols, connected by a bond symbol (- for single bond, = for double, * for triple, # for quadruple, ~ for aromatic - note that this is different from SMILES !), or an element, followed by a sequence of bracketed ligands, each with a preceding bond symbol. Patterns like these describe one central atom (the first element in the pattern), with one or more ligands. Examples are “P=O” or “C(-Cl)(=O)” or “C(-H)(~C)(~C)” . For internal reasons, all multiple bonds in a pattern must be written before any aromatic bond.

The - aro option controls how aromatic systems in the ensemble are matched. The default is normal , meaning that single and double bonds in SMARTS patterns match aromatic bonds in the ensemble, regardless of their Kekulé bond order, and single bonds in ligands patterns match aromatic ensemble bonds. In strict mode, non-aromatic bonds in the pattern do not match aromatic ensemble bonds. This mode has an effect only for smarts matching, not ligand matching. The aro match mode lenient only has an effect on matching ligand patterns. If not selected, ligand pattern double bonds do not match aromatic ensemble bonds. If the mode is lenient , they do.

If the - tauto flag is set, the matching of both ligand and SMARTS patterns is further modified. In ligands mode, tautomeric ensemble bonds (as per property B_ISTAUTOMERIC ) are excluded from any match which requires an exact bond order match. In smarts mode, the matched fragment must be compatible with a tautomeric form with shifted bond orders and relocated hydrogen atoms. This flag is intended to be used to construct a screening bit string for tautomer-tolerant substructure searches. Because less patterns can be positively identified to be matching under these circumstances, these bit strings have generally less bits set, and are therefore less effective filters.

If the - nobondorder flag is set, bond orders of pattern fragments of both types are ignored.

The - hydrogen option controls how patterns with hydrogen atoms are handled. By default, in mode match , they are matched like any other pattern. In mode ignore , patterns with hydrogen never match. This is the mode to use if a screen vector for superstructure search is constructed. In mode mark , any pattern which contains a hydrogen atom reports a match, and any pattern which does not a mismatch. This mode is intended to be used for construction of bit masks for the removal of any bits from a screen vector which are hydrogen-dependent. This allows for example the re-use of a substructure screen vector for superstructure search.

The Python version of the command intentionally has a different argument order than the Tcl version. Additionally, single-word arguments in the Tcl version must be specified as named arguments with a boolean value. All parameters after the pattern set must be passed as named arguments.

sqsum

sqsum args...
sqsum(?arg?,...)

Interpret the arguments as numeric values and compute the sum of the squared values.

stddev

stddev arg arg ?args?...
stddev(arg,arg,?arg?,...)

Interpret the arguments as numeric values and compute their standard deviation. A minimum of two arguments is required.

sum

An alias for lsum .

tmpdir

tmpdir
tmpdir()

This command returns the current potentially application-specific directory for temporary files (/tmp or C:/temp or similar).

tmpname

tmpname ?prefix? ?directory? ?suffix?
tmpname(?prefix=?,?directory=?,?suffix=?)

Generate a valid name for a temporary file. The file name prefix, the suffix as well as the directory may be specified. If these parameters are omitted, or set to empty strings (including None for Python ) a temporary file in the standard tmp directory and with a file name prefix derived from the application name (obtained via invoking the command infox appname in the current Tcl interpreter, where the standard Tcl features to configure its results apply) is generated.

Example:

tmpname myapp {} .res

returns something like /tmp/mya2462.res , dependent on the operating system and local set-up.

uncgi

uncgi ?-noreset? cgi_string ?variable? ?untrimmedfields? 			?fieldname default?...
uncgi(cgi_string=,?defaults=?,?noreset=?,?untrimmedfields=?,?variable=?)

This command decodes CGI data, as it is delivered to a CGI application from data input in a WWW form via the Web server. It automatically recognizes the two standard transfer formats application/x-www-form-urlencoded and multipart/form-data and adjusts the decoding process accordingly.

The cgi_string input data can be obtained either from the QUERY_STRING environment variable ( PUT forms, or direct CGI URL s), or from reading the stdin channel ( POST forms). A typical code snippet in case the data submission method is not known is:

fconfigure stdin -translation binary
set data [read stdin]
if {$data==””} { set data $env(QUERY_STRING) }
uncgi $data params

The return value of this command is a dictionary with name/value pairs. This dictionary can be read into an array variable by the standard array set Tcl command. If the optional variable parameter is used, an array variable of that name is automatically created or reset and filled with the decoded data in the form of array elements.

By default, leading and trailing white space is removed from the decoded data. Fields for which this white space removal should not be performed can be listed as a standard Tcl list in the untrimmedfields parameter. These fields are decoded without any processing.

Note that it is generally advisable to set the stdin input channel to binary mode before reading the CGI data. On Unix, this is likely to be a no-op, but the transfer of binary data on Windows usually does not work at all without this setting.

For security reasons, certain XML / HTML -style tags, including their inner text if they possess it, are automatically removed from the input data. The currently deleted tag list is <embed> , <frame> , <iframe> , <img> , <object> , <script> and <style> . This tag deletion cannot be suppressed.

Data of type multipart/form may transfer additional parameter attributes for the data together with the actual content. In case of file uploads from Web forms, the original client-side file name is captured in an additional result element named by appending “_filename” to the basic data field name. The MIME type of the data, if transmitted, is similarly stored in an extra element with the appended name part “_type”.

A single unnamed field in the data string is accepted by the decoder. The data is stored as element unnamed in the decoded result.

In case a field name is occurring more than once in a data string, the additional instances are appended to the first instance as list elements. The final content of the decoded field is then a list of all values found in the input.

If an output variable parameter is used, all existing array elements are removed before decoding starts. In case results should be accumulated, the - noreset option can be used to suppress the variable reset step.

After the parameter listing fields not to be trimmed an arbitrarily long list of pairs of field names and their default values can be specified. If a field name listed there was not present in the input data, it is set in the result list and array variable with the default value following the field name.

The structure of the arguments is intentionally different in the Python version of the command. All arguments after the CGI data must be passed as named arguments. The noreset option requires a boolean argument value. Instead of an open argument set for field names and their default after the standard arguments a dictionary with field names as key and defaults as values is used.

Example:

URL: http://www.example.com/cgi-bin/doit.tcl?a=alpha&b=beta&b=gamma

The data sent by invoking the CGI script via this direct URL can be decoded in the doit.tcl script with the statement

uncgi $env(QUERY_STRING) params

An array variable named params is set up, or reset if already present, and it contains exactly two elements: Element a with value “alpha”, and element b with value “beta gamma”

unzip

unzip nested_list ?index?
unzip(data=,?index=?)

Extract a list of indexed elements from a nested list. From each element of the nested input list, the element indicated by the index parameter is selected and appended to the result list. If the index parameter is omitted, the default is zero. If a selected list element does not exist, an empty string is substituted.

Example:

set l2 [unzip {{a 1} {b 2}} 1]

The l2 variable is set to a list with elements 1 and 2.

upload

upload filename url ?mimetype?
upload(filename=,url=,?mimetype=?)

Upload a file to a remote destination. The first argument is a path to a local, readable file. The second argument is an URL which indicates the transfer protocol and the remote location. The optional final argument is e MIME type specification which is transferred to the remote host in addition to the file content. If it is not specified, the type is implicitly application/octet-stream .

The supported protocols currently are:

The ACL can be any of private , public-read, public-read-write , authenticated-read , aws-exec-read , bucket-owner-read , bucket-owner-full-control or log-delivery-write (see AWS documentation). The default is private. The available AWS regions are frequently updated, please refer to the AWS documentation. The specified value is not checked on the client side.

Example:

upload mydata.sdf s3://$bucket/folder1/mydata.sdf?region=eu-central-1

In this example, the global control variable settings for the AWS key, secret and ACL are used, while the storage region is explicitly specified.

vec

vec add v1 ?v2?...
vec centroid p1 p2 ?p3?...
vec create vspec
vec crossproduct v1 v2
vec degangle v1 v2
vec distance p1 p2 ?p3?...
vec dotproduct v1 v2
vec fitline p1 p2 ?p3?...
vec fitplane p1 p2 p3 ?p4?...
vec len v1
vec len p1 p2 ?p3?...
vec negate v
vec normalize v
vec plane p1 p2 p3 ?p4?...
vec planenormal p1 p2 p3
vec pt_line_distance p1 p2 v2
vec pt_plane_distance p1 d v1
vec radangle v1 v2
vec scale v d
vec subcommands
vec subtract v1 ?v2?...
Vec(vspec)
Vec.Create(vspec)
dir(Vec)
v.add(?v1?,...)
Vec.Add(?v1?,...)
Vec.Centroid(p1,p2,...)
p.centroid(p1)
v.crossproduct(v1)
v.degangle(v1)
Vec.Distance(p1,p2,?p3?,...)
p.distance(p1)
v.dotproduct(v1)
Vec.Fitline(p1,p2,?p3?,...)
Vec.Fitplane(p1,p2,?p3?,...)
Vec.Len(v1)
Vec.Len(p1,p2,?p3?...)
v.len()
p.len(p1,?p2?,...)
v.negate()
v.normalize()
Vec.Plane(p1,p2,p3,?p4?,...)
Vec.Planenormal(p1,p2,p3)
Vec.PtLineDistance(p1,p2,v2)
p.ptLineDistance(p2,v2)
Vec.PtPlaneDistance(p1,d,v1)
p.ptPlaneDistance(d,v1)
v.radangle(v1)
v.scale(d)
v.subtract(?v1?,...)
Vec.Subtract(?V1?,...)
v + v1
v - v1
v += v1
v -= v1
v * v1
-v

This command provides a couple of useful 3D vector and point manipulation commands. In the Tcl case, the points and vectors are internally standard Tcl list objects with floating point elements, so operations are not blazingly fast but still reasonably effective for routine vector arithmetic. Vectors are not toolkit objects, there is nothing to destroy when they are no longer needed. In the Python implementation, there is a custom point/vector object which holds a triple of floating-point values.

This simple utility command only supports vectors and points of 3 dimensions. There is no syntactic difference between vectors and points. The exact interpretation depends on the context.

Vectors can be decoded from a variety of string representations. A vector can be made from

The following subcommands are understood:

vec create arg1 ?arg2 arg3?

Create a point or vector and return its fully expanded numerical representation. If only one argument is given, any of the standard representations is accepted. In case three arguments are provided, they are internally concatenated and this list submitted to the decoding procedure. The command result, if the arguments could be decoded, is the numerical vector representation. The vector commands generally understand both resolved vectors, and the short forms which can be decoded by this command, to in many cases, explicit syntax resolution is not required.

vec add v1 ?v2...?

Add two or more vectors. The return value is the vector sum. Subcommand aliases are plus and + . The Python implementation provides both class and object methods. Additionally, the + and += numerical operators are overloaded.

vec subtract v1 ?v2...?

Add two or more vectors. The return value is the vector sum. Subcommand aliases are minus and - . The Python implementation provides both class and object methods. Additionally, the - and -= numerical operators are overloaded.

vec degangle v1 v2
vec radangle v1 v2

Compute the vector angle between v1 and v2 in degrees or radians. The subcommand may be shorted to deg or rad.

vec len v1
vec len p1 p2 ?p3...?

If only a single argument is specified, interpret the argument as vector and compute its length. In case multiple arguments are used, compute the length of the straight, acyclic path between the points.

vec distance p1 p2 ?p3...?

Return a list of the distances between point one and two, two and three, and so on. For two arguments, the result is the same as using vec len , but if there are additional points, the individual distances between the waypoints are returned as a list instead of the total length of the path.

vec centroid p1 p2 ?p3...?

These command aliases compute the centroid of the points passed as argument. The return value are the centroid point coordinates. midpoint is a subcommand alias.

vec dotproduct v1 v2

Compute the dot product of the two vectors. The result is a floating point value. dot and * are subcommand aliases.

vec crossproduct v1 v2

Compute the vector cross product of the two passed vectors. The return value is the cross product vector. The subcommand may be abbreviated as cross , and additionally prod , product and x are subcommand aliases. In Python, the * multiplication sign is overloaded with this function.

vec negate v1

Negate the vector. This is equivalent to scaling with minus one.

vec normalize v1

Normalize vector to length one. The normalized vector elements are the return value. unit is a subcommand alias.

vec scale v1 d

Scale length of vector v1 by the specified floating point factor. The return value is the scaled vector.

vec fitline p1 p2 ?p3...?

Fit a line to a set of points. The return value is a list of a line point and the direction vector.

vec fitplane p1 p2 p3 ?p4...?

Fit a plane to a set of points. The result is returned in Hesse normal form: The closest distance of a plane point to the origin, and the normal vector of the plane.

vec plane p1 p2 ?p3...?

Compute a plane (fitted in case more than three points are specified) spanned by the specified vectors. The result are two orthogonal plane vectors.

vec planenormal p1 p2 p3

Get the normal vector of the plane specified by the three points.

vec pt_line_dist pt l_point l_vec

Compute the distance between a point (coordinates in first argument) and a line in 3D space (specified by an anchor point on the line and the direction vector).

vec pt_plane_dist pt p_dist p_normalvec

Compute the distance between a point (coordinates in first argument) and a plane in 3D space (specified in Hesse form, i.e. smallest distance of any point on the plane to the origin and plane normal vector).

zip

zip list1 ?listn?...
zip(sequence,?sequence...?)

Merge one or more lists. The result is a nested list where each element is a sequence of input list elements at the corresponding position. The size of the largest input list determines the output. If any input lists are shorter than another input list, empty elements ( None for Python ) are substituted.

Example:

set l [zip {a b c} {1 2}]

The result is a single list „ {a 1} {b 2} {c {}}

It is possible and sometime useful to use only a single argument list. Here, every element is reformatted so that itself is a proper nested list. Example:

set l [zip {a {b c} d}]

The result is a list „ {a {{b c}} d} “ with an extra nesting level to protect the middle element so that it can a reclaimed unchanged by un-zipping with a command like

set l0 [unzip $l 0]