A Practical Guide to Tcl
Machine-translated from the Chinese original.
A Practical Guide to Tcl
Reference: Roben_Chen, Tcl Tutorial
Editor: Jimmy_Chen
Most of the code examples and the order of the early chapters follow roben_chen’s handout. I’ve reworked the material for clarity, added explanations and hands-on notes, and written new chapters on applying Tcl in VMD. Enjoy!
Chapter 0: Before You Use
VMD uses Tcl as a scripting language. Its syntax is straightforward enough to cover in an evening if you already have some programming experience. My goal in learning Tcl is to write and use scripts more effectively in molecular dynamics tools such as VMD.
0.1 Using VS Code
Starting today, we'll start by introducing some basics of writing scripts for tcl interpreters, before you should install one vscode to learn.
I believe this may be your first time using VS Code. Before using it, you should be curious: How to make good use of VS Code?
Here's a brief introduction:
- There's a chat room on the right side for you to use the chat code, but now I suggest you turn it off (in the top right corner there's a bubble icon)
- On the left side is a four-square icon where extensions can be installed.
- Remember, in the bottom right corner, turn off the copilot (he often gives or predicts what you're going to type, which is bad for elementary school)
- In addition, there is the concept of a control panel mouse, where you can move the mouse under the screen and pull up a control panel if you form a cross, and of course you can also build a terminal on top of the terminal in the upper left corner. The start-up and runner are related.
- VS Code has many useful plugins, which are recommended to install neovim or vim. Its operating logic is consistent with the vim in the terminal, and the vim plug-in logic will be applied every time you open VS Code.
0.2 Running the Tcl interpreter
There are many ways to run tcl, such as in zsh on mac:
- Type
tclshin the terminal and press Enter to start the interactive Tcl interpreter. - When the terminal prompt changes to
%, you are in the Tcl interpreter. - If you want to withdraw, it is directly
exitor can bebrew install tcsh.
In VS Code, you don't just have to install one. Code Runner The extension, and the way to go command palette I'm going to set it up. Because the code runner can't recognize tcl language )。 The following is the configuration of the code runner:
- It can be directly opened by cmd+shift+P or by view - command palette.
- In the output search box, enter:
Open Settings (JSON) - The following is the list of preferences: Open User Settings (JSON)
- Add Tcl rules: You'll see a file containing various set codes. The outermost layer is a large bracket pair {}). Please copy and paste the following code in this file to find a suitable place (e.g. above the last line of code):
"code-runner.executorMap": {
"tcl": "tclsh"
},
"code-runner.executorMapByFileExtension": {
".tcl": "tclsh"
}
It is important to note that if you have the original code on the line where you paste it, remember to add an English comma at the end of the line ,, due to the grammar rules of JSON files..
If you have a runner-code.executorMap tab, you can just add the tcl tab: tclsh tab and then save cmd+s to exit.
The following are some specific modifications:
First of all. :
{
"security.workspace.trust.untrustedFiles": "open",
"extensions.experimental.affinity": {
"asvetliakov.vscode-neovim": 1
},
"editor.fontSize": 14,
"github.copilot.enable": {
"*": false,
"plaintext": false,
"markdown": false,
"scminput": false,
"tcl": false
}
}
Changes :
{
"security.workspace.trust.untrustedFiles": "open",
"extensions.experimental.affinity": {
"asvetliakov.vscode-neovim": 1
},
"editor.fontSize": 14,
"github.copilot.enable": {
"*": false,
"plaintext": false,
"markdown": false,
"scminput": false,
"tcl": false
},
"code-runner.executorMap": {
"tcl": "tclsh"
},
"code-runner.executorMapByFileExtension": {
".tcl": "tclsh"
}
}
You can then round a character to the right and then run code, the plugin will automatically identify it as tcl language, or VS Code in the top left corner Run - Run Without Debugging
Chapter 1: TCL syntax
1.1 Script & command & word symbols
First, let's look at the basic grammar of tcl interpreters and some common commands.
tcl is a type of Scripted language , its syntax is very simple, and it consists mainly of Commands and Parameters Each command begins with a word followed by some parameters, which can be the result of strings, numbers or other commands. .
A tcl script can contain one & more commands, specifically with several requirements:
- The commands must be separated by The change of characters or The number
; - Each command starts with a word symbol followed by some parameters.
- Note that the interval between words (note that the interval between the words "h" and "h" is required by the above) must be separated with The empty space or TAB key and cannot be separated by other separators, such as commas or prefixes.
- The Tcl Every command will Contains one or more words .
- In general, the first word represents the name of the command, while the other word represents the parameters of the previous function (the command).
For example, the following two examples are allowed:
example_1 Use the linear separator command to use spaces between words:
set a 1
set b 2
example_2 Using the split command, use spaces between words:
set a 1; set b 2
The following is a simple example to show the subtle difference.
example_3 It is important to note that the following expressions are values of the variable sel shown:
set sel
puts $sel
The following is a detailed discussion of the specific differences between the two:
set sel
- Set command: set is the first command in Tcl to handle variables.
- It has two uses:
- The value (two parameters): set sel 100 // Put 100 in a box called sel
- Read it (a parameter): This is the current situation. When you give a set only one parameter, it is used to return the current value of the variable.
So, if you first set:
set sel "Hello"
The following entry:
set sel
The program is designed to Hello The string is not printed on the screen unless the interactive terminal will display the value of the string by default. )
In ordinary script documents, simply writing a line set sel makes little sense It's just a value-added thing. Get it out. The first thing that I did was to click on it and not print it on the screen or pass it on to other commands.
puts $sel
putsThe command:putsThe full title isput string(Exit string) can be printed on the screen and read easily.- In this case,
puts(命令) $sel(参数)$tcl means that the value of the variable is replaced by a string of values. The following is a detailed explanation. ) ⋅ Simply put, tcl first reads$selthe string, and since there is $, tcl goes to the memory to find outselwhat exactly the variable is (sel what is in the box).
From above: If the parameter sel is not assigned a value, then there is no output, so write:
set sel "Hello"
puts $sel
The following commands are executed and the printed words can be seen Hello
Summary: In tcl, the value of a variable can be referenced by the $ symbol.
The TCL interpreter divides the process of adding value to a command into two parts: analysis & execution.
- The analysis phase: TCL interpreter uses rules to break down the input command into A separate word The Commission shall, at the same time, The first is the "Replacement" 。
- The execution phase: The TCL interpreter takes the first word as the command name and checks to see if there is a definition for this command. If there is a definition, activate the corresponding C/C++ process for this command and pass all words as parameters to the command process for the process to be processed.
As we have mentioned before, in the tclsh interpreter,‘% The command prompt for TCL the following commands are omitted %, but please don't forget!), TCL executes the output command results on the next row after the input command is returned.
In addition, In tcl interpreters, use # as an annotation symbol the language used # as an annotation symbol is also Python, Ruby, Bash, PowerShell and so on.
- Software such as Gaussian, written in Fortran, uses
!as an annotator. - Double-slip
//or/* ... */: used as an annotator in C, C++, Java, JavaScript, Rust, Go, and other languages.
p.s. Therefore, when writing a file in Markdown language .md, only the opening # of the code is dyed as an annotated color when the specific code content is ```tcl.
1.2 Use of substitution functions
1.2.1 Examples of introductions
This is very important!!️: TCL interpreters treat all command parameters as strings when analyzing commands. The following are some examples to see what this means.
ex_1:
set x 10 # 定义变量x,并把x的值赋为10
10 # 交互式终端的输出结果
set y x+100 # y的值是x+100,x被当作是字符串x+100的一部分
x+100 # 交互式终端的输出结果
This is very different from the modern language, which should be 110 if used with a modern interpreter, so it needs to adapt to the uniqueness of tcl.
- What if the previous Section 1.1 example_3 used the $$$?
ex_2:
set x 10
set y $x+100
10+100 //这里仅仅是'$x'这一部分被替换为上面赋值的‘10’,10+100 被 tcl 当作一个字符串而非表达式
If we want to use the value of x defined 10 And then we have to tell the Tcl interpreter that what is expected here is that the Tcl interpreter will be able to understand the meaning of the word. Variable x value ,Not charactersx。
How to tell tcl this requirement? It is to be provided in tcl language. Replacement function
TCL offers three types of substitution:
- Changes in variables
- Order to switch
- Reverse slope replacement Note: 1) Each substitution results in one or more words themselves being replaced by another value; 2) substitution can occur in every word including the command name; 3) substitution can be embedded.
1.2.2 Variable substitution (variable subtitution)
- The variable is replaced by a $ symbol;
- A variable substitution causes the value of a variable to be inserted into a word.
For example, in the above ex_2 set y $x+100, because tcl takes 10+100 It looks like a string, not an expression. ; y is also It must be replaced by commands. used to obtain a value of 110, tcl can take 10+100 as an expression and thus derive its value.
1.2.3 Command substitution
- The command substitution is a TCL command and its parameters enclosed by
[ ] - A command substitution results in the words of one command being replaced by the results of another.
The following is an example:
set x 10
set y [expr $x+100]
110
Here y successfully obtained the 110 we expected. It is not difficult to understand, based on the second point above,[ ] that the contents of the first word in its bracket are re-assigned as a new command, which first processes the contents of the bracket:expr it becomes the name of the command within the bracket, thus activating the value of the corresponding expr C/C++ process, computing $x after the variable is replaced 10+100.
The following is a list of some of the most common types of cancer:
- If we remove
[ ]in the previous example, then TCL will report an error.... because under normal circumstances, TCL interpreter only sees the first word in the command line as a command other words are treated as Common strings , It looks like a command parameter. [ ]The first is that the TCL script must be valid. The length is unlimited 。[ ]in The value of the script is the return value of the last command 。exprIf a variable is introduced later, for example$a+$bThere are two ways to write:expr "$a+$b"orexpr {$a+$b}The latter is not prohibited from converting, and can be calculated directly by calling the cpp engine, while the former will also spend some time checking variables.
The following are examples of the importance of these reminders:
set y [expr $x+100; set b 300] # 优先处理 [ ] 的内容,而分号与换行符是分隔命令的,是允许的。故方括号内的最后一个命令是 set b 300,所以 y 的返回值为 300
In the end, a command substitution is actually represented by a The commands can be embedded between the commands. that is, a The result of one command can be used as a parameter for another command .
1.2.4 Backlash substitution
The inverse of the slope in TCL is similar to the inverse of the slope in C (as well as Markdown),It is mainly used for inserting characters in word symbols such as 换行符 ,空格 ,[ ,$ that are treated by TCL interpreters as special symbols to avoid being translated. and here's an example:
set msg multiple\ space # \ 使得后面的一个 space 不被转义为分隔符
mutiple space # 只有使用了 \ 输出结果才不报错
TCL will report errors if there is no \. Because The interpreter will consider the space between the last two words here as a separator. So, what? Finds that the set command has more than two parameters, and thus misses 。 After the addition of a 'space', the space is not considered as a separator, and the 'multiple space' is considered to be a whole word, even if there is a space.
It is worth noting that the anti-slip \ also has a unique Reverse slope replacement rule, which has Identify the markers and can be accomplished with some The process of conversion and ASCII code mapping :
Table 1.2 Backslash Sequence Replaced By:
| syntax | function |
|---|---|
\a | Audible alert (0x7) |
\b | Backspace (0x8) |
\f | Form feed (0xc) |
\n | Newline (0xa) |
\r | Carriage return (0xd) |
\t | Tab (0x9) |
\v | Vertical tab (0xb) |
\ddd | Octal value given by ddd (one, two, or three d’s) |
\xhh | Hex value given by hh (any number of h’s) |
\ | newline space A single space character, with the end of a line if there is \, indicating that the next line is at the end of that line |
For example, two examples of inverse-slope substitutions:
ex.1:.
set msg money\ \$3333\ \nArray\ a\[2]
money $3333 # 这个命令的执行结果为两行,由于有\n
Array a[2]
ex.2:.
set a \x48 #对应 \xhh
H #十六进制的 48,对应十进制正好是 4*16+8=72,对应 ASCII 码映射为 H
set a \110 #对应 \ddd
H #八进制的 110,正好是 72。因为 `8*8+8=72`(第一个1是从另一位进上来的,因此要有8次进位,而另一位也是8次进位来的,因此从左往右数的第一位 1 应该是 8*8,第二位 1 是 8,因此是 72,其对应 H
set a [expr \ #这一行的\即对应\newline space,故一个命令可以用\newline 转到下一行继续读取
2+3]
5
The reverse slope
\Line Continuation Character is commonly used as a continuation character, whereby a line character represents the end of a complete command and a reverse-slip character can be ignored to continue. It is important to note that the The inverse curve\must be the absolute last character of the physical line. So, in the example above,\(one more space behind the reverse slope) is only identified as a space below the non-translation, which causes error. When writing VMD map code, commands such as draw cylinders often require a long string of parameters (e.g., starting point coordinates, end coordinates, radii, etc.). If all of them were squeezed together, the code would be very difficult to read. So we're using it more when we write a string.\Continuous operation can increase the readability of code.
Computer common sense adds
- The decimal point is the decimal point. :
This is the most natural and familiar way of counting in our daily lives.
基本规则:它拥有 10 个基本数字(0、1、2、3、4、5、6、7、8、9),核心规则是“**逢十进一**”。比如数字 12,代表 1 个“十”加上 2 个“一”。因为我们人类有十根手指,所以十进制对我们来说最直观、最容易理解。
- The sixteenth hexadecimal :
This is a method of computation often used by programmers and computer scientists to shorten the numerical value of a binary system. The bottom of the computer actually only knows 0 and 1 (binary) However, binary writing is too long and the 16th can be perfectly abbreviated as binary.
基本规则:它有 16 个基本符号,核心规则是“逢十六进一”。
特殊符号:除了借用十进制的 0 到 9,为了凑齐 16 个符号,它还借用了英文字母来帮忙:A代表10,B代表11,C代表12,D代表13,E代表14,F代表15。
As we have seen in the previous Tcl language ex.2, \x48\x this means that it is a decimal number. Its conversion logic is: the number 4 represents 4 16 (i.e. 64), plus 8, and the decimal number we know as 72 is correct.
- The first is the "Fireflowers" (Octal). The rules are that the eight-point line is a straight line. It usually uses only the 0, 1, 2, 3, 4, 5, 6, 7 eight digit symbols.
- The following is a list of characters that first appeared in the American soap opera Once Upon a Time.
ASCII's full title is "A" US standard code for information exchange and you can use it directly as a "A" to help the calculator read human text.
为什么需要它:计算机的“大脑”里全都是数字,它根本不知道什么是英文字母“A”、什么是标点符号“!”。为了让计算机能显示和处理人类能看懂的文章,先驱科学家们就制定了这张通用的对照表。
工作原理:这张表规定了每一个常见的英文字母、数字字符或标点符号,都固定绑定一个对应的十进制(或十六进制)数字。
在 ASCII 字典里,大小写字母是严格区分、分开排号的。
Combining the results we just calculated, and going through the ASCII dictionary, you'll find that the decimal number 72 (i.e., 48 in 16 and 110 in 8) corresponds to the capital H. So when the computer is processing the string and encounters this value, it translates it into a dictionary that shows you a string H on the screen.
In summary: decimal is the habit of our daily human calculations, decimal is the abbreviation for computer data that programmers use to easily represent the underlying data, and ASCII is a reference dictionary that translates icy numbers into letters you can understand.
1.3 Double quotation marks and flower brackets
In addition to the use of reversal, TCL offers two other methods for making an interpreter, Use special characters such as separator and substitution characters as normal characters without special processing, which would be using binary quotation marks" " and flower brackets{}.
The following is a comparison of the two:
" "The TCL interpreter The various separators in the binary quotation marks will not be processed ,However, both substituents换行符and$and[ ]are normally dealt with。{ }: In the flower brackets, all special characters will be ordinary characters. , losing its special meaning, TCL interpreters do not treat it as special.
ex.1:
set y "x ddd"
x ddd # 输出结果表明双引号内确实成功将"x ddd"当作一个词来处理,并没有读取空格这个分隔符
ex.2:
set x 100
100
set y "$x ddd"
100 ddd # 输出结果表明双引号内顺利转义了变量置换,成功将 "$x" 置换成100,并且没有读取分隔符,空格没有被转义
ex.3:
set y {/n$x [expr 10+100]}
/n$x [expr 10+100] # 这里前面反斜杠也被如实打印出来,并且分隔符不读取, [ ] 内的命令置换也照样不读取其特殊意义,直接打印出来
1.4 Commentary
This section is actually mentioned in Section 1.1 and the notation in TCL is #. We will go into more detail below:
- The notation in TCL is
# #and all characters until the end of the line are considered by TCL as annotations- TCL interpreter The commentary will not be treated in any way (to distinguish it from the normal character on the above)
- Note that the place where
#The first character of the TCL interpreter expect command must appear appears is only considered as a commentary.
The following are examples:
ex.1:
#this is a comment
This example satisfies the syntax,# with the first character appearing as the command.
ex.2:
% set a 100 # Not a comment
wrong # args: should be "set varName ?newValue?"
The reason for the error is that # it does not appear as an annotator, and it appears in the middle of the command, and the TCL interpreter treats it and the characters after it as the parameters of the command, thus causing the error.
ex.3:
set b 101 ; # this is a comment
This # is used as an adjective because the previous command has ended with a subnumber.
Chapter 2: Variable
2.1 Simple variables
In this section we will briefly present the concept 简单变量 and the way in which set variables are used.
- A simple variable of a TCL consists of two parts: Name and Value 。 So what we use is Command + variable that is The command is + ((name + value) 。
- Tcl does not distinguish between the types of variables, and the variable names can be numeric, bottom line, small numbers, etc.
- The name and value can be any string For example:
set 1323 7&* # 这里表明 "1323 7&*" 的变量在 TCL 中都是合法的
- However, for better use of substitution, the variable name is best named after the naming rules for identifiers in C\C++ languages. For the content of substitution, see The following is a list of the most common types of diabetes:
- When analyzing a variable substitution, the TCL interpreter only names the word symbol between the $ symbol backwards and the first It's not letters, numbers or lower case characters. as the name of the variable to be replaced. For example:
set a 2
2
set a.1 4
4
set b $a.1 #因为 "." 不是字母/数字/下划线,因此在识别到 "." 的时候就截止了
2.1
In the last command line, we want to give the value of the variable a.1 to b, but TCL interpreterIn the analysis, only the $ symbol is followed by the word symbol (here .) between the first non-letter, numeric or downline character (here a) as the name of the variable to be replaced. so TCL interpreter substitutes a for 2, and then gives the string 2.1 to the variable b. This is clearly different from our original intention.
It is obvious that the case is met, but what if we do not want to replace the variable with a.1, and then we will not be able to replace it with a variable?
If the name of a variable is not a letter, number or lower-case character, it is replaced, The name of the variable can be enclosed by a floating bracket for example:
set a.1 4
set b ${a.1} # 使用花括号大成功
4
In TCL The set command can generate a variable or read or change the value of a variable ... for example:
set a {kdfj kjdf}
kdfj kjdf
If variable a is not defined yet, this command will generate the variable a and set it to kdfj kjdf If you a The first is that the definition of a simple a The value of kdfj kjdf。
I'll give you an example:
set a
kdfj kjdf
This is a set of parameters that only read the current value of the order a kdfj kjdf.
2.2 Grouping
2.2.1 Concepts of arrays
In this section we will learn some concepts: The method of declaration of arrays, array names, array elements, Tcl
The set of elements of an array It's a few. 。 There is a big difference between TCL arrays and arrays in ordinary computer languages:
- The following is the text: In TCL, an array cannot be declared separately, and an array can only be declared together with the array elements. 。
- The following characteristics:
- In arrays, the names of array elements have two parts: Group names and Name of the elements in the array 。
- The most flexible is the one with the most flexibility. The name of the array element in TCL (subs) can be used for any string
For example:
set day(monday) 1 # 生成 day 的数组,并切生成 monday 的数组元素,并把值设为1,下同
set day(tuesday) 2
The following is an example of this. The first command generates a Group named day, At the same time (because tcl arrays are declared with array elements) in the array Generate an array element named monday and Set the value to 1 The second command generates a name tuesday The value of the array element is 2。
- Important reminder: Tcl does not automatically convert ordinary variables to arrays
- If a variable is already defined as a normal variable (a metric), you absolutely cannot operate it as an array using brackets anymore
$x(...) - For example, if the previous one has been set to normal as
set day 2definesdaythen the next entryset day(tuesday) 2will be errorcan't set "day(tuesday)": variable isn't array
2.2.2 Replacement of the array elements
The replacement of simple variables has been discussed in the previous section, and here we talk about the replacement of array elements. In addition to having brackets, the substitution of array elements and simple variables are similar. 。 For example:
set a monday
monday # 设定 a 的值为 monday
set day(monday) 1
1 # 设置 day 数组,其中锚定一个 monday 的数组元素,并赋值为 1
set b $day(monday)
1 # b 的值为 1,即 day(monday) 的值
set c $day($a)
1 # c 的值为 1,这里先进行了变量置换把 $a 变成了 monday,即获取 day(monday) 的值
Other failures:
set c $day
can't read "day": variable is array
set a day(monday)
day(monday)
set c $day($a)
can't read "day(day(monday))": no such element in array
TCL cannot support complex data types, which is a big regret. The company has also been accused of many things about TCL. However, an extension of TCL's ITCL addressed this flaw.
What is complex data type?
If you consider a string Simple data types such as a number1, a characterA, a boolTrue, or a string of string that can be anything in TCL as a block The single LEGO building ; then a complex data type is a string of a complex data type such as a The model of a special toy, built with different colors and shapes of bricks (like a pickup truck, a castle) .
In TCL, the Although there are lists and arrays, they are essentially stacked together to make string strings. 。 while Modern high-level programming languages (such as Python and Rust) The first is the "Clean" and the second is the "Clean". The mold Oh, let the programmer It's a way to pack different data, even behavioral functions, into a structure. 。 That's what it's called. Complex data types 。
The following is a more specific example of Python and Rust:
Example A: Python's infinite nested dictionary
The array of TCL can only be a simple string-key string string string, while the array of TCL can be a simple string-key string, and the array of TCL can be a string-keyed string. Python dictionaries can include lists, other dictionaries, and even objects.
# 一个描述学生的复杂数据结构
student = {
"name": "Jimmy", # 字符串
"age": 20, # 整数
"grades": [95, 88, 92], # 列表里面装整数
"address": { # 字典里面嵌套字典
"city": "Shanghai",
"zipcode": "200000"
}
}
Example B: Python's object-oriented cluster (Class)
The class not only packs data (attributes) but also behaviour (methods). This is a concept that TCL does not have in its original form.
class Car:
def __init__(self, brand, speed):
self.brand = brand # 存放数据
self.speed = speed # 存放数据
def accelerate(self): # 存放行为(函数)
self.speed += 10
print(f"{self.brand} 加速到了 {self.speed} km/h")
my_car = Car("Tesla", 60)
my_car.accelerate()
Example C: Structure in Rust (Struct, original structure)
Rust is a system-level programming language. Structurists allow you to combine multiple different types of data into a meaningful whole. It is like a rigidly-hardened map.
// 定义一张图纸,规定一个 User 必须包含哪些数据,且类型严格固定
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
// 实例化一个 User
let user1 = User {
email: String::from("jim@example.com"),
username: String::from("Jim"),
active: true,
sign_in_count: 1,
};
Example D: Rust contains a list of data in the database (Enum, original enumerate)
The Rust listing not only shows the option of a few options, but also It's a great way to get involved in every option. a private bundle of goods Storing different types of data ), which Algebraic data type ADT is very powerful.
enum Message {
Quit, // 不携带数据
Move { x: i32, y: i32 }, // 携带一个匿名结构体
Write(String), // 携带一个字符串
ChangeColor(i32, i32, i32), // 携带三个整数
}
let msg = Message::Write(String::from("hello"));
After you look at Python and Rust, you will find out. They can very easily define a set of clear levels, strict type constraints, structures that bind data and functions together, and support complex data types.
while TCL native ((in cases where object-oriented extensions such as ITcl are not used) is essentially the only basic type of string 。 Even lists and arrays have special formats at the bottom. 。 If you want to represent the user structure of Rust in TCL, you can only put the data into a long string or complex list and analyze it yourself every time you use it, both easily and unintuitively.
2.3 set/unset/append/incr commands
set
The Commission's report on the implementation of the order is published in the Official Journal of the European Union. Section 2.1 。
unset
This is the order. Remove variables from the interpreter It's behind it. It can be any number of parameters , Each parameter is a variable name , It can be a simple variable. It could be. array or array elements 。 For example:
unset a b day(monday) # 删除了变量 a、b 和数组元素 day(monday),但没有删除数组 day
The above statement removes the variable a、b and the array element day ((monday), But the array day is not deleted and other elements are present, To delete the entire array, you just need to give the name of the array. . This example can be proven as follows:
set day(monday) 1
1
set day(tuesday) 2
2
unset a b day(monday)
puts $day(monday)
can't read "day(monday)": no such element in array
puts $day(tuesday)
2 # 这里可以发现关于 day 这个数组并没有被删掉
unset day # 这里删除整个数组
puts $day(tuesday)
can't read "day(tuesday)": no such variable # 这里发现顺利地删除掉 day 这个数组了
append&incr
These two commands provide a simple means of doing so. Changes in the value of the variable
appendOrder Add text to the back of a variable For example:
set txt hello
hello # 注意这里变量时 txt,故下文使用 append 的时候也要加 txt
append txt "! How are you"
hello! How are you # 直接添加在了文本的后面
incrOrder Add a variable to an integer (or subtract) 。incrRequirements The original value of the variable and the added value must be integers 。
set b a
a
incr b
expected integer but got "a" # 再次反映了对于该命令的要求是前后的值都必须是整数这一个要求
set b 2
2
incr b 3
5 # 当前后的值都是整数的时候这个命令就正常运行了
# 此外,如果加的数值为 1,则也可以直接写成:
incr b # 其等价于 incr b
6
# 如果要减去一个整数,则前面加个减号:
incr b -3
3
2.4 Rest and fragmented knowledge of the array
parray val: Displaysvalall elements in the array (Here is the link)valThe following is a list of the most commonly used methods for calculating the number of times- It is important to note that
parraycan only queryarray, cannot querylist..
- It is important to note that
- The array can also be multidimensional, such as:
set val(2,4) 6.4
puts $val(2,4)
Chapter 3: Expression
3.1 Operating numbers
Read more: What do the types of operation int and float mean?
The expression TCL Operating numbers is usually The whole number or Real numbers .
The whole number : In general English we use integer
- usually is The decimal point Yeah, I know.
- If the first character of an integer is
0(zero) So TCL will look at this as an integer. The Eightfold Method Yeah, I know. - If the first two characters are
0xSo this whole number is considered to be 16th of July Yeah, I know.
Real numbers : In general, we say that floating point numbers ≠ real are all real numbers. The spelling of TCL's real numbers is exactly the same as ANSI C (American National Standards Institute, abbreviated ANSI, whereas ANSI C is the standard set by ANSI for the C language). For example:
2.1,7.9e+126e43.
Here is an example of a real number calculation:
set c 1.2e+5
1.2e+5
puts [expr $c+1000]
121000.0
Storage of knowledge: type of operation, modeling, bit operation, logic, selection of operations
In the following section Section 3.2 Calculators and Priorities , some knowledge of programming is required. Here we will popularize some concepts of some of its pre-set knowledge.
i. What is the meaning of operating types int , float and string?
The first two words represent the two most basic types of computers The digital type :
int(Integer, whole number) : is a number that we use every day without small numbers, such as-2,0,100. In Tcl, The first step is to move the bit (i.e. left-move, right-move) and Modeling both must be required The operator is of typeint..float(Floating-point, floating point number) I mean: The real numbers with small numbers For example,3.14、-0.001、2.0。 It's called floating point floating point. Because when stored at the bottom of a computer, the location of small points is where the floating point can be held 。stringThe type is specifically tailored to a specific class of operations: Relational calculator (compared to the calculator) 。 The bottom line is that computers are based on what we've been through before. The ASCII code dictionary The first is the comparison, which is done in dictionary order.
ii. % What does Modulo mean?
The following is a list of the most common types of modules: I'm actually a math teacher in elementary school. Ask for the remaining number of digits 。
- Rules of computation :
a % bI mean, byaExcept forbAnd then Just take the remainder. 。 - Examples :
5 % 2The result is1(Because 5 is excluded by 2 vs. 2 plus 1)8 % 4The result is0(Because it can be solved, there are no remainder numbers)- In English, the remainder when 17 is divided by 5 is 2, written as
17 ≡ 2 modulo 5
- Commonly Used Scenes : In programming, Modeling it is often used Judging the Odds (e.g.
x % 2 == 0to say that the numbers are even) or to make the numbers rotate in a range.
iii. What is the concept of Bitwise Operations?
It's about computers. The bottom The way we think. The computer doesn't know decimal, only knows 0 and 1 (Bile) Bit operation is the process of computing directly on binary bits (bit). 。
In a strict sense, All bit operators (including by & It's not the same as the original. ^ By the bit or | and left/right shift <<、>> All of them. The strictly required operands must be of type int。
For example, the number
5in binary is101, the number3in binary is011.Common bit operators :
&(by bit and ): both are 1 and only 1 are observed carefully101 & 011, since the first two are different and only the last one has meaning, so by bit operation&it becomes001((i.e. decimal 1)).|(by bit or ): If there is only one, it is 1.101 | 011becomes111(i.e. decimal 7)<<and>>( Left and right shift ): To move the binary number integers to the left or right.~It's called Byte counter-rebates , Bitwise not 。 Put a binary bit characteristic of a number in the computer's base corresponding to 0 and 1) It's all over. 。 It turns out.0The rate of change1It was.1The rate of change0。 For example, you have a very small 8-digit integer that has a bottom binary representation of0000 0101The first is the ten-digit number 5. If it is executed~The first thing that I'm going to do is to make a decision about the process, and every single one of them turns around and the result is that it's a process that's going to be a process.1111 1010。
p.s.: If you are primarily a chemistry informant or write ordinary Tcl scripts, bit operations are usually very little used, all you need to know is that it is a bit Direct operation of binary 0 and 1 bit.
What is the concept of Logical Operations?
Logical operations are used to make judgments about what is true and what is false. 。 The results are usually two: It is either true = 1, or false = 0 The value of the two is called the bool value.
&&(logic with - AND): The two conditions must be created simultaneously, and the results will be true. 。- For example:
(年龄 > 18) && (存款 > 100). Only when the adult and deposit criteria are met is the entire condition passed.
- For example:
||(logical or - OR): The result is true if one condition is met. 。- For example:
(今天是周末) || (今天是节假日). You can rest as long as you meet one of these requirements.
- For example:
!(Not logically) : And make the truth false and make the false true. 。- For example:
!(下雨). It means "snow" if it doesn't rain.
- For example:
v. What is the concept of a Choice/Ternary Operator?
This is a very clever The short-text grammar of the language and very common in tcl. It is used specifically to replace simple if-else judgments.
- The grammar formula :
a ? b : c(note the gap!) - How to read :A preliminary judgment
aon whether it is valid (for true) is given. If it is, return the value ofb; if not, return the value ofc.。 - Examples :So in this example, because 20 is greater than 18 is true, so
set age 20 # 如果 age 大于等于 18,输出 "成年",否则输出 "未成年" set status [expr {$age >= 18 ? "成年" : "未成年"}] 成年 set status [expr {$age >= 18 ? 成年 : 未成年}] invalid character "成" in expression "$age >= 18 ? 成年 : 未成年" # 说明中文得用双引号来避免转义识别错误 set status [expr {$age >= 18 ? "yes" : "no"}] yes set status [expr {$age >= 18 ? yes : no}] yesstatusThe value of the"成年"。
3.2 Calculators and priorities
The operators used in TCL are very similar in their syntax and usage to ANSI C: The following operators are ranked by priority from high to low (the same as the operator priorities in the same grid)
Table 3.2 Ranking of the priority of the calculator
| The syntax | The results | Type of operation |
|---|---|---|
-a | Negative a | int,float |
!a | not a | int,float |
~a | Bit operation not | int |
a*b | multiplication | int, float |
a/b | division | int, float |
a%b | The model This is the surplus | Modeling to int |
a+b | addition | int, float |
a-b | subtraction | int, float |
a<<b | Bit operation, left shift | int |
a>>b | Bit operation, right shift | int |
a<b | Less than | int, float, string |
a>b | It's more | int, float, string |
a<=b | Less than equal to | int, float, string |
a>=b | It's equal to | int, float, string |
a==b | It's equal to | int, float, string |
a!=b | It's not equal to | int, float, string |
a&b | Bit operation and | int |
a^b | Bit operation is different or | int |
a|b | Bit operation or | int |
a&&b | Logic and | int, float |
a||b | Logic or | int, float |
a?b:c | Select the calculation | a: int/float |
p.s.: In Tcl You can use it very intuitively, directly. == or < The content of the two strings is compared. In C language , It is not possible. Directly == So, what's the point of comparing the content of two strings? If written in C string1 == string2 The computer base Comparison The fact that the two strings are in memory is the gate mark. (pointing address) is the same? The characters in the book are different, not the same as the characters in the book. Compare strings in C language and call for a dedicated standard library function strcmp()。
3.3 Mathematical functions
- TCL supports commonly used mathematical functions, and the writing of expressive mathematical functions is similar to that of C\C++ languages.
- The parameters of a mathematical function can be arbitrary expressions, separated by commas between multiple parameters. 。
3.3.1 Expr command
exprThe command is a command from the tcl interpreter.- The language :
expr arg ?arg ...?Two of them?The parameters between the two are represented by the This form of representation is used for all of the commands introduced below. Parameters saved 。exprIt can be one or more parameters that put all the parameters together as an expression and then it takes value. 。
Ex.1 Calculate 2; sin x<3)
set x 2
2
expr 2*sin($x<3)
1.682941969615793
Ex.2 body combination, note the difference in the interval number between the two expressions below
expr 1+2*3
7
expr 1 +2 *3
7
expr 1 + 2 * 3
7
The following is a summary of the mathematical functions supported by Tcl interpreters:
Table 3.3.1 Math Functions supported by TCL
| Function | English Description | Chinese Description |
|---|---|---|
abs(x) | Absolute value of x. | The absolute value of x |
acos(x) | Arc cosine of x, in the range 0 to p. | The inverse of x, ranging from 0 to π |
asin(x) | Arc sine of x, in the range -p/2 to p/2. | The inverse of x, ranging from -π/2 to π/2. |
atan(x) | Arc tangent of x, in the range -p/2 to p/2. | The inverse of x, ranging from -π/2 to π/2. |
atan2(x, y) | Arc tangent of x/Y, in the range -p/2 to p/2. | The inverse of x/y, ranging from -π/2 to π/2 |
ceil(x) | Smallest integer not less than x. | The smallest integer of x is ((i.e. Up and down ) |
cos(x) | Cosine of x (x in radians). | The unit of x is the arc |
cosh(x) | Hyperbolic cosine of x. | The double chord of x |
double(i) | Real value equal to integer i. | Converting the integer i to an equivalent real number (the floating point number) is a very useful type of conversion. |
exp(x) | e raised to the power x. | x times e |
floor(x) | Largest integer not greater than x. | The greatest integer of x is not greater than Down and down |
fmod(x,y) | Floating-point remainder of x divided by y. | x minus the remaining number of floating points in y |
hypot(x,y) | Square root of $(x^2+y^2)$ | $(x^2+y^2)$ The square root of x is the length of the hypotenuse of a right triangle |
int(x) | Integer value produced by truncating x. | The fraction of a fraction of x that is cut off produces an integer value, i.e. the floating point number takes the fraction of x and takes the whole |
log(x) | Natural logarithm of x. | The natural number of pairs x is equal to e |
log10(x) | Base 10 logarithm of x. | The prime of x is 10. |
pow(x,y) | x raised to the power y. | The y-axis of x, in addition to ** can also be expressed as a c. |
round(x) | Integer value produced by rounding x. | The total value of the floating point x after 4x5 is integrated into the whole |
sin(x) | Sine of x (x in radians). | The unit of x is the arc |
sinh(x) | Hyperbolic sine of x. | The double chord of x |
sqrt(x) | Square root of x. | So x is the square root of x, and the root is zero. |
tan(x) | Tangent of x (x in radians). | The unit of x is the arc |
tanh(x) | Hyperbolic tangent of x. | The binary of x is right. |
*:M_PI is a built-in π variable that can be referenced with $M_PI
There are many commands in TCL. Expressions as parameters 。 The most typical are the expr commands, and the if, whilst, for and so on. The term "expression" is also used as a parameter in the control of cycles.
Chapter 4: List
4.1 list commands
- List is a relatively important data structure in TCL that is very useful for writing complex scripts.
- The term list is used in TCL. Indicates the set
- The list in TCL is An ordered set of elements :
- list Can be embedded ,list Each element can be an arbitrary string, or it can be a list.
- The list elements are wrapped in flower brackets 。
The following is a list of legal acts in TCL:
{} # 空的 list,列表个数为0
{a b c d}
{a {b c} d} # list 可以嵌套,这里列表个数为3
TCL provides a number of basic instructions for operating the list, one by one:
- The wording:
list ?value value...? - This command The elements of a list are all values. :
list 1 2 {3 4}
1 2 {3 4}
Example of error: ((list is the recognizable command!)
list1 {a b}
invalid command name "list1"
In Tcl, how do we distinguish between different lists (and the elements within them)?
This is about the core philosophy of Tcl: stringing everything together. In Tcl, List is not a special complex data structure in memory. It is essentially a string of standard strings.
The Tcl interpreter The list elements are separated and broken down entirely by separator and packet. states:
1. 空格作为天然分隔符:
Tcl 默认用空格(Space)、制表符(Tab)或换行符来区分列表中的不同元素。比如字符串 a b c,在 Tcl 眼里天然就是一个包含 3 个元素的列表。
2. 花括号 {} 划分边界与嵌套(最常用):
如果你的某个元素本身就包含空格(比如一个英文句子,或者一个子列表),为了不让 Tcl 把它拆散,你必须用花括号把它包裹起来。
举例 1:{how are you} 作为一个整体被花括号包裹,这就只是一个单元素。
举例 2:{a {b c} d}。Tcl 看到外层花括号,知道这是一个大列表;通过数内部空格,它认出第 1 个元素是 a,第 3 个元素是 d;中间的 {b c} 因为被花括号包着,所以被当作整体作为第 2 个元素(同时它也是一个子列表)。
3. 双引号 "" 划分边界:
和花括号类似,双引号也可以用来将包含空格的字符串打包成一个单独的列表元素。区别在于,双引号内部允许发生变量置换($)和命令置换([ ]),而花括号内部则是原封不动的纯文本。
In short: in Tcl, you It's not like you need to specify a list of languages. The interpreters are the levels of the numerical spaces and the matching brackets/double quotes. , to distinguish precisely which parts are separate lists and which are sub-elements of the list.
4.2 Concat command
concatThe full title is concatenate In English, the term "plugging", "connecting", and "setting" are synonyms for "plugging".- The wording:
concat list ?list...? - This command The first step is to combine multiple lists into one list, and each list becomes an element of a new list. to convert the parameter into a new list of sub-elements is a function of the
listcommand, while theconcatfunction is Breaking the boundaries, merging elements - It removes the spaces at the end of each parameter when it is spelled and seamlessly connects them with a single space. When you have multiple independent lists and want to align them and merge them into a continuous large list,
concatit is the perfect choice. - Below we will compare the commands
concatandlist:
set list1 {a b} # 用 set list1 "a b"也可
set list2 {c d}
# 注意下面都要用到命令置换
# 场景 1:使用 concat 拼接
set result_concat [concat $list1 $list2]
puts $result_concat
a b c d
# 解释:原来两个列表的“包装”被拆掉了,里面的 4 个元素被合并成了一个单层的新列表
# 场景 2:使用 list 命令组合
set result_list [list $list1 $list2]
puts $result_list
{a b} {c d}
# 解释:每个原来的列表整体变成了新列表中的一个独立元素。这是一个包含 2 个子列表的“嵌套列表”
# 场景 3:日常使用的 concat
concat {4 3} {2}
4 3 2
4.3 lindex command
lindex The main role is Extract items from a list that are located in a specified location 。
- The language :
lindex list index - Function : return the third
indexelement inlist - The rules of indexing are very important The list index for Tcl is: 0-based And that's what I mean. The first element index of the list is
0, and the second is1, with such a push。
The following are examples:
lindex {1 2 {3 4}} 2
3 4
# 这个列表共有 3 个元素:第 0 个元素是:1; 第 1 个元素是:2; 第 2 个元素是:3 4 (它作为一个整体被外层的花括号包裹),要求获取索引为 2 的元素,所以输出结果就是 3 4。
In addition to using specific numbers,lindex's
indexparameters also support a very convenient keyword:endIf you, I want to get the last element of the list no matter how long the list is, write directly:
lindex {a b c d} end# output:dIt can even be combined with the end for simple calculations, such as getting the second element of the counter number:
lindex {a b c d} end-1# output: cMulti-dimensional list extraction (Tcl 8.4+ Support): If your list is nested, you It is possible to continuously input multiple indices to directly grab deep elements ; for example, want to get the 0th element in the second element {3 4}:
lindex {1 2 {3 4}} 2 0# output:3
4.4 Lingth command
- The language :
llength list - The role Return to the list: Number of elements 。 For example:
llength {1 2 {3 4}}
3 # 显然 {3 4} 被当成子表
4.5 Linsert command
- The language :
linsert list index value ?value...?The new string is back, the new string is back. Insert allvalueparameters intolistbefore the thirdindex(0-based, i.e. counting from 0) element I got it. (Note: the monkey is a monkey) Before ”!!!) Example:
linsert {1 2 {3 4}} 1 7 8 {9 10}
1 7 8 {9 10} 2 {3 4}
This should be divided into three parts to see,{1 2 {3 4}} and is considered a list, followed closely by 1 index as it starts from 0 and is then inserted 2 in front of it. The value inserted is index1) behind 7 8 {9 10}
4.6 Lreplace command
- The language :
lreplace list first last ?value value ...? - Returns a New thread , the new string is obtained by taking the elements from the list first (0-based) to last (0-based) with all The value of the parameter .
- If there is no value parameter, it means that the elements from
firsttolastare removed.。 Example:
lreplace {1 7 8 {9 10} 2 {3 4}} 3 3
1 7 8 2 {3 4}
# 先识别 list 为 {1 7 8 {9 10} 2 {3 4}},然后 first 为 `3`,last 为 `3`,故从以0开始计数的第3号数到第3号数结束,这里第3号数应为{9 10},由于没有 value 参数,于是直接删除。
lreplace {1 7 8 2 {3 4}} 4 4 4 5 6
1 7 8 2 4 5 6
# 分为四部分,{1 7 8 2 {3 4}} 为 list,4 为 first,4 为 last,其 4 号对应为 {3 4},最终其替代的 value 为 4 4 5,故替换成功后,直接得到如上结果。
4.7 Lrange command
- The language :
lrange list first last - A string consisting of the first (0-based) to last (0-based) element of a return list If you Last is end And the first one is from the first. The end of the line 。 Example:
lrange {1 7 8 2 4 5 6} 3 end
2 4 5 6 # first为3,故从以0开始为计数的第3个即为2,从那个数开始直到最后
# 有时,甚至可以是 end-1 选取倒数第二个
4.8 Lappend command
Before the introduction, it is highly recommended to make a comparison with The following article is a summary of the results: .
- The language :
lappend varname value ?value...?take Each value ofvalueis added as an element to The variablevarname((variable name) behind And then we'll return the new value of the variable. Ifvarnamedoes not exist, this variable is generated。
Below we will give examples to distinguish between append and lappend:
appendIt's used to spell strings.appendAnd then we'll take the following parameters as The text is pure The original variable is fixed at the end of the original variable. It doesn't automatically add space in the middle, and it doesn't care what the original content is.lappendis used Adding elements to the list .lappendThe target variable is treated as a list. It Each parameter followed as a separate list element , attached to the end of the variable.lappendautomatically adds spaces between the original list and new elements, and between each new element. It is more intelligent to automatically add brackets{ }if the added new element contains a space itself.
# append 直接把追加的参数当作纯文本直接导入
set mylist "a b c"
a b c
append mylist "d" "e f"
a b cde f
# lappend 把追加的元素当作 列表元素
set mylist "a b c"
a b c
lappend mylist "d" "e f"
a b c d {e f}
4.9 Lsearch command
- The language :
lsearch ?-exact? ?-glob? ?-regexp? list pattern( Select the parameters of the matching pattern, or by default -glob, and then follow the list and the elements to be found. ) - Return the index of elements of the first matching pattern pattern in the list, and return -1 if no matches are found. 。
-exact、-glob、-regexpIt is a technology that matches three models.- The following table shows the matching method of the string commands:
-exactindicates The exact match ;-globandandstring matchthe same way as the command matches, which will be explained later when the string command is introduced;-regexpindicates The official expression matches . - The default is to use
-globmatching.
Example:
set a { how are you }
how are you
lsearch $a y*
2 # 不写明时默认 -glob 匹配,这里‘*’则说明只需要y开头的元素,而无所谓y后面的长度。返回 pattern 的元素索引(lindex),由于是从0开始计数的,所以2对应的就是列表元素 you,
lsearch $a y?
-1 # 不写明时默认 -glob 匹配,这里'?'代表任意单个字符,之所以返回-1是因为长度限制了只有两个字符并且y开头的。
# 再举一例,下面这些例子输出结果都是合理的:
set a { what do you mean }
what do you mean
lsearch $a m*
3
lsearch $a mean
3
lsearch $a m?
-1
lsearch -exact $a m*
-1
# 下面举一个简单的例子,来提醒别忘了变量置换!
lsearch a m*
-1 # 之所以报错,是因为这里 a 没有成功地被认为是一个表格,而是一个纯字符串a,因此这里找不到便返回 -1 了
The following is a brief description of why -exact ,-glob ,-regexp and how to write:
1 -exact (accurate match)
It's the most rigorous, the most rigorous way to match.
- Rules : Target strings You have to be with the pattern you're looking for. The same thing, 100% is absolutely equal. 。 The first is that the letter "A" is not a single letter.
- Examples : If you look for
-exactappleit only recognizesapple. such asApple: different size)apples: more than one s) is not a match.
2 -glob (compound matching) shell Tcl default mode
It is a simple and extremely commonly used blur matching method. Its matching rules are exactly the same as those in Tcl,string match and are similar to those used when searching for files on a computer.
- Rules You: Some simple place-marks can be used (i.e. consonants) to replace uncertain characters。
- Commonly used couplers :
*: representing The length of the Any string including empty strings).?: representing any The single character.[chars]: Any One of them. character in a matching character set (e.g.[a-z]represents matching a to z to any lowercase)
- Example 1 : If you look for
app*with-globthenapple,applicationand even a singleappcan be matched successfully. - Example 2 : Delete the current directory with
orbbeginning with.cubfiles, and runfile delete {*}[glob orb*.cub], hereglobis the return of all file names that meet the specified consonants, i.e. any length.cubfiles starting withorbfiles. Note that here[glob orb*.cub]The middle brackets must be used to ensureglobthat this matching method of the coupling is identified as a command and as a command substitution.:.
It is important to note that the rules of the convex notation,-glob are to be distinguished from -regexp .
3 -regexp (corresponding to the normal expression) written with the normal expression
This is the most powerful and complex end-text matching technology.
- Rules : Using a whole set of logical languages consisting of special symbols (regular expressions, regular expressions) to describe extremely complex text characteristics. it Not only can it specify what characters to look for, but also how many times they appear, where they appear (e.g. must be at the beginning
^or end$) etc.。 - Examples : When processing data in chemical information science, if you want to extract a molecule that starts with capital letters and is followed by a number of numerical molecules, you can write a normal expression similar to
^[A-Z][0-9]+to accurately capture it.
If the direct order is regexp rather than a parameter, the syntax is regexp {pattern} $x..
{pattern} The standard expression needs to be protected by encapsulation {}。 The simple normal expression enters the text (simply understood as finding the rule):
^: The beginning of a string 。 It means that you have to Starting with the first character, it's a strict match. ”。$: The end of a string 。 This means that the potassium matches until there is no other impurities in the potassium.
.: matches any character.*: representation The characters in front can occur 0 or infinitely.?: The characters in front The number of words in the word can be 0 or 1 times (possibly or not).+: The characters in front occurring 1 or more times (at least) ⋅
In the normal, the middle brackets represent a string:
[a-z]: matches any small letter of the alphabet.[0-9]: The allowed characters are any number between 0 and 9.[A-Za-z0-9]: matching arbitrary letters and numbers.
For example, for variable substitution commands [regexp {^[0-9]*$} $x] And the one who is {^[0-9]*$} And that means that the string is from the beginning. ^ To the end $ It's got to be all numbers. [0-9] And I'm not sure what the numbers are. * I can do that. It is still necessary to remind people that {pattern} It's still in the packaging.
4.10 lsort command
The language :
lsort ?options? listlsortThis command is used to sort and execute Return the string after the list is sorted 。optionsThe value of the data can be as follows:-asciibyASCIIThe order of the characters The first is the comparison.optionIt's the default.- The first three elements are the following:
-dictionaryAccording to The order of the dictionary and-asciithe places where they differ are: (1) Not considering size (2) if there are numbers in the element, The numbers are sorted as integers (3) If the letters are exactly the same, then return to ASCII code to decide on a negative value.
Adopted The order of the dictionary The big boy is between bigbang and bigboy (this is the first example), x10y is between x9y and x11y. In the ASCII code table, The number of capital letters is smaller than the capital letters (Latin:
BIt's 66, small.bIt was 98. So the numbers are smaller.bigBoyI'm in line.bigboyThe front of the 。
The following commands are also used options, and multiple options parameters can be filled at once to satisfy the required sequence order:
-integerConvert the elements of a list to integers, and sort them by their integer.-realConvert the elements of the list to floating point numbers, sorted by floating point number.-increasingFrom left to right upstream order (as compared to ASCII characters) is the default order of tcl.-decreasingDisplacement (as compared to ASCII characters)-command command: Custom order, front-commandto follow the self-definedcommand(the name of this command can be customized) TCL automatically uses the command to compare each element one by one and then give the ordering results.-uniqueRepeated list elements can be removed
Small trick: Sometimes we want to sort things out in a complex way, like a set of words, and we don't want to sort them alphabetically, but rather by the length of the words. And then you can write a book.
procThe Tcl automatically uses it to compare each of the two elements one by one. Rules of Use: This customized refereeing process is a refereeing process. The two parameters must be received (i.e. the two elements to be compared) and The number of elements in the set is equal to the number of elements in the set. :
返回 -1:表示第一个元素应该排在前面。
返回 0:表示两个元素一样大(打平)。
返回 1:表示第二个元素应该排在前面。
For example:
set list1 {acc bcc dcc}
acc bcc dcc
lsort -dictionary -decreasing $list1
dcc bcc acc
-command command The following is an example of a custom order:
# 第一步:写一个“裁判过程”,定义名称为 compare_length (比较两个字符串的长度)
proc compare_length {a b} {
set len_a [string length $a]
set len_b [string length $b]
if {$len_a < $len_b} {
return -1
} elseif {$len_a == $len_b} {
return 0
} else {
return 1
}
}
# 第二步:使用 -command 参数,并把我们的裁判过程名字传给它
set list1 {apple banana pear kiwi watermelon}
lsort -command compare_length $list1
pear kiwi apple banana watermelon # 根据上述过程,自定义的单词字母越短(因为比较 string length)则排名越靠前,即越往左
4.11 Split command
- The language :
split string ?splitChars? - SplitChars separates the string into a single word. The word "symbol" is a synonym for "symbol".
- If splitChars is an empty character { } , String is separated by characters (This should be
{}The characters. - If splitChars is not given, use the space as a separator 。
Example:
split "how.are.you" .
how are you
split "how are you" {}
h o w { } a r e { } y o u
split "how are you"
how are you
4.12 join command
- The language :
join list ?joinString?joinThe order is Inverse of a command 。 This is the order. Combine all the elements in the list into a string, separated by the joinString in the middle. 。 The default joinString is empty.
The reverse of split is understood to be the process of split.
Example:
join {h o w { } a r e { } y o u} {}
how are you
join {how are you} .
how.are.you
An application of the command join can be found in ex.11.27..
4.13 Lassign command
- The wording:
lassign {a b c} x y z - The list elements in the list can be assigned to the following variable in turn.
For example:
lassign {a b c} x y z # x的值被赋予为a,其余类推
puts $x
a # 核验赋值正确
- In particular, if it is
lassign {d e} x y z, it isx=d y=e.. - If it is
lassign {f g h i} x y, it isx=f y=g..
Chapter 5: Control of flow
Control flow in TCL is similar to the C language, including commands such as if,whilefor,foreachswitchbreakcontinuereturn and others.
Before learning, we have to stress again: when writing control flow in Tcl (if 、while 、for etc.),The distance between the right brackets } , keywords and left brackets { must be kept at least one empty space forever.!
5.1 if command and switch command
5.1.1 if Commands
- Sentences:
if test1 body1 ?elseif test2 body2 elseif....? ?else bodyn?# This should be seen as three parts/if a b//elseif c d elseif...//else e/ - Specific rules: TCL executes test1 As an expression for value , If it is not 0 and returns body1 as a script Execute and return the value of the income ; Otherwise tests2 as an expression to the value, and if it is less than 0, executes body2 as a script and returns the resulting value... so repeatedly.
- The point is that you Each block of code (including the parentheses) and keywords must be clearly separated by a space. 。
- For example:
if {$x > 0} {
......
} elseif {$x == 1} {
......
} elseif {$x == 2} {
......
} else {
......
}
It can also be:
if {$x>0} {
......
} elseif {$x==1} {
......
} elseif {$x==2} {
......
} else {
......
}
Note that in the above example { Must be written in the first line, becauseIf not, the TCL interpreter will assume that the if command has ended at the intersection note and the next line is considered a new command, leading to an error result., this is also noted in the writing of the following loop commands. One of the problems to be noted in writing is that between if and {, There should be a space. otherwise the TCL interpreter would take if{ as a whole as a command name, which would lead to errors.
5.1.2 switch Commands
- and C
switchThe same thing happened in TCL.switchThe command can also beifThe commands are executed. It's just a little bit more trouble writing, noifThe command is so intuitive. - But in functional implementation, it can be considered as The first is the super evolution of silicon, the more refined if-elseif-elsei silicon. . When you have a variable and need to make an extremely cumbersome multiple choice judgement based on its value, using
switchis the most elegant.
switchThe order's syntax is:switch ?options? string { pattern body ? pattern body ...?}- The first is Selectable parameters
-optionsThe following is a list of How to match 。 TCL supports three matching modes: exact mode, glob mode, and regexp mode. The following is a list of the most commonly used methods for calculating the value of a currency. Section 4.9 The difference is,lsearchdefault matching method-globandswitchThe default matching method is-exact - The second parameter
stringis to be used as a test value. - The third parameter is a pair of elements that are bounded together.
In simple terms, switch The principle is you. The default is to match it (not write-exact) with a target string (i.e. string). And then it takes this string, and it goes up and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down and down The model is a "sort of" pattern) The first is the comparison. The script code behind the matching is executed immediately:body)。
The most recommended spelling of the syntax if is:
Ex.1 switch Recommended writing: Judging ratings examples
set grade "B"
# 下面的 $grade 就是 string, 默认匹配方式是 -exact,"A" 就是 pattern,后面接着执行脚本的内容 body
switch $grade {
"A" {
puts "优秀!"
}
"B" {
puts "良好!"
}
"C" {
puts "及格!"
}
default {
puts "未知成绩或不及格!"
}
}
Here $grade is the goal we want to judge.switch We will take the B-section and look downwards. After finding the B-section, we will execute the following {puts the B-section well!}.default This is a keyword that stands for else. If none of the above match, we will execute the code in default default.
Ex.2 switch High-level play: combined matching mode
If you don't write a parameter, the default switch is -exact(Accurate matching) ⋅ but if you want to blur matching, you can add -glob or -regexp.
set file_name "data_001.txt"
# 使用 -glob 通配符模式,通配符的常见模式可以见 第4.9小节
switch -glob $file_name {
"*.txt" {
puts "这是一个文本文件"
}
"*.csv" {
puts "这是一个表格文件"
}
default {
puts "未知文件格式"
}
}
Ex.3 switch Multiple conditions share a single piece of code (using a linked character -)
If you have several different situations and want to perform exactly the same operation, you can use a decimal number - minus one - to represent the number of digits. The same pattern and same body is used.
set fruit "apple"
switch $fruit {
"apple" -
"pear" -
"peach" {
puts "这是一种蔷薇科的水果!"
}
"banana" {
puts "这是香蕉!"
}
}
Here, if the fruit is any apple, pear or peach, it will slip smoothly down and perform the same printing. (Because they are all roses.)
Ex.4 switch Example of template
switch $x {
a -
b {incr t1}
c {incr t2}
default {incr t3}
}
where a And then there's a - Indicates the same script used as the next pattern。default Indicates the matching arbitrary value。 Once you've got it switch The command to find a pattern matching, execute the corresponding script and return the value of the script as the return value of the switch command.
5.2 Circular commands
The circular commands include while ,for ,foreach etc.
5.2.1 while command
- The wording:
while test body - The parameter
testis a Expressions ,bodyis a The script - If the expression is less than 0, run the script until the expression stops cycling at 0. , While the command interrupts and returns an empty string 。
- If
while {1} {...}is true, it represents the eternal truth of the argument), i.e.while {True} {...}it generally represents an infinite loop. In tcl language scripts,while {1} {...}it is usually written in conjunction withbreakto jump out of the loop.
For example: Suppose a is a The Chain Table , the following script copies the value of a to b:
set b " " # 返回一个间隔符
set i [expr [llength $a] -1]
while {$i>=0} {
lappend b [lindex $a $i]
incr i -1
}
Explanation: Here, divide by two, one is the expression i One is the script. {lappend b [lindex $a $i] incr i -1 } The first is the "Blood of the Dead", which is a book about the life of a young boy.
For the i The value is defined as the chain table. a The length of the numerical value minus one is the beginning of the i The value of the (Note, why should I? $i_{max}-1$ This is because the count of the lindex below is 0-based, and the count of the lingth is 1-based in accordance with our intuition, so here to subtract from 1 and below compatibility, starting obviously from the last value of the chain table; the i value after that is from below incr i -1 The first is the controlled cycle. The following loop command checks for its expression each time. $i>=0 And this is the script below. incr i -1 The script itself is executed at the end of each cycle. i-1 The process of self-testing $i>=0 When $i=0 then while The first is to break and return an empty string. The script is actually executed by lappend b [lindex $a $i] I'm going to give it to you every time. b List of adding elements to the list [lindex $a $i] and lindex $a $i I'm going back to the chain every time. $a The following is a list of articles related to i The value is inserted into the b。 The details here are: lappend b [lindex $a $i] The command is executed by replacing another line of script with a line marker to avoid error.
5.2.2 for command
- The wording:
for init test reinit body - The argument
initis one Initial script , the second argumenttestis one Expressions , used to determine when a loop breaks, the third argumentreinitis one The script for the restart and the fourth argumentbodyis also The script .
If you want to design a script with the same purpose as an instance and Section 5.2.1 Subsection using the command for, you can write:
set b " "
for {set i [expr [llength $a] -1]} {$i>=0} {incr i -1} {
lappend b [lindex $a $i]}
5.2.3 Foreach commands
foreachIt's a good idea to understand Elements in the circular list The simplest way to do this is to use a few lines that are simple. The World The way. This command can be used to Section 5.1.2 ofswitchThe command to compare.switchis Choose your questions , andforeachis done Water pipe or pipe for transmission . It is the strongest loop command in Tcl specifically used to deal with lists.foreachThe key advantage of this is that you don't have to worry about it.indexAnd you don't need to write.$i < [llength $list]The first is that the world is not going to be able to see the light of day.
The command has two syntactical forms:
- The syntax 1 :
foreach varName list bodyThe first parametervarNameIt's one. Variable The second parameterlistIt's one. Table (Ordered set), third parameterbodyis Circulars 。foreachEach time an element of a chain table is obtained, the loop is executed once.
The following example has the same function as the preceding cases Section 5.2.1 Subsection and Section 5.2.2 :
set b " "
foreach i $a {
set b [linsert $b 0 $i]
}
The code above is simply to remove the list from $a The first is the reverse of the element. and save it to the new list $b.
set b " "Initial opening of the empty container 。 Create a variable called b with an initial value of a space. In dynamic type analysis of Tcl, this is equivalent to preparing an empty list container. (Note: More stringent and standard writing is usuallyset b {}The first is that the space can be used to create a space. )foreach i $a {The road to the cross 。 We're not going to be able to do that.foreachLike a stream of water, From left to right, each element in the old list$ais grabbed in sequence and temporarily stored in a variablei(This process is called The World )。set b [linsert $b 0 $i]Linsert is a list insert command, and the number 0 represents the index of the list 0 (because it is 0-based, that is, top). The goal of this is to capture the elements that are present.$iAnd it's always on the list.$bThe first element of the number 0.
However, in modern versions of Tcl (8.5 and above), the official version has already been provided with a A command specifically for reverse lists to improve operational efficiency. In actual project development, you can directly replace the entire loop above with this line of code, which will be higher:
set b [lreverse $a]
Ex.1 The most basic of the two is the one that runs through the cage.
set fruits {apple banana orange}
# fruit 是变量名,fruits 是装满元素的列表,该列表的元素会被遍历临时存储在 fruit 这个变量中,然后执行脚本内的内容
foreach fruit $fruits {
puts "我吃了一个 $fruit"
}
# 输出结果:
我吃了一个 apple
我吃了一个 banana
我吃了一个 orange
Ex.2 One-shot multiple elements: capturing molecular coordinate data
This is similar to lassign (see Section 4.1.3 ). Many other programming languages foreach only use one element per time, but Tcl allows you to capture multiple elements at once .
set coords {1.0 2.0 3.0 4.5 5.5 6.5}
# 一次性分配给 x, y, z 三个变量
foreach {x y z} $coords {
puts "原子的坐标是:X=$x, Y=$y, Z=$z"
}
# 上述方法可以让 foreach 在进行遍历的时候以三维度的变量进行匹配抓取
# 输出结果:
原子的坐标是:X=1.0, Y=2.0, Z=3.0
原子的坐标是:X=4.5, Y=5.5, Z=6.5
Ex.3 Go through multiple lists at the same time
- The wording:
foreach 变量1 list1 变量2 list2 { 执行动作 }
Sometimes you have two completely separate lists (for example, one is the name of an atom and one is the atomic number) and you want to process them in a row together, you can do this:
set atoms {C H O}
set ids {1 2 3}
# 同时从原子的列表和序号的列表里拿东西
foreach atom $atoms id $ids {
puts "$id atom is $atom"
}
# 输出结果:
1 atom is C
2 atom is H
3 atom is O
5.2.4 break and continue commands
In a circular body, the commands break and continue can be used. Disrupted cycle
- The following are the commands
breakFinishing the whole cycle and Jumping out of the loop continueIt's just End the cycle 。
5.3 eval commands and source commands
evalA command is a command used to construct and execute a TCL script, which is a command that is used to execute a TCL script. It's not important. 。 The wording:eval arg ?arg ...?It can take one or more parameters, then combine all the parameters into a single script separated by spaces, and then query the value of that script.sourceOrder Read a file and retrieve the contents of that file as a script 。 Generally, we use this command to call scripts. For example:source e:/tcl&c/hello.tclNote the description of the path It should be compatible with UNIX. ,Use of the/It's not\。
Chapter 6 The process:
6.1 Process definition and return value
6.1.1 Definition of the process
The TCL supports the definition and calling of processes, In TCL, the process can be seen as a command executed using the TCL script. which results in similarities to the inherent commands of TCL. We Can be used at any time proc Commands to define their own processes see that processes in TCL are similar to functions in C.
The TCL process is generated by the proc (full name is procedure) command:
For example:
proc add {x y} {expr $x+$y}
- The first parameter of the proc command is The name of the process you want to define , the second parameter is List of parameters of the process , The space between the parameters and the third parameter is A TCL script that represents the process .
proc generates a new command, and we can Calls like a custom command, when the corresponding parameters are directly entered into the list (For details on default and variable parameters, see The following article is published in the Official Gazette of the European Union: :
proc add {x y} {expr $x+$y}
add 1 2 #上面过程的名字
3
6.1.2 Return value of the return
Generally, for interrupt processes, we use return values (i.e., the step at which we often enter results).return We can directly specify return values and exit.
- In the definition process, you can use the
returncommand Return the value you want anywhere . returnOrder The process of rapid disruption and The result of the process is its parameters. 。- Return value of process is Return value of the last execution order in the process 。
For example:
# 下面是一个定义绝对值过程的内容
# 其中过程体中的第二行,若if命令下无法实现,则该行无 return 的返回值,无法中断,这时他会跳到第三行运行 return 命令得到返回值,此时过程体最后执行的那条命令就是返回值
proc abs {x} {
if {$x >= 0} { return $x }
return [expr -$x]
}
6.1.3 Rename command
Changing the name of the process The method:
rename Tae Layer: Rename theTeacommand toLayerrename CHU2: DeleteCHU2command
6.2 Local variables and global variables
- For the in The variables defined in the process because they can only be accessed in the process , and When the process is out, it is automatically deleted. , it is called Local variables
- in The variables that are defined outside of all processes are what we call global variables. 。
- Note: In TCL, local variables and global variables can be named the same, and the intersection of the domains of the two is empty. : ((in tcl) The scope of local variables is it The internal processes involved ; The scope of global change is it Not including the internal processes (hence the two variables are named the same). This is a big difference from C!
If we want to see the, The process internally refers to a value of a global variable Can be used with the command global; it is important to note that The changes made internally also affect its value externally. :
set a 4
4
proc sample { x } {
global a
incr a
return [expr $a+$x]
}
sample 3
8
set a
5
The global variable a is accessed during the process.Changes to a in the process are directly reflected in the overall (Although the domain of the local variable is within the process in which it is located, if a global variable is referenced, the global variable is also a subset of the local variable at this point, so the change will be reflected globally).If the statement global a, TCL is removed, it will be wrong because it does not recognize the variable a (remember, we are usually all $ to refer to the variable).
6.3 Default parameters and variable number parameters
TCL also provides three special formats of parameters:
- It can be Defining a process without parameters , for example:
proc add {} {expr 2+3}
- can Definition of the process with default parameters We can. Provides default values for all or part of the process parameters , If the call process does not provide those parameters, the process automatically uses the default value assigned to the corresponding parameters. 。
- The function has a default parameter value in C\C++, and the function is a function with a default parameter value in C\C++. Parameters with default values can only be located at the back of the list of parameters, i.e.: all parameters after the first parameter with default values can only be parameters with default values 。
Example:
proc add {val1 {val2 2} {val3 3}} {
expr $val1+$val2+$val3
}
add 1
6
add 2 20
25
add 4 5 6
15
The above sentence describes the fact that a computer is executing code, and for the sake of The first is the death of a man who was born in the city of San Juan. Whether C++ or Tcl, the parameters are all plotted from left to right in order of number entries. , we will give some examples below to see why this rule would lead to ambiguity if it were not:
# 假设 Tcl 允许这种语法(实际上会直接报错或逻辑混乱):
# a 默认设置为 10,b 是变量必须填
proc test {{a 10} b} {
expr $a + $b
}
# 当你自以为a已经默认,于是调用时只传了一个数字赋予b:
test 20
wrong # args: should be "test ?a? b"
The error above is that the computer matches from left to right and it sees you passing the message. 20 It will not hesitate to take 20 The first parameter is a。 The result is that the b The program went down without a break. The computer cannot guess whether you want to cover 20 the default value a or pass it on to the required b..
To address this confusion, language designers have established a deadline: First, place the required parameters (parameters that do not have a default value) in front of the default parameters and then bring the missing parameters (parameters that do not have a default value) to the final page.
The correct spelling is as follows:
proc test {b {a 10}} {
expr $a+$b}
test 20
30 # 由于a值已经默认,这时候只有一个参数提交的时候赋予b变量,于是10+20
And the above can also be assigned simultaneously to a andb, i.e. order test 10 10(according to list,b assign 10,a assign 10)
- The process definition of TCL is Supports variable number parameters (i.e. a parameter fills in multiple values when assigned) ,If the process The last parameter is
args( args = arguments, generally translated in cs as the arguments of a stringed parameter or the actual arguments of a stringed parameter, i.e. the parameters that are transmitted in real time when a function is called ), then indicate that the process is supported Parameters of variable numbers 。- The parameters in the
argsIt's the same as before. are treated as ordinary parameters. - However, any additional parameters need to be treated in a special way in the processor.The local variables of the process
argswill be set to a list, with elements of all the additional variables. - If no additional variable is present,
argsit is set to an empty string The following is an example:
- The parameters in the
proc add { val1 args } {
set sum $val1
foreach i $args {
incr sum $i
}
return $sum
}
# 定义过程 add,sum 变量置换为 $val1,然后遍历可变参数 args,最后返回 sum 值变量。
add 2 # 应输出值为 2,因为只给了 val1 的值,而 args 则是空串
add 2 3 4 5 6 # 值为 20
Chapter 7: String operation
Since TCL treats all inputs as strings, TCL It provides a stronger string operation , TCL has commands related to string operations:string,format,regexp,regsubscan etc.
7.1 format command
The command is used for this purpose. Formatting output
- The wording:
format formatstring ?value value...? formatThe commands are similar to those in ANSIC.sprintfIn functions and MFCsCStringClass offeredFormatMember function:- The following is a list of the values of each
valuein the sequence:formatIn the format provided byformatstring, a new string is formed informatstringand returned.
For example:
set name john
John
set age 20
20
set msg [format "%s is %d years old" $name $age] # "%s is %d years old"为 formatstring,其他后面为变量
john is 20 years old # %s 对应 $name; %d 对应 $age
In the above example,format when the command is working, the It's like filling out a form with a blank sheet of paper with the bottom line. binary notation " " The contents of this form are the template. ; the variable behind the binary notation $name and $age is the data you are going to fill in the form in a relative order from left to right, and tcl detects the first band of the position indicator % (such as%s/%d), which will be the first variable after hard-bound binary notation.
tcl is not only necessary to know What do you want? , but also necessary to know How to display the matching format of assigned values (also called the row control) :
%sThe stringstring, string The text is pure , thus crawling to$namejohnis filled in directly as pure text%c–Character CodeRead the characters, code, and so on. Read only one character and it will instantly convert that character to the corresponding decimal integer (Unicode/ASCII code) returns the integer value of the corresponding single character. For example,Applein%cBack to the bottom.64The corresponding letter is the first capital letter.AThe ASCII code%d–decimalThe number of digits in the decimal place Fill in decimal digits with no small numbers%fThe number of floatsfloatand floats Fill in numbers with small dots can also be specified to fill in a few subsets, such as%0.2fretaining the second subsets.
In addition, the above%d and %f can also be Control of width and precision of small numbers (%s in fact, they can also control the width of the position), here are some examples:
%4d: The decimal integer and the integer-controlled cube-size widthd: still represents decimal integers.
4: represents the minimum total width of the field (Field Width) of 4 characters.
Its rule is: If your number is not four, the computer will automatically fill in the space on the left side of the number. , force it to be lowered to 4 bits wide, this is called Right alignment ). If the number is more than 4 bits, it will output at the actual length and not be cut off.
The small rule summarizes:
- In summary, for integers (decimal system), If the gap is not enough, it's a perfect match; if it's actually long enough, it's not cutting off, but all of the output. ; the same case applies to strings (e.g.,
%4s, when not enough is added together, It's not cutting it off, but it's all coming out. ) - If a forced cut is required, it is a small number of points added
.(e.g.%.4s) - In addition, the addition is The default is to fill in the space; if added
0(e.g.%04d) it is to fill in with0 - The default right alignment is generally, but if The Left wants to achieve alignment , it needs to be added
-(e.g.%-4s)
The following example is used to illustrate the effect of a real printed match, with [] to enclose:
ex.1:%4d
set a 5
set b 123
set c 56789
# 为了看清楚空格,我在两边加了中括号 []
puts [format "[%4d]" $a]
puts [format "[%4d]" $b]
puts [format "[%4d]" $c]
# 输出结果:
[ 5] # <- 左边补了 3 个空格
[ 123] # <- 左边补了 1 个空格
[56789] # <- 原样输出,不受 4 的最小总宽度限制,没有被截断
- In addition, If you want the minimum width of the space to be not enough, the left automatically fills in 0, instead of filling in the space, just adding a 0 to the front.
%04d) can be operated as follows:
ex.2: %04d
# 此法用于补齐总宽度时,不再使用默认的空格,而是使用数字 0
set id 7
puts [format "%04d" $id]
0007
# 这个方法对于我们整理文件需要 0001.txt 这样的格式时非常好用
%6.3f: simultaneously control the total width of the cylinder and the precision of the cylinder%f: represents the number of floating points..3(Small number accuracy): The third digit is required to be reserved after the small number. 0 is not enough for 3 to add up to 4 to 5 more than 3 。6( Minimum total width ): The whole number represents the whole number, and contains the small numbers themselves and the numbers behind the small numbers! (b) At least 6 characters in width 。 If not enough, fill the gap on the left. 。
ex.3: %6.3f
set pi 3.14
set e 2.71828
puts [format "[%6.3f]" $pi]
puts [format "[%6.3f]" $e]
# 输出结果拆解:
[ 3.140] # <- 解析:首先变成 3.140(保留3位)。此时共有 5 个字符(3、.、1、4、0)。因为要求总宽是 6,所以左边补 1 个空格。
[ 2.718] # <- 解析:首先四舍五入变成 2.718。此时正好是 5 个字符。总宽要求 6,所以左边补 1 个空格。
In addition, if the above When filling in the total width, no longer use the default space, but use the number 0 I agree. ex.2 It's a very simple way to write. %06.3f。
Ex.4: %4s with %-4s and %.4s
# Tcl 格式化字符串 (%s) 精简排版测试
set atom "O"
set long_atom "Calcium"
# 下面需要两个括号,一个括号是文本,因此需要反斜杠避免转义,一个括号则是因为要执行命令置换
puts "1. 对齐测试 (设定宽度为4):"
# 左对齐 (加负号)
puts "左对齐 (%-4s) : \[[format "%-4s" $atom]\]"
# 右对齐 (默认不加负号)
puts "右对齐 (%4s) : \[[format "%4s" $atom]\]"
puts "\n2. 长度超限测试 (字长为7,设宽为4):"
# 自动撑破宽度限制,完整保留所有字符
puts "超限完整保留 (%-4s): \[[format "%-4s" $long_atom]\]"
puts "\n3. 强制截断测试:"
# 限制最大长度 (使用小数点)
puts "最大长度截断 (%.4s) : \[[format "%.4s" $long_atom]\]"
# 占6个字符宽度,右对齐,且只截取前4个字符
puts "占6位且截断 (%6.4s) : \[[format "%6.4s" $long_atom]\]"
# 输出结果:
1. 对齐测试 (设定宽度为4):
左对齐 (%-4s) : [O ]
右对齐 (%4s) : [ O]
2. 长度超限测试 (字长为7,设宽为4):
超限完整保留 (%-4s): [Calcium]
3. 强制截断测试:
最大长度截断 (%.4s) : [Calc]
占6位且截断 (%6.4s) : [ Calc]
ex.5: %.4f and %.4s
%.4fThe number of digits is shown as a four digit number after the small number. If the original number is not precise, it is filled with 0, and if it is exceeded, it is replaced.%.4sThe string is intersected by four bits from left to right, and the gap is filled in if it is not enough.
7.2 Scan command
scan The command can be thought of as format The opposite of the command The system is similar to ANSIC. sscanf The function.
- The wording:
scan string format varName ?varName ...? scanThe string is analyzedstringby the format providedformatand thenSave the result to a variablevarName(if the variablevarNamedoes not exist, TCL will automatically declare the variable)scanThe return value of the command is the number of matched variables- Note that except for the keys
spaceandTAB,The characters and%instringandformatmust match the format the meaning of specific format matching parameters, see Section 7.1 ) ⋅
The following is an example:
# 例1中,"some 26 34"为 string,"some %d %d"为 format
# string 根据 format 检查匹配格式要求,并分别把结果存入a和b
# 最后返回其匹配的变量个数为2
scan "some 26 34" "some %d %d" a b
2
set a # 检验其赋值是否成功,下同
26
set b
34
# 例2则是将 scan 和 format 结合的范例
scan "12.34.56.78" "%d.%d.%d.%d" c d e f
4
puts [format "the value of c is %d,d is %d,e is %d ,f is %d" $c $d $e $f]
the value of c is 12,d is 34,e is 56 ,f is 78
Chapter 8: Access to files
TCL provides a wealth of document operation commands. These commands allow you to operate the file name (see "File Matching Mode") in order or at random to read and write files, and retrieve system-reserved file information (such as last time of access).
The following is a list of the most common types of cancer:
- Note that:It uses
/(rectangular) rather than\(reverse-slip) when representing the directory structure of a file, which is related to TCL originally implemented under UNIX., Unix often uses the right-angled syllable/(e.g./home) to indicate a directory structure, i.e. path. - If it is in win, it should be written as
C:/tcl/sample.tcl(with the right slope)/The first is the "Signal" or "Signal".\The two reverse slopes are used.\\The following is the text:C:\\tcl\\scripts。(Normally, the c-disk path under windows should be represented as a single reversal of slopeC:\tcl\scripts, but not here!) - In tcl, you can use commands in the operating system directly, such as
lspwd, ((current workplace directory) orcdetc., but in customizedprocyou cannot use them directly and call using theexeccommand.
8.1 Basic file input and output commands
The following is a process called tgrep to create a version of tcl grep, so that Explain the basic features of TCL I/O :
proc tgrep {pattern filename} {
set f [open $filename r]
while {[gets $f line]} {
if {[regexp $pattern $line]} {
puts stdout $line
}
}
close $f
}
- In fact, There's a bug in the code above. : in tcl,
gets $f lineReturns the number of characters it successfully reads for example, reading text with 10 letters per line returns10becausewhileCentral Africa is true and so it continues to circulate.If you read a blank line (with no characters, only a return) it returns0, ending the while loop. If there is content left behind, then the content left behind is missing! - If you want to stop reading the empty line of a car back, you want to read it at the end of the document. The can be added to
[gets $f line] >= 0And the reason for this is that Because the EOF at the end of the file is read,getsit returns-1values, endingwhilethe loop.。
The code can therefore be converted to a version that is more in line with the grep (((filed from start to finish) definition tgrep:
proc tgrep {pattern filename} {
set f [open $filename r]
while {[gets $f line] >= 0} {
if {[regexp $pattern $line]} {
puts stdout $line
}
}
close $f
}
proc tgrep {pattern filename} {: Defining a process calledtgreprequires input of two parameters: you The following is a list of the file names and their names. .set f [open $filename r]: Open this file with Read only the pattern (r) , The system will send a file with the code name "Crypt" and wePut it in a variable$f.while {[gets $f line] >= 0} {:Read the contents of a file in a row, with a variable temporarily present in a single line of text each time it is readlineand in the discretion of this loop, not only is the line of text storedline,The number of characters in this row is also returned towhilebut if the number of characters >=0 ((includes a blank line of return), it will still be read and not interrupted until the end of the file is read (EOF at the end of each file returns to value-1and thus stopswhileloop).if {[regexp $pattern $line]} {:Check with the normal expression (regexp) in this line$line(The next step is to store the text inside the line in the line.) Is there any feature that contains what we are looking for$pattern?puts stdout $line: If included, add this row to The standard output of the screen is printed in the original closed position.close $fThe first step is to make the decision. The paperwork is complete and the craftsman's license number must be registered.$fThe ban was lifted.closeClose the files and release the memory! !
The above process is very similar to the UNIX commands grep and can be called with two parameters, one is pattern 模式, the other is filename,The line defined tgrep will print all lines in the file that match the pattern..
p.s.: Order grep = Global Regular Expression Print( The overall normal expression is printed ),global 全局 The first line of the document is searched from the first to the last line, rather than just finding one. regular expression 正则表达式 The type of filter or pattern filter you are looking for; print 打印 The corresponding line is then printed out on the screen.
The following are the key points we will be introducing here:[open $filename r]
8.1.1 Indicates the status of access to the file
Before we begin to introduce the input and output of a file, we need to know: What are the ways to open documents?
- The way the file is opened is similar to the C language we are familiar with, and it has the following features:
Table 8.1.1: The representation of the file access status (how)
| The short form | Explanation and requirements |
|---|---|
| r | Just read. The way is open. The documents must already exist. this is default mode 。 |
| r+ | The read-write format is open, the document must already exist. |
| w | Just write. The way you enter and open the file, If the file exists, empty the contents of the file, or create a new empty file. |
| w+ | Read-write to open a file, and if the file exists, empty the contents of the file, or create a new empty file. |
| a | Just write. The way to open a file, the file must exist, And pointing the pointer to the end of the file 。 |
| a+ | Read the file and open it and point the pointer to the end of the file. If the document does not exist, create a new empty file. |
8.1.2 Preparation knowledge of I/O (input/output)
The process of operating a file in Tcl can be imagined as The carrier is hired to deliver the goods .
- The core concept: What is file ID file?
In Tcl, you cannot directly yell at a file name (e.g. data.txt) to get it to deliver data.The first command to file a certificate is to use open to make a certificate.open Returns an exclusive passcode number (usually file1file2), which is fileId. All subsequent read-write actions only recognize this passcode (i.e. fileID). For example:set f [open $filename r] We've all used $f to represent the identity of its file.
Tcl also carefully prepared three sets of permanent free passes in advance for you:
stdin: Standard input (usually your keyboard)
Stdout: Standard output (usually your screen)
stderr: Error channel (a channel specifically used to display red flag information on screen)
- The command to read the file:
gets↓ Move by line) vs.read↓ Package move)
With the above-mentioned pass from the open command $f ((document ID), we can start to get data from the file. Tcl offers two modes of transport:
gets(According to the readings): This is a Most commonly used commands for processing biometric data or log files . It reads only one line each time, and automatically helps you throw the back of the line.- The method is:
gets $f myLine. It will bePut a line of words you read into a variablemyLineand calculate that line with several characters, returning the number of characters as a result to you. If you read the last EOF, it returns -1.. .
- The method is:
read(full disc packaging): If you can read a line at a time, you want to fill the entire file in memory once and for all.- The method is:
set allData [read $f]. This directly reads all the remaining words. You can also add a number (numBytes), formatting asread $f numBytes, e.g.,read $f 100, explicitly requiring only the next 100 bytes to be read.
- The method is:
- Writing documents and buffers:
putsandflushandclose
This is a very common question: why do I write data using
putsand open the file and find it empty?
The essence of Buffer:
Because the read-write speed of a computer's hard drive is much slower than the CPU. If Tcl only writes one letter at a time and starts the hard drive, the hard drive interacts too many times. So, what is this? The C language base gives puts a buffer zone that looks like a shopping cart cab. When you execute puts $f "Hello""Hello" the buffer zone is actually thrown into memory and not actually written into the hard drive file.
If you want to make data Immediately The document is used in the flush:
flush $f The order is like a settlement order. it It will put all the data in the buffer zone into the real files on the hard drive. 。If you do not call manually flush, the data will only be saved automatically when the buffer is full, or when you execute the last close command.
Therefore, when the file is completed, the file identifier $f must be deleted,close Closing files, releasing memory!
8.1.3 Basic file input and output commands (written version)
- The wording:
open name ?access? - The name of the file opening method
accessnameand the specificaccessfile opening method can be referenced Section 8.1.1 Subsection . - The order will be Return the file identifier used for other commands
getsclose, etc.。 - If the first character of
nameis|, the pipeline command is triggered, rather than opened. openOrder Returns a string to identify the file that is opened 。 When you call other commands, such as:gets,puts,closeThe following is a list of the most commonly used file identifiers in the United States.- TCL has three specific Document identification :
stdin,stdoutandstderr, respectively Standard input , Standard output and The wrong way , and you can use these three file identifiers at any time.
The following will be presented respectively gets \ read \ puts \ flush \ close:
gets fileId ?varName?Read the next line of the identifier filefileIdand ignore the barcode。If the command is invarName, assign the string to it and return the number of characters in the string (the EOF at the end returns-1) If not,varNameThe next line of the return file is the result of the command (if it reaches the end of the file, return the blank string).
readThe order andgetsSimilarly, butreadNot in line units It has two forms:read ?-nonewline? fileId: Read and return all remaining bytes in the identifier filefileId. If there is nononewlineswitch, the alternating note stops.。read fileId numBytes: Read and return the nextnumbytesbyte in the identifier filefileId。
puts ?-nonewline? ?fileId? string: WritestringtofileIdand add a linear inverter if there is nononewlineswitch.fileIdThe default isstdout。 The command to return the value to an empty string.- Generally speaking,
putsthe default is standard output (stdout), which is printed directly. putsThis means that the buffer zone program of a standard I/O library is used to command C. Information generated by usingputsdoes not appear immediately in the target file。
- If you want to get the data right away in a file, you call it.
flushThe command:flush fileId: Write the contents of the buffer zone in a document with an identifierfileId, return the command value to the empty stringflush: Forcing the buffer zone data to be written into a file 。flushThe data is not returned until it is written. Buffer zone data is automatically generated when the file is closed.flush。
close ?fileId?: Closes a file that is identified asfileId, usually automaticallyflush, and commands to return the value to an empty string.
It is particularly noteworthy that the operation of the TCP socket, piping, and string are similar to those of the file, and the above commands apply to the file as well.
The following is an example:
# 1. 办证,搞文件标识(打开文件)
# 以只读 (r) 方式打开源文件,通行证存为 f_in
set f_in [open "source.txt" r]
# 以写入 (w) 方式打开目标文件,通行证存为 f_out
set f_out [open "target.txt" w]
# 2. 搬运(循环读写)
# 用 gets 一行行地读,只要返回值大于等于 0,说明还没到文件尾
while {[gets $f_in line] >= 0} {
# 把读到的这一行,放进 f_out 的缓冲区里
puts $f_out $line
}
# 3. 销户(关闭文件并自动 flush)
# 注销通行证,此时 f_out 缓冲区里的数据会自动写进目标硬盘!
close $f_in
close $f_out
puts "复制完成!" # 这里没写 fileId,所以默认发给了 stdout(屏幕)
8.2 Document handling and access to document information
Chapter 9: Deep exploration
9.1 Tracking of variables, recall functions trance
TCL provides trace Command to track one or more variables. If already To set up a tracking for a variable, a corresponding Tcl command is activated no matter when the variable is read, written, or deleted. , tracking can have many uses:
- Monitoring The use of variables (e.g., printing each operation that is read or written)
- Transmitting the change of variables to other parts of the system (For example, in a TK program, the current value of a variable is always displayed on a small icon.)
- Limitations Some operations on a variable (e.g. any behavior that attempts to change the value of a variable with non-decimal numbers) cause an error or Recharging some operations (e.g. every time a variable is removed, it is recreated).
- The macroscopic syntax:
trace option ?arg arg ...?trace: Main commandoption(Options/Subcommand): Tell the Commander-in-Chief what you're going to do Specific tasks 。 For example, you want to The following is a list of the most commonly used methods for calculating the value of a currency. 、 The video is a great example of this. Or... or The first is the "Vinfo" ??arg arg ...?: Indicate Additional parameters unknown . Complete several parameters, depending on which option you have selected.
The options are in the following forms: monitor variables, delete variable tracking, return tracking information to the variable.
9.1.1 Monitoring of variables
When option is replaced by variable by Monitoring of variables
- The wording:
trace variable name ops commandor the modern grammar supported after version 8.4 of tcl (the meaning would be clearer)trace add variable name ops command: The order should be divided into three parts:trace variable / name / ops / commandThis command sets the variablenameThe following is a list of the most common types of cancer: Each time a variablenameis madeopsthe commandcommandis executed.nameIt can be A simple variable or it can be Elements of an array (e.g.,person(name)) or the entire array (e.g.,person)。- Among them,
opsThe following are the most common types of Operations The following are the most commonly used methods of measuring the amount of energy in a given volume.r(Read): It is triggered as soon as someone reads its valuecommand.w(Write): It is triggered whenever someone changes/writes its value.commandu(Unset): It triggers when someone deletes this variable.command。 By usingunsetThe commands are Clearly deleted A variable, A process call ends by implicitly removing all local variables 。 The variable is also deleted when the interpreter is removed, but tracking is no longer working.- They can be put together, such as
rwtriggering when they are readily written to represent the readability of the text
commandIn general, it is to execute what is written in advance.procBut again, Section 6.1.1 There are some differences.- When tracking a variable is triggered, the TCL interpreter automatically adds three parameters to the list of parameters in the command
command. So, what?commandThe actual change is:command name1 name2 opThese three are The implicit transmission of the real 。 The following is a detailed explanation.
- Among them,
- In addition, If a variable has multiple tracking information the tracking is triggered. The principle of precedent is that the most recent tracking is triggered first, and if a tracking error occurs, the subsequent tracking will not be triggered.
Why do you need to add these three parameters automatically?
Suppose you write a very general alert process called security_alarmcommand and then you use trace The alarm is installed on 10 different variables at the same time. (e.g. $水温, $气压, $电压 and so on).
If the alarm is triggered security_alarm, Without these three additional parameters, your program will be in an awkward situation: it only knows what's going on, but it doesn't know who's doing it or what's going on. 。
To solve this information-blind zone problem, Tcl interpreters are very careful when the alarm is sounded. The police force forced three stamps on the scene to show small paper stamps. The three notes are that Three automatically added parameters .
Explanation command name1 name2 op:
This is actually a requirement that when the variable is operated, The system automatically passes the name of the variable, the name of the array element, and the type of operation to this process, called a context-transmitter in the loop in the callback mechanism. 。
name1 name2The use of: Indicating the variables being manipulated- If the variable is a Simple variables , then
name1gives the variable its name, whilename2is an empty string; - If the variable is a An element of an array , then
name1gives the name of the array, andname2gives Name of the element - If the variable is The whole group , then
name1gives the name of the array andname2is an empty string
- If the variable is a Simple variables , then
- When writing
procthe process receives a list, it is possible to fill in the received variable names, the array element names and the type of operation,proc define_name {varName indexName operation}all three being formulas and taking any name. The real meaningful name depends on how the commands intraceare written.
Since Tcl will force three parameters behind your command, the biggest crater many beginners step on is: Forget to write these 3 receiving parameters when defining proc, so don't forget to write these three parameters into the receiving list!
Ex. 9.1_1: Misrepresentation
Common problem 1: If you do not write three form parameters in
proctrace variable age w my_alarm, if you only writeproc my_alarm {} { puts "出事了" }at the definitionproc, whentraceis triggered, Tcl actually tries to executemy_alarm age "" w, so it will immediately throw out red letters:wrong # args: should be "my_alarm"((parameter number error)! Because When the three variables are not written, these parameters are still defaulted to the process name behind, causing args of the number of parameters to be problematic. , correct spelling should beproc my_alarm {name1 name2 op}((what name does not matter as long as there are three pitches running))Common Question 2: Written
""or空格in the list ofprocactually,proc proc_name {varName index operation}these three words It's not a fixed format at all. , which are just Programmers around the world have been calling a commonly-used term "Frazo". to make the code easy to understand), can be written entirelyname1 name2 op, but the more recommended writing is concise.varName index op
It is important to note that the Proc is defined here as the reserved space (s) , The trace and set are the actual data that corresponds to the external trace. 。
Let's say we have a simple variable to define now:
proc print_alarm {my_money " " w} {
puts "🚨 警告:监控到变量 '$my_money' 刚刚发生了 '$w' (写入) 操作!"
}
# 直接报错:
argument with no name
# 因为第二个形参是空格,没有名字,因此报错。此外,也没必要将三个行参取成和实参意义的名字。
So we are I just need to be proc The brackets are arranged in three empty boxes with a common name (positioning symbol). When trace is triggered, the Tcl interpreter will automatically take the truth like a courier. my_money、"" and w And then, the three data are in the order of their being put into these three boxes that you're ready for!
Ex. 9.1_2: Examples of anti-fouling fouling monitoring
# 第一步:写好“报警动作” (当变量被操作时,系统会自动把变量名、数组元素名、操作类型回调,传给这个过程)
proc print_alarm {varName index op} {
puts "🚨 警告:监控到变量 '$varName' 刚刚发生了 '$op' (写入) 操作!"
}
# 第二步:定义我们要监控的变量
set my_money 1000
# 第三步:安装监控摄像头 (盯住 my_money,只要发生 w 写入操作,就呼叫 print_alarm)
trace variable my_money w print_alarm
# 第四步:测试触发监控!
puts "准备修改变量..."
set my_money 500 ;# 这一步会瞬间触发监控过程!
#于是返回:
🚨 警告:监控到变量 'my_money' 刚刚发生了 'w' (写入) 操作
# 如果还想进一步考虑元素是否在某个数组里,让打印内容更具体,则可以写成:
proc print_alarm {varName index op} {
# 直接检查 index 是不是空字符串
if {$index == ""} {
puts "🚨 警告:简单变量 '$varName' 发生了 '$op' 操作!"
} else {
puts "🚨 警告:数组 '$varName' 中的 '$index' 元素发生了 '$op' 操作!"
}
}
set my_money 1000
trace variable my_money w print_alarm
# 检查是否正确监控:
set my_money 50
🚨 警告:简单变量 'my_money' 发生了 'w' 操作!
Ex. 9.1_3: Introduction upvar: Tracking and scope of variables
Before we understand this example, let's look back. What are local variables and global variables Section 6.2 。
The following section of the code uses Tcl's The following is a list of the most commonly used methods for tracking variables: and Scope Aliasing technology is a new technology that has been developed to help people with a range of problems. to achieve a common The following is a list of the most commonly used methods for the treatment of cancer: process that unifies the capture and processing of The scale (scalar) and array elements (array element) write operations events and dynamically reads the most recent value of the modified values.
trace variable color w pvar
trace variable a(length) w pvar
proc pvar {name element op} {
if {$element !=""} {
set name ${name}($element)
}
upvar $name x
puts "Variable $name set to $x"
}
# 验证
set color green
Variable color set to green
green
We have broken it down into several parts to explain:
- Registered tracker (Trace Registration):
trace variable color w pvar
trace variable a(length) w pvar
The two lines of code Two tracking events were registered at the national interpreter level are used when a specified variable ((metricalcolor or array elementa(length)) is written in the operation ((w)),The interpreter will automatically hang up the current execution stream and call the process as pvar ((Procedure))
- Signature of the re-call process (Callback Signature)
proc pvar {name element op} {
According to Tcl trace The basic rules of the mechanism, The interpreter automatically passes the three real parameters in a process called back-and-forth. 。 So, what is the point of this? The process definition must explicitly state these three parameters The following is a list of the most commonly used methods for calculating the number of days in a calendar year.
nameThe name of the base variable is:element: Key/Index of the array: Array Key/Index. If it is a metric, this value is the empty string string "A".op: The specific operation symbol that triggers the current feedback (here is always w)
- Dynamic name reconfiguration (Dynamic Name Resolution)
if {$element != ""} {
set name ${name}($element)
}
This block of code is achieved by Multimodal compatibility treatment of scales and arrays . . . by The logic of the empty checking $element != represents not equal) to distinguish the current triggered variable type.
- If the array elements are passed through
elementThe first is the use of a vacuum element. String insertion String Interpolation re-spells the array name and array elements asaandlengthThe following is the text:a(length)),and overwrite local variablesname。 - The purpose of this step is to In the local domain, a complete string string handle can be generated that uniquely identifies the target variable ,To use the following commands
upvar。
Thus, if the trigger is a(length), then $name is a,$element is length; and after spelling, the value of the local variable name becomes complete a(length). If the trigger is color simple variable),element is empty, this paragraph if will not be executed,name and remains color.
upvar: Cross-domain reference binding (Cross-Scope Reference Binding)
upvar $name x
This is the core mechanism of the feedback process. In Tcl, Processes have independent local variables (Local Scope/Stack Frame)。The feedback process receives only the variable name (i.e. proc the three parameters of the receipt) (String strings) The memory address or actual value of the variable is not the one that the variable is pointing to 。
Why not print it directly and make a joke?
upvarWhat is this?
- Because of the isolation of the scope: when Tcl is executed in
pvarIt's like a small room that is completely closed. In this room, it's I'm just saying, we know what the name of the variable is. (Should be kept$nameI'm not sure.color)。 But it doesn't get what data exactly is in that variable. (For example, it doesn't know the variablescolorIt was transformed intoredOrblue),Because the realcolorvariable remains outside the room (in the global scope or other process)。 - Upvar's role is to open a wormhole hole, Cross-domain reference binding :
upvar $name xwhich means telling Tcl: The worm helped me cross the wall of this room,Go outside and find the real variable of that name called$nameand then into this little room. And I'm going to give it a name.xThe following is a list of the countries of the world by population. From this point on, operating local variablesxis equivalent to the actual variable that directly reads or modifies the external global or other processes!
So, what is the point of this? upvar The command is used to execute call-by-reference The simulation.
upvar $name x The Tcl interpreter is directed: In the domain where the caller is located, find the variable named $name in the default upper layer of the call string, i.e. level 1. The Commission is also working on the proposal to extend the scope of the Created a pseudonym called x (Alias/Reference) (Any other name can be used, but it's also a good one.) proc The display declaration received in the same way as the linear parameter, followed by the external variable color For other values, then. x Due to the name It is bound so that it can be mapped color The real parameters are external.
After that, Any read-write operations for local names x are mapped directly to external target variables at memory level(color or a(length) I'm going to go.
- Standard I/O output
puts "Variable $name set to $x"
}
At this point, $name Stores the complete variable name string after formatting, andBy deleting local aliases $x, the code successfully reads the latest memory values of external variables after "write" operations occur.. Eventually, the output is passed through puts to the standard output stream (stdout).
- Verification phase
set color green
Variable color set to green
green
upvar $name x After a reference passes the default layer of the call string, the internal variable is x With the outside color The map is actually mapped to the data, and it's connected so the actual result is upvar $name x -> upvar color x -> upvar color green
Ex. 9.1_4: Access to the tracked variable in the same process
The above is due to the The only variable names that the feedback process receives are (i.e. proc The three parameters received (string handle) The memory address or actual value of the variable is not the one that the variable is pointing to 。 If it trance The proc In the same process, they are in the same range of a local variable, and then they are in the same range of a local variable. Direct calls are made without the need upvar to cross-scale reference passing binding。
command The following is the code that triggers the tracking operation: If access to the tracked variable is in a process, command it is possible to access the local variable of that process.:
proc Hello { } {
set a 2
trace variable b w { puts $a ;list } # 这里 $a 可以直接访问过程的局部变量(上一行),而无需使用 upvar
set b 3
}
f
# 验证输出顺序,运行 set b 3 之后,跟踪到变量改变,于是先执行 {puts $a ;list},再返回 b 的值 3
% Hello
2
3
For read-write operations of tracked variables,command it is After the variable is read and before returning the value of the variable performed. So, this is the first example I've read. set b 3 The first is the printing of the code, which triggers the echo function and prints it as a priority. $a。
Ex. 9.1_5: Tracking mechanism temporarily fails when executing commands
Since command is executed after the variable is read and before returning the value of the variable. Therefore, weThe value of the variable can be changed at command to make the new value a read-write return value, and becauseTracking mechanisms temporarily fail when executed command, soReading and writing of the variable in command does not result in command being recycled activated (i.e. does not continue to trigger because command rewrites the variable trance)
trace variable b r tmp
proc tmp {var1 var2 var3} {
upvar $var1 t
incr t 1
}
set b 2
2
# puts 是读(r)操作,先触发了 incr t 1,由于 upvar 跨作用域,从而使 b 变成 3,再返回 b 的值 3
puts $b
3
puts $b
4
Ex. 9.1_6: A data type constraint (Type Enforcement) mechanism
if Failure to track read-write operations I mean, Command failed So, what? The read-write operations that are tracked will also fail and return and command The same message of failure. Use this mechanism Can only read variables 。
The following code implements a The data type enforcement mechanism is strictly data type restrictions. , usedForced assurance variables size can only be assigned non-negative integers (i.e., values can only be given to positive integers):
trace variable size w forceInt
proc forceInt {name element op} {
upvar $name x
if ![regexp {^[0-9]*$} $x] {
error "value must b a postive integer"
}
}
The first thing to consider is:
[]Order to switch The following is the list of the countries of the European Union:regexpRegular expression is a common knowledge of regular expression Part 3 of Section 4.9 。
- Question about code writing:
[regexp {^[0-9]*$} $x]Can it be written as{regexp {^[0-9]*$} $x}or{regexp [^[0-9]*$] $x}or[regexp [^[0-9]*$] $x]?
The answer is It doesn't work. ! to understand the relationship between a normal expression and a tcl interpreter. The middle bracket [ ] means: ∈ Execute orders and ask for results ∈, that is, the order substitution we have previously understood.
The outermost layer
[regexp ...]is written to the Tcl interpreter.It means: please help me execute this command
regexpand give me the matching result ((successfully returns 1, failure returns 0) so I can judge the if afterwards.If you change
{regexp ...}((your first and second modification), Tcl will treat it as a string of pure text strings, not to perform matching actions. If the sentence is directly wrong, it will be wrong.
- However, you may be confused:
[regexp {^[0-9]*$} $x]It's obviouslyprocIt's a big one, but it's not.{}Why don't all the commands in it be converted into plain text strings? Why is normal expression necessary?{}The packaging?
- The outermost large brackets only protect the definition stage of the string and The inner brackets are responsible for protecting the execution phase of the pump 。 Thus, the Tcl interpreter sees the largest outer brackets and considers them to be a
procThe process. The outermost layer of this big bracket means Let tcl interpreter do the code in a hurry and pack it in its original container. And put in his name.forceIntIn the variables. So, what? When the definition phase is passed into the execution phase,{}restrictions on the execution level expressed by the protection rule take effect.。 - Tcl interpreter takes out the largest brackets on the outside of the code each time it runs. 。
{^[0-9]*$}This big bracket is The word "expression" is used to protect the normal expression inside. 。 Why do we need protection? And that's because in normal expressions,[]The word "symbol" is used to represent the set of characters.$The end of the world is a long way off. But in Tcl, it's not the same as in the other languages.[]The command to replace the pump is executed by the pump.$The name of the game is "Variable Reading". Therefore, there are certain syntactical contradictions between regular expressions and tcl interpreters that need to be used.{}The first is to protect it and make it successful.regexpThe command to correctly identify the analysis, rather than tcl interpreter to solve it. And it's not right here.""The two quotes are because$The first is that the language is not a language. If you don't{}It's written[regexp [^[0-9]*$] $x]The third is that Tcl will be smart enough to make it a first.^[0-9]*$When a Tcl command is executed, the resulting system cannot find a single command.^The order to crash is a direct return!
In the Tcl, we have a lot of people who are not in the same situation. The big braces are like a shield for consumer goods. 。 Every time the code is executed, the outermost layer of protective cover is used up. 。
`proc` 后面的大括号,在调用函数时被消耗了。
`if` 后面的大括号,在判断条件时被消耗了。
正则表达式上的大括号,是为了确保这串包含各种特殊符号([ ], $, *)的“火星文”,在真正递交给正则引擎之前,绝对不会被 Tcl 解释器误碰!
The process is very simple with the above knowledge:
race variable size w forceInt
proc forceInt {name element op} {
upvar $name x
We are well aware of the preliminary basic mechanism of registrationtrace variablename, element, op showing the signature reception of the transmitted, and upvar cross-sphere reference binding) regexp and the rule of expression for the value (Regex Evaluation):
if ![regexp {^[0-9]*$} $x] {
The regexp command is used to model matching of the local reference variable $x (the latest written value for external size).
^ 表示字符串的起始边界。
[0-9]* 表示允许出现 0 个或多个 0 到 9 的连续数字。(*代表前面这字符允许出现0次或无数次)
$ 表示字符串的结束边界。
前面的 ! 为逻辑非操作符。整体逻辑为:如果写入的值不是由纯数字构成的字符串,则条件判定为真(True)。出发 if 后面的 body
error "value must b a postive integer"
When the above normal matching fails (i.e. output true), it is triggered directly Tcl's error command。 This is it. The current execution stream is immediately suspended, generates a standard error throw and sends the default error message prompt to the console. 。 At this point, Illegal assignment operations will be considered a fatal error that causes program crashes, effectively preventing subsequent computing processes from contaminating dirty data.
9.1.2 Revocation of monitoring variables (VDDlete) and tracking information for querying returning variables (vinfo)
When option is replaced by vdelete by Removal of surveillance
- The wording:
trace vdelete name ops command- Remove the tracking of operations on the variable
nameops. Returns a value as an empty string. - For example: To stop tracking
trace variable color w notice, run:trace vdelete color w notice
- Remove the tracking of operations on the variable
When option is replaced by vinfo by The query variable
- The wording:
trace vinfo name- This is the order. Returning tracking information for variables 。The return value is a
list,listEach element of a string is a substring, Each substring consists of two elements: tracking operations and commands associated with operations 。 If the variablenameThe following is a list of characters that first appeared in the serial in 2012, by order of first appearance.
- This is the order. Returning tracking information for variables 。The return value is a
Additional knowledge: Fragmented tcl
- Judging the existence of variables :
info exist xxxThe existence is then output to1, otherwise it is0 sleep xSleep x seconds It takes integers ), Suspended script execution duringexecThe command line: Run commands or third-party programs in shell in tcl 。 In tcl, commands can be used directly in the operating system, such asls、pwd(current job list) orcdI'm not sure.procThe media cannot be used directly, it needs to be usedexecOrder to call.
upvar、global、exec What is the difference between these two commands?
The three commands can be divided into two main camps to understand:
- The scope of variables (
globalandupvarThey are all used to solve Tcl. The process of solving proc is not able to read the external variables directly inside the solvent This is a tool for isolation restrictions. Both of them. Always floating inside the Tcl interpreter, they only handle variable punctuation in memory 。- Global is an absolute positioning scale used for the purpose of the global scale. Connecting global variables
- Upvar is a relatively/absolutely positioned variable, which can be Connecting variables at any level (It is the core of making the reference passing the pump).
- System calls (
execIt is Tcl has nothing to do with internal variables 。 It's the It is used to directly command the underlying operating system (such as Linux/Windows) to execute external programs beyond the Tcl language itself. 。 will Fork derivative is a subprocess for running system commands 。 If you'reexecPath problems are often caused by environmental variables in the OS (such as PATH) that do not match the paths within Tcl.
globalOpening of the National and Local Corridor Design thinking: In Tcl, the design process is a process of creating a new image.procThe interior is a closed local domain, not interconnected with the global domain. If the entire script shared in the process is to modify the universal variable hash, it must be usedglobalOrdered a statement.
# 1. 在全局作用域定义一个变量
set system_status "Offline"
proc start_system {} {
# 2. 声明我们要使用的是外面的那个全局变量
global system_status
# 3. 此时修改它,外面的真实变量也会跟着改变
set system_status "Online"
puts "内部提示:系统正在启动..."
}
# 检验结果是否合理
start_system
puts "外部检查:当前系统状态为 $system_status"
# 输出结果将是:
外部检查:当前系统状态为 Online
In addition, global varName It's actually equal to upvar #0 varName varName。 It's always pointing to the dead. The top-level scope of the interpreter is:Level #0)。
upvarThe following are the types of worms that can be transmitted across a range: Design thinking: as we have done beforetraceThe following examples are discussed: ex.9.1_3),upvarNot only is it able to access the global variable, but it is even more powerful because it can access the local variable that calls the clock at the top. This allows us to pass the variable name string to the function and then pass it through theupvarI'm not sure what the real quote is.
proc add_ten {varName} {
# 将外部传进来的变量名与局部的别名 x 绑定
# 默认是向上跳一层 (level 1)
upvar 1 $varName x
# 对 x 的任何修改,都是对外部真实变量的修改
set x [expr {$x + 10}]
}
proc calculate {} {
set my_score 50
# 我们把变量的名字 "my_score" 传进去,而不是传 50
add_ten my_score
puts "我的分数变成了:$my_score"
# 输出结果将是 60
}
calculate
Grammar is upvar ?level? otherVar myVar . It is an essential tool for writing advanced, general-purpose Tcl processes (such as custom data structures or monitors). If level not specified, call up a layer of call string by default.
execRemote controls for the operating system Design thinking: When Tcl itself is not enough -- like you want to copy a file, see the system process, or call a Python script -- you can use it to create a new script. Shell commands can be executed directly at the operating system level usingexeccommands。
# 假设我们想调用 Linux 系统的 ls 命令列出当前目录下的文件
proc list_files {} {
# 捕获执行外部系统命令的输出结果
# 这里的 ls -l 并不是 Tcl 命令,而是操作系统的原生命令
set result [exec ls -l]
puts "当前目录下的文件有:"
puts $result
}
list_files
The syntax is exec ?switches? arg ?arg ...?. It is important to note that,exec The Tcl script will also drop the error by default and suspend the call if the program is faulty. .
The following summary:
Tcl core commands: upvar, global and exec
| Order | Key functions | Objects of Action | Typical use scenarios |
|---|---|---|---|
global | Introducing global variables | Variable within Tcl The global scope | Internally read and write the general state or configuration information shared by all functions in proc |
upvar | Create a variable citation | Variable within Tcl Any level | Implementing a reference-pass filter allows the process to directly manipulate variables in the caller's environment. |
exec | Execute system external commands | External procedures in Operating system | Call the OS original life commands (such as ls, cp) or run scripts written in other languages (such as .sh, .py). |
- Continuation: The end of a line, if any
\, indicates that the next line reaches the end of this line (this is mentioned in The following article is intended to help you: ). - The line can be used as an indentation
tab - Deleting a file that starts with
orb.cubin the current directory can be done as follows:file delete {*}[glob orb*.cub] - In addition to reading from a file, tcl can also read from information entered by the user. For example,
set a [gets stdin]prompting the user to enter standard input data, assigning values to variables,athis way of requiring the user to provide input is also known as interactive scripting. - Tk is a toolkit for creating graphical interface programs The first is to build a desktop, network, database, and so on. The Commonly used in conjunction with tcl, known as Tcl/Tk (For example, VMD is the Tcl/Tk program.) However, Tk also has other dynamic language interfaces, such as Python (which is a very simple language). Tkinter It is part of the Python standard library.
- The dictionary command
dict, in the new version of tcl, also features similar dictionaries to python:
# 一个简单的例子,并且使用了 [dict exists ...] 的命令
set count_dict {}
foreach char [split $word ""] {
if {[dict exists $count_dict $char]} {
dict incr count_dict $char
} else {
dict set count_dict $char 1
}
}
Chapter 10: Built-in commands for VMD
In this chapter, we aim to introduce the most commonly used vmd built-in commands. For a complete review or learning, see the tcl plug-in writing manual at vmd.
10.1 Atomselect command
10.1.1 Selection Concept of objects
The wording:
atomselect 体系ID号 选择语句 [frame 帧号]In VMD, the command to create a selection object and modify information about the object can be used to create a selection object with the specified region atom.
atomselectThe name of the object is followed by the order in which the selected region is created, respectively, byatomselect0atomselect1atomselect2...The script uses
atomselectand typically uses the following spelling:set sel [atomselect top "name CA"], which is where we have long since used$selto call this object.If the selection of a sentence itself requires the use of double quotation marks, the selection of a sentence can be used
{}The following is a list of the most commonly used names in the English language. For example, choose a name toSFor the first atom, with two or three characters behind it, it can be written:atomselect top {name "S.." "S..."}The same applies to the reverse slope, of course.\The two quotes in the string are not translated:atomselect top ""name \"S..\" \"S...\"
10.1.2 Memory usage mechanism of atomselect
The trajectory analysis process often produces a stack of
atomselectThe VMD crash was caused by a memory filling.atomselectThe more atoms selected, the greater the memory it takes. So, what is the point of this?atomselectAfter use, it is recommended to delete to release memory, such as using$sel deleteTo remove the variable, release memory. but The new atomselect number will continue to be passed back and forth. 。The command
atomselectis usually stored in memory during execution if it is called in the subroutine, but ifThe memory of the subroutine is deleted immediately after its inventionatomselectand does not accumulate memory. (as in the fortran language) it is equivalent to using$sel delete..If the subroutine itself is complex, it will call many times
atomselectShould be used appropriately in the subroutinedelete, to avoid finding that memory is not sufficient after the subroutine is not running.If Running directly in the control panel
atomselect, or running a loop command directly and using itatomselect, will always be memory-intensive is not droppeddelete.
10.1.3 Atomselect related commands
And then we're going to create the first one by default. selection that is atomselect0 The first is the "Sweetness".
atomselect0 num: The selected area is shown How many atomsatomselect0 list: Displays selected content Atomic numberingatomselect0 text: Displays the selected range Selection of the corresponding sentencesatomselect0 molid: Displays the selected content corresponding to System ID numberatomselect0 frame: Displays selected content The kitchenatomselect0 frame x: The information obtained by theatomselect0corresponding nickname Updated to the x-ray and then using theatomselect0 getcommand will be changed accordingly. p.s.: Ifatomselect0the corresponding dynamic field isx<20(for example, in the selection statement), it is usually necessary to update the selected atom to x-rays withatomselect0 update.atomselect0 global: Transferred to the universal naming space defined in the subroutineatomselect0
Chapter 11: Tcl scripting in real life
The code file for this section can be found at ~/tcl_practice
- These scripts were written by Tian Lu (sobereva@sina.com)
- Notes were written by Jimmy
- Some optimized scripts were written bt Jimmy
ex.11.1 outselpdb.tcl
set sel [atomselect top "same fragment as within 5 of fragment 0"];#区域选择选择 top 体系,选择语句是距离片段0的5埃范围范围内相同片段,并把这个 selection 存储到 sel 变量中,这里要用中括号来进行命令置换
set n [molinfo top get numframes];# molinfo 查询体系的信息,这里获得体系的帧数信息,并存储到 n 这个变量中
for { set i 0 } { $i < $n } { incr i } {
# 这里是循环命令的设置,设定 i 的起始值为0,然后如果变量i小于n,则运行脚本,直到i=n则终止,并且循环i,incre加1作为重启初始
$sel frame $i;# 获得当前帧
$sel update;#更新当前帧数的信息(因为当前是动态选区,5埃内的片段可能会变化,因此需要更新)
$sel writepdb $i.pdb;#把目前所选到的原子写入到当前工作目录下的 $i.pdb 文件中,格式为 pdb
}
# 首先需要明确的是,这里的 frame & update & writepdb 都是 vmd 的 atomselect 的内置命令,具体对应的功能在相应的行列中已经有标注出来
# molinfo & atomselect 都是 vmd 的内置命令
# 此脚本的目的是为了把选择的原子的每一帧结构都输出到当前目录下 $i.pdb
ex.11.2 allpairdist.tcl
#Output distance between each pair of atoms in all frames for "top" system
set natm [molinfo top get numatoms];# 这里设置一个变量 natm 代表 number of the atoms,molinfo获得top体系的原子的数量
for {set i 0} {$i<$natm} {incr i} {
#本质上这里是嵌套了两个循环语句,先看最外围的for循环
#起始的i设定为0,如果i小于总的原子数的数量,那么就运行脚本,并且重启化脚本是incr i加一
for {set j [expr $i+1]} {$j<$natm} {incr j} {
# 这里嵌套了新的变量j,j的值永远大于i并多1
# 这里需要注意的逻辑是,i 与 j 循环的时候,这里 i 和 j 是起始条件不同,例如i为1,则j为2,但j会从2慢慢往上遍历3、4、5...,而i仍旧为1,直到下一轮i的循环才改变i的起始
puts "Atom index: $i $j"
#值得一提的是,之前我们学过format来进行格式化的填写表格,
#这里设置打印出来的内容的格式为 atom index,即原子序号,为了展示我们配对的这一对的原子的原子序号是什么
set pair "$i $j"
#设定变量pair为那两个原子,这里需要用到双引号,方便变量引用
puts [measure bond $pair frame all]
#打印命令置换里measure的内容,measure的内容是测量bond的距离
#由于bond的测量需要两个参数值,因此前面才要写入pair,并且这里打印出来的内容还是所有帧数
}
#因此这个脚本总的来说是对i和j两个变量进行循环,最后打印出来循环的这一对原子的序号,以及他们的原子间距离,并且输出所有帧的情况
}
# 这个脚本用于显示 top 体系中每一对原子在所有帧中的距离
# 这个脚本用到的vmd的内置命令是molinfo和measure
# 而measure里的内容还有内置命令参数bond
ex.11.3 outwaternum.tcl
set sel [atomselect top "same residue as {water within 5 of resid 15}"];# 选区残基号15(从1开始记或者是与结构文件一致)附近5埃内的残基号(从0开始记)一致的水分子
;# 选择语句"same p as AAA",AAA选区的p属性相同的部分,上面的语句选择了与AAA选区一样的residue号,resid从1号开始记(若有结构文件有残基号则和结构文件的一致),residue 从0开始记
for {set i 0} {$i<=200} {incr i 1} {
# 创建一个 for 循环,起始i为0,≦200继续循环,每轮i加1,这里可设置循环的帧数范围
$sel frame $i ;# 设定选区的帧数为i变动
$sel update ;# 更新每帧
puts "Frame: $i Number of waters: [expr [$sel num]/3]"
# 打印结果,显示目前的帧数为多少,距离残基号15号附近5埃的水分子数量
# 这里用到一个内置命令atomselect0 num,得到选区的原子数量;其中之所以选区的原子要除以3,是因为一个水分子有三个原子,这里要显示水的数量
# 如果已知水中氧的名字为 OW,可以直接选取 OW,最后也不用除以3了
}
# 这个脚本的目的是显示 0 到 200 帧之间每一帧中距离残基15号 resid 15 的 5 埃内水的数量
ex.11.4 rangenum.tcl
proc rangenum {select fps1 fps2 {step 1}} {
# 定义一个过程为 rangenum 的命令,并且输入的参数值有选区、选择的帧数1、帧数2,并且设定了 step,其 step 默认的步长为1
set sel [atomselect top $select] ;#设定 sel 为选择 top 体系的当前帧,选择语句得自己后面输入,这里定义了到时候调用 rangenum 时填入的第一个参数本质是 atomselect 的选择语句
set totnum 0 ;# 设定 total number 为0
set numfps 0 ;# 设定 number of fps 为0
# 这里之所以两个都要设定为0,就是因为在后续循环语句中需要统计从帧数1到帧数2内选区内的累积的总原子数以及总的统计帧(for 循环几次就知道统计了几帧)
# 因此这里设计的两个是累加变量
for {set i $fps1} {$i<=$fps2} {incr i $step} {
$sel frame $i
$sel update
set num [$sel num]
puts "Frame $i : $num" ;# 打印每次循环到的对应帧数以及选区的原子数
incr totnum $num
incr numfps
# 更新 totnum 和 numfps
}
set avgnum [expr $totnum/double($numfps)] ;# 这里使用了double就是为了将帧数(整数)转换为浮点数
# 补充: tcl 语言和 python 不同,这里需要其中有一方转换成浮点数,否则两个都是整数,在tcl里只会得到整数
puts "Average number of atoms in this region:"
return $avgnum
# 计算完之后用 return 返回结果并终止循环
}
# 这个脚本的目的是:显示某一范围内的原子数目,从 fps 1 到 fps 2,每 step 帧输出一次(默认为1),并且统计此范围内的原子数的平均值
# 使用举例:rangenum {resname SOL and z>30 and z<52} 0 4000 50
# p.s. 用之前要记得载入轨迹!
ex.11.5 cylinder.tcl
set z 20; set zend 30; set step 0.5
# 这里我认为可以写成 set {z zend step} {20 30 0.5}
while {$z<$zend} { ;# 这里使用 while 循环
set ztmp [expr $z+$step] ;#设定 ztmp 为原先的 z 增加0.5的值
puts "Avg. num. of atoms between z= $z and $ztmp: [rangenum "((x-33)^2+(y-14.5)^2)<10^2 and z>$z and z<$ztmp" 0 100]"
# 使用到了前面我们的脚本 rangenum.tcl 定义的 rangenum 命令。其选择以 (33,14.5,$z<z<$ztmp) 为区域,这里为(33,14.5,20<z<30)半径小于10的圆柱,统计并输出0-100帧内每两帧、每0.5埃区间内平均粒子数
set z $ztmp ;# 重新初始化 z 为叠加了 0.5 的 z,然后重新循环
}
# 这个脚本是用于:统计出所设柱形中在 z=20~30 埃内每0.5埃区间内的平均粒子数,统计范围为 0-100 帧
ex.11.6 proteinHBnum.tcl
set sel [atomselect top protein]
for {set i 0} {$i<=100} {incr i 1} {
$sel frame $i ;# 由于上述蛋白质选区是静态选区,不管是哪一帧蛋白质选区的原子数都不变,因此就不需要再 $sel frame up 了
puts "$i [llength [lindex [measure hbonds 3.5 35 $sel] 0]]"
# 由于上面选定了是哪一帧的选区,因此这里 measure hbonds 也是上面的第几帧的选区
# measure hbonds D-H 和 A 原子的距离不超过3.5埃,D-H-A 的角度为35度
# 由于 measure hbonds 返回的是成氢键的 list,氢键的 list 会返回三个子列表(分别是Donor的index,acceptor的index,最后是氢原子的index),因此这里随便抓取 lindex 0号位置(0-based)的元素统计其长度即可知道成了多少氢键
# 随后, llength 返回该 list 的列表元素的数量,因此得到了氢键数目
}
# 这个脚本目的:显示 0~100 帧选区的蛋白质中的氢键数目随时间变化,打印出的结果就是第几帧,氢键有多少个
# 这个脚本主要用到的命令是 measure hbonds
ex.11.7 hb.tcl
proc hb {fps1 fps2 donor accept} { ;# 定义 hb 这个命令,需要输入帧数1、帧数2、氢键给体、氢键受体
set cum 0 ;# 初始化计数器 cum 为 0,用来记录“存在氢键的帧数”计算一个总数
for {set i $fps1} {$i<=$fps2} {incr i 1} {
set dd [atomselect top "index $donor" frame $i]
set aa [atomselect top "index $accept" frame $i]
# 在当前帧 ($i) 创建两个原子选择:一个是给体原子 dd,一个是受体原子 aa
set temp [measure hbonds 3.5 35 $dd $aa]
# 测量 dd 和 aa 之间是否满足氢键条件(距离 3.5 埃,角度 35 度),结果存入 temp
# 这里使用了一个 vmd 内置命令: measure hbonds [D-H···A的最大距离] [D-H-A的最大角度]
# measure hbonds 如果成键,会返回三个子列表的大列表,分别是 {Dodor atom index} {Acceptor atom index} {Hydrogen atom index}
if {$temp!="{} {} {}"} {puts $i;incr cum}
# 这里就是利用了 measure hbonds 的特点,如果满足氢键判据,则一定会输出三个list
# 所以这里判断若 temp 不含有三个空列表,则一定成键了,因此打印出形成氢键的帧号,并且计数器 cum 加1
}
puts $cum
# 循环结束后,利用计数器 cum 打印出总共形成氢键的帧数(你可以用它除以总帧数,算出氢键占据率)
}
# 这个脚本是用于分析轨迹中特定氢键的存在频率,定义统计氢键的命令
# 这个脚本可以使用 hb 5 200 34 86 来统计出在5~200帧之间,34号原子(作为氢键给体)与86号原子(作为氢键受体)之间形成的氢键总次数,形成了氢键的具体帧号也会在脚本运行期间被输出
# 事实上,上面这个脚本虽然逻辑正确,但存在两个问题
# 1. memory leak: 观察到,在 for 循环中,每次使用 atomselect 都会在内存中创建一个新的选择对象。如果不手动删除,它们会不断堆积。
# 因此,必须在循环结尾添加 $dd delete 和 $aa delete。
# 2. 在 temp 的列表判据中,可以写的更优雅:
# 用字符串比对 != "{} {} {}" 是一种比较“脆弱”的写法(如果由于某些原因中间多了一个空格就会判断失败)
# 更好的方法是将其存入 temp 之后,用 llength 去判定列表长度,你可以是判断整个 temp 的长度,也可以 lindex 抓取列表中的某个子列表,判断子列表的长度
proc hb {fps1 fps2 donor accept} {
set cum 0
for {set i $fps1} {$i<=$fps2} {incr i 1} {
set dd [atomselect top "index $donor" frame $i]
set aa [atomselect top "index $accept" frame $i]
set temp [measure hbonds 3.5 35 $dd $aa]
# 提取第一个子列表(给体列表),检查其长度是否大于 0
set donor_list [lindex $temp 0]
if {[llength $donor_list] > 0} {
puts "Frame $i: H-bond found!"
incr cum
}
# 极其重要:清理内存,防止循环堆积 atomselect 导致内存泄漏
$dd delete
$aa delete
}
puts "Total frames with H-bond: $cum"
}
# 上述这个脚本可以打印出总的形成给定的 donor atom 和 acceptor atom 的氢键帧号以及形成该氢键的总的帧数
ex.11.8 atomxyz.tcl
proc atomxyz {atom} { ;# 定义 atomxyz 这个 processor
set result [open atom$atom.txt w] ;# 写操作写入 atom$atom.txt,并颁发 result 这个文件句柄id
set nfps [molinfo top get numframes] ;# 信息读取 top 体系的 number of frames,计数为 nfps
set sel [atomselect top "serial $atom"] ;# 选择语句为 top 体系的以 serial(1-based) 为顺序的原子序号
for {set i 0} {$i<$nfps} {incr i 1} {
$sel frame $i
# 一帧帧的过
puts $result "$i [$sel get x] [$sel get y] [$sel get z]"
# 打印写入 atom$atom.txt 的内容为 [帧号] [该原子的x/y/z坐标]
# 这里用到了 [atomselect0 get property] 命令,笔者认为,实际上这里可以写的更优雅
# 例如写为 puts $result "$i [$sel get {x y z}]"
}
close $result ;# 释放内存
puts "Done!"
}
# 这个是定义输出轨迹中某原子的坐标的命令
# 例如使用 atomxyz 7,则7号原子在所有帧中的 x,y,z 坐标会输出到 VMD 目录下的 atom7.txt 里,第一列是帧号
ex.11.9 hhj.tcl
for {set ifps 0} {$ifps<=100} {incr ifps 1} {
# 这个 for 循环主要是统计对象是 0-100 帧的,步长为1
set hhjcen [measure center [atomselect top "name O4" frame $ifps]]
# 利用 vmd 内置命令 measure center $sel 来获取选区的几何中心以及指定的帧号,并返还该坐标的 list
# 后续将该坐标的 list 分别用 lindex 抓取相应的 x/y/z 坐标值用于后面的计算
set nowx [lindex $hhjcen 0]
set nowy [lindex $hhjcen 1]
set nowz [lindex $hhjcen 2]
set selow [atomselect top "((x-$nowx)**2+(y-$nowy)**2+(z-$nowz)**2 < 9**2) and name OW" frame $ifps]
# 这段是这个脚本的关键之处。首先选定 top 体系与上述几何中心距离小于9纳米且原子名称为 OW (由于这是水的氧,因此本质反应了水分子数量)的选区,并且指定帧数
puts "$ifps [$selow num] $nowx $nowy $nowz"
# 打印结果在第几帧、上述选区的 OW 原子反应水分子数、以及对应的几何中心的坐标
$selow delete
# 释放内存,避免内存泄漏
}
# 这个脚本的应用场景举例如下:
# 统计某环糊精在 0-100 帧内空腔内水分子数
# 即统计以环糊精6个名为 O4 的原子几何中心为原点,半径为9埃内的 OW 原子数
# 输出结果第一列为帧数,第二列为水分子数,后三列为此环糊精
ex.11.10 rangeindex.tcl
proc rangeindex {range} {
# 从下面的 atomselect 也可以看出来这里要输入的 range 本质上是选择语句
set fps [molinfo top get frame] ;# molinfo 获取当前 top 体系目前的帧号
set sel [atomselect top $range frame $fps] ;# 将当前帧的选区存储到 sel
set result [open D:\\range.txt w] ;# 发布一个 result 的身份 id,写操作写入 range.txt
# 需要注意的是,这里的路径应该是针对 windows 版本的。
# linux 路径下一律用单正斜杠 /
# windows 的文件路径表示是用的反斜杠 \,但由于 tclsh 是 unix 下的,因此 win 的路径表示要么用单正斜杠/,要么用两个反斜\\
# 正确写法例如:D:/tcl/range.txt 或 D:\\tcl\\range.txt
set k 0 ;# 设定计数器 k 的初始值为0
foreach i [$sel list] {
# foreach 对 atomselect 的 list 进行遍历循环
incr k
puts -nonewline $result [expr $i+1]\
# -nonewline 代表不换行,将结果写入 $result
# 而写入的内容则是 $sel list 的每一个列表元素加上1,这样才能满足从序号1开始
# 注意!上面需要一个空格,以便于将写入的 $i+1 的元素分别用空格隔开,需要反斜杠避免空格转义
if {$k%6==0} {puts $result " "}
# 注意,这里 $k%6==0 并非是我们在 tcl_note.tcl 中 7.1 小节中学习的排版控制
# 这里的 $k%6==0 本质上是运算符号,% 是 modulo。如果 k 的值能被6整除,余尾0,则打印 " "
# 因此,这个 k 就是每循环一次计数一次的计数器,每输出六次 $i+1 后换一行
}
close $result ;# 释放缓冲区
puts "$k atoms in total"
# 在循环结束的最后打印总的统计到的选区的原子数,但不写入文件而是打印在终端
# 笔者认为,这里最好补充一个 $sel delete 释放内存
$sel delete
}
# 利用 VMD 选择语句构建 GROMACS 的索引文件,在得到的文本中的第一行加入组名,例如 [ CA ],并改为索引文件后缀,以便于在 GROMACS 中使用 make_ndx 命令时能够正确识别这个组
# 这个脚本的目的是输出*当前帧*中指定选择范围内的原子的序号到 D:\range.txt。格式与 GROMACS 的 .ndx 文件相同,从序号1开始,每6个换一行,以空格为间隔
# 使用例子:rangeindex {name CA and not within 13 of index 964}
ex.11.11 numless.tcl
set k 0 ;# k是计数器,用来反映满足条件的帧数有多少个
label delete Bonds all ;# 删除所有历史测量距离,确保接下来新建的标签 ID 为 0
# 这是一种非常好的“打扫战场”的编程习惯。VMD 给新建的标签是从 0 开始自动编号的。如果你不清空历史记录,你接下来新建的标签可能被编号为 1、2 或 3,导致后续代码找不到实际我们所需的标签。
label add Bonds 0/85 0/98
# label add Bonds:添加一个距离测量标签,由于前面我们已经清楚了 label - Bonds 类别下的标签,因此这里创造的 label 的 ID 号将为0
# 0/85 和 0/98 中,0指的是0号分子,而非 label ID 为0
# 0/85:代表第 0 号分子 (Molecule ID 0) 的 第 85 号原子 (Atom Index 85)。
# 0/98:代表第 0 号分子的第 98 号原子
foreach i [label graph Bonds 0] {
# label graph Bonds ... 将一次性提取整个轨迹数据,得到指定的 Bonds,Label ID号为0的所有数据
# label graph 将导出一个 list,因此可以用于遍历
# label graph Bonds 0 中的0与前面的0不一样,这里的0是 Label ID - Bonds 类别下的 ID 0号
# 因此,前面才要删除所有 label - Bonds 类别的标签,不然 0 号指定可能会错误
if {$i<16} {incr k 1}
# 如果满足原子间距离小于16埃,则满足条件的帧数计数器k加1
}
puts $k
# 打印出轨迹中满足条件的帧数
# 这个脚本的作用:显示 index 85 与 index 98 在轨迹中距离小于16埃的帧数
# 这个命令用到了 vmd 的内置命令 label,label 是 VMD 中极其强大的“几何量角器”和“轨迹测距仪”
# 常规思路来说:在早期的脚本编写中,很多人会写一个 for 循环,然后用 animate goto $i 逐帧跳转,再用 measure bond 去量距离。这种“跳转一帧 -> 测一次 -> 再跳转一帧”的方法非常慢,因为 VMD 每次跳转都需要重新渲染和更新很多底层状态。
# 而 label graph 默认就是测量并提取所有帧的数据
# 例如1000帧轨迹,使用 label graph 将会调用 VMD 的底层 C++ 引擎计算出一个包含 1000 个数值的 Tcl List:{第0帧距离 第1帧距离 第2帧距离 ... 第999帧距离}
# 应当指出,上面的脚本还有两个可以提升的地方,可以进一步提高鲁棒性:
# - 0号分子可以更改为动态获取当前分子 ID(用top体系的动态性来获得分子 ID的动态性)
# - label 也可以更改为动态获取
#################优化版本#################
# 先清空历史
label delete Bonds all
# 动态获取当前分子 ID(假设为 top,动态获取)
set mol_id [molinfo top]
# 添加标签,但不需要死记它的 ID,这里仍然需要自己指定是哪两个原子
label add Bonds $mol_id/85 $mol_id/98
# 获取刚才添加的最后一个标签的 ID(动态获取)
set label_list [label list Bonds]
set last_label_id [lindex [lindex $label_list end] 0]
# 首先获得 label 里 bonds 类别的 list,随后 lindex $label_list end 知道最新的 label list
# 上述获得的 list 中第一个列表元素就是 bonds 的 label ID,而后面的列表元素则是具体是哪个分子ID的哪个键
# 因此还需要 lindex [lindex $label_list end] 0 获取 label ID
# 举例来说,set label_list [label list Bonds]后,执行后,VMD 会返回一个包含多个子列表的“大列表”。
# 此时 $label_list 变量里面存储的是:{ {0 0/5 0/10 on} {1 0/85 0/98 on} }
# lindex $label_list end 提取大列表里的最后一个元素(也就是刚刚最新创建的那个标签的属性)。
# 执行后,得到的是一个子列表:{1 0/85 0/98 on}
# 子列表里不仅包含 label ID,还包含了具体的键(0/85, 0/98)以及开关状态(on)
# 最外层的 lindex [...] 0,提取刚刚那个子列表的第一个元素,从而才能真正动态获得 $last_label_id,这样就可以动态抓取
set k 0
foreach dist [label graph Bonds $last_label_id] {
if {$dist < 16.0} {incr k 1}
}
puts "距离小于 16 Å 的总帧数为: $k"
ex.11.12 outdih.tcl
set result [open result.txt w] ;#写操作,并颁发 $result 的身份ID
foreach i [label graph Dihedrals 0] { ;# 遍历已经标记好的二面角在轨迹每帧的数据
# 这里的0是标签索引 Dihedral 目录下的 label ID
# 假设现在有两帧数,那么将得到 {atom1 atom2 atom3 atom4 angle1} {atom1 atom2 atom3 atom4 angle2}
puts $result $i} ;# 写入文件,并且写入 label graph 的 list,并且还附上相应的帧号
# puts 将逐行写入,因此得到:
# atom1 atom2 atom3 atom4 angle1 1
# atom1 atom2 atom3 atom4 angle2 2
close $result
# 这个脚本的作用:把标记好的二面角(0号)的每一帧数值输出到 rize.txt 中
# 亦可直接写(直接一行命令,不用写上面这么几行,直接利用 VMD 的内置命令):
# label graph Dihedrals 0 rize.txt
# 此时 rize.txt 的格式是:[帧号][数值]
ex.11.13 comdist.tcl
proc comdist {sel1 sel2} {
# 定义 comdist 过程,需要提交两个选区的参数
set result [open comdist.txt w]
# 创建文件ID result,写操作写入 comdist.txt
set nfps [molinfo top get numframes]
# molinfo 获得 top 体系的帧数,存入计数器 nfps
set range1 [atomselect top $sel1]
set range2 [atomselect top $sel2]
# 将前面的两个选择语句正式变为选区 range1 和 range2
for {set i 0} {$i<$nfps} {incr i 1} {
# for 循环,上线就是循环完整个 top 体系的所有帧
$range1 frame $i; $range1 update
$range2 frame $i; $range2 update
# 由于是动态选区(与时间距离挂钩),因此需要时刻更新帧以及相应的选区更新
set com1 [measure center $range1 weight mass]
set com2 [measure center $range2 weight mass]
# 利用 vmd 内置命令,分别获得 range1 和 range2 的质心
set disx [expr [lindex $com1 0]-[lindex $com2 0]]
set disy [expr [lindex $com1 1]-[lindex $com2 1]]
set disz [expr [lindex $com1 2]-[lindex $com2 2]]
set dist [expr sqrt($disx**2+$disy**2+$disz**2)]
# 计算质心之间的距离
puts $result "$i $dist"
# 最后打印到 $result 里为 [帧号] [相距多少埃]
}
close $result
# 笔者认为,这里应该还得内存释放下:
# $range1 delete
# $range2 delete
}
# 这个脚本的目的是 计算整个轨迹中两组选区的质心之间的距离随时间的变化。
# comdist = center of mass distance
ex.11.14 mindist.tcl
proc mindist {region1 region2 {frame -1}} {
# 先定义 mindist 这个过程
# 需要输入三个参数:前两个参数是两个选区的选择语句,而第三个参数为帧数,默认为 -1
if {$frame==-1} {
set fps [molinfo top get frame]
# 假设用户没有提交帧数(因为一般来说帧数不会为-1),则触发该分支
# molinfo top get frame 这个命令将会获得当前 top 体系的帧数,并存储到 fps 中
} else {
set fps $frame
# 假设用户提交了帧数,则触发该 else 分支
# 直接将 fps 设定为用户提交的帧号
}
# 上述实际上提供一种思路,设定一个不可能的默认值,来导向一个已经确定好确定方案的分支
set sel1 [atomselect top $region1 frame $fps]
set sel2 [atomselect top $region2 frame $fps]
set mind 999999
foreach i [$sel1 list] {
foreach j [$sel2 list] {
# 经典的设置对一对 i&j 循环的语句
set tmpd [measure bond "$i $j" frame $fps] ;# 获得这一对原子之间的距离
if {$tmpd<$mind} {
set mind $tmpd
# 到这里为止是这段代码的精华所在之处
# 首先利用预设的 mind 为999999确保这个 if 语句初始阶段可以启动
# 此后测得更小的 tmpd 便更新赋值给 mind
set min_i $i
set min_j $j
# 后面这几个嵌套的语句不断循环,直至没有比 tmpd 更小的 if 条件出现时,则打印出此时 tmpd 对应的 i&j 一定也是距离最近的
}
}
}
puts "Minimum distance is [format %9.4f $mind] Angstrom between index $min_i and $min_j"
# 上面用了一个 format 命令,语法为 format formatstring(排版格式) varName...
# %9.4f 指定后面填入的 $mind 的排版格式,指定数字类型是浮点数,保留4为小数点,总的字符占用为9格(包括小数和小数点,因此小数点前的部分最多4格)
# %9.4f 默认当没有值可占用时用空格占用,如果写成 %09.4f 则用0占用
# 假设两个选区最近的两个原子分别为11和22,距离为 2 埃,且修改为 %09.4f,则打印结果为:
# Mnimun distance is 0002.0000 Angstrom between index 11 and 22
# 建议最后写上:
# $sel1 delete
# $sel2 delete
}
# 该脚本的目的:计算两个选区间最近的两个原子间距离并给出原子号
The commentator argues that, Since it was originally written using only tcl for double looping, this is a waste of computational resources (the weight calculation should be handed over to the c++ engine to do it). the following approach measure contacts is proposed, first by the probe to reduce the range of atoms required for a loop (and then by cpp), and then by a more rational method of double-looping:
#####优化版######
# 注者注:
# 事实上,像这种双循环的例子是十分浪费计算资源的(尤其是 Tcl 这种解释型脚本语言,它的循环非常慢),低效且不优雅!
# 下面的优化版本的核心策略:
# 把最沉重的“找邻居”工作,外包给 VMD 底层的 C++ 极速引擎(使用最新的 measure contacts 命令配合网格搜索算法),用较快的 c++ 创建微球探针,缩小实际上要遍历的原子对,然后在极小的数据范围内用 Tcl 的循环找出精确最小值
proc mindist {region1 region2 {frame -1}} {
# 1. 动态获取帧数 (延续了原先的默认值设计)
if {$frame == -1} {
set fps [molinfo top get frame]
} else {
set fps $frame
}
# 2. 建立原子选择
set sel1 [atomselect top $region1 frame $fps]
set sel2 [atomselect top $region2 frame $fps]
# [容错防御] 如果选区有一方是空的,直接退出,避免系统崩溃
if {[$sel1 num] == 0 || [$sel2 num] == 0} {
puts "警告:其中一个或两个选区为空,请检查你的选择语句!"
$sel1 delete; $sel2 delete
return
}
# 3. 核心算法:自适应截断半径搜索 (Adaptive Cutoff)
# 设定一个初始的探测半径(比如 2.0 Å),如果没有接触,就翻倍放大,直到找到接触为止。
set cutoff 2.0
set max_cutoff 200.0 ;# 设定一个极其安全的搜索上限
set contacts {} ;# 显示声明变量,避免潜在的作用域问题
while {$cutoff <= $max_cutoff} {
# 调用底层 C++ 极速命令:找出 cutoff 范围内的所有成对原子
set contacts [measure contacts $cutoff $sel1 $sel2]
# contacts 会返回两个列表:{ {sel1的原子} {sel2的原子} }
# 如果第一个列表长度大于 0,说明我们“网”到原子了,立刻用 break 跳出循环:
if {[llength [lindex $contacts 0]] > 0} {
break ;# 结束整个循环,并跳出循环
}
# 如果没网到,把半径翻倍继续找 (2->4->8->16...)
set cutoff [expr {$cutoff * 2.0}]
}
# 4. 在锁定的小范围内,寻找绝对精确的最小值
set mind 999999.0
set min_i -1 ;# 显示声明变量,避免潜在的作用域问题
set min_j -1 ;# 显示声明变量,避免潜在的作用域问题
set list1 [lindex $contacts 0]
set list2 [lindex $contacts 1]
# 在上一步 contacts 返回给我们的成功匹配到的潜力原子对放入 list 1/2
# 此时,我们只需要遍历被底层 C++ 引擎筛选出来的这几十/几百对原子即可
foreach i $list1 j $list2 {
set tmpd [measure bond [list $i $j] frame $fps]
if {$tmpd < $mind} {
set mind $tmpd
set min_i $i
set min_j $j
}
}
# 5. 打印结果
puts "Minimum distance is [format %9.4f $mind] Angstrom between index $min_i and $min_j"
# 6. 清理一开始的 atomselect 导致的潜在内存泄漏!
$sel1 delete
$sel2 delete
}
ex.11.15 proteinSASA.tcl
set protein [atomselect top "protein"]
# 选择 top 体系的蛋白区域 protein
set phob [atomselect top "hydrophobic"]
# 选择 top 体系的憎水区域(hydrophobic,因此缩写为 phob 注意不是亲水的 hydrophilic)
set phil [atomselect top "not hydrophobic"]
# 选择 top 体系的亲水区域(hydrophilic,因此缩写为 phil),这里直接非疏水的认定为亲水的了
set n [molinfo top get numframes]
# 获取当前 top 体系的所有帧数,记为 n
set myfile [open SASA.dat w]
# 写操作写入 SASA.dat,并给文件 id 为 myfile
puts $myfile "hydrophobic hydrophilic Total"
# 打印后续的数据内容对应的名称 “hydrophobic hydrophilic Total”
for {set i 0} {$i < $n} {incr i} {
puts "Calculating frame $i/$n..."
# 打印当前帧的计算进度(进行到哪一帧了)
$protein frame $i
# 选取 $i 帧的选区
set val1 [measure sasa 1.4 $protein -restrict $phob]
set val2 [measure sasa 1.4 $protein -restrict $phil]
# 这里用到了 vmd 的内置命令 measure sasa
# measure sasa 1.4 atomselect0 -restrict $sel
# 以 1.4 埃为探测球的半径得到 atomselect0 的 SASA,单位是 埃平方
# 加上 -restrict $sel 则是计算前面 atomselect0 体系中 $sel 选区暴露在表面的 SASA
# 理论上,体系中各个部分单独算的结果之和应与计算整体时是一致的
puts $myfile "Frame $i: $val1 $val2 [expr $val1+$val2]"
# 将该打印结果打印到 $myfile,内容为 “Frame [帧号] [蛋白的疏水区域的 SASA] [蛋白的亲水区域的 SASA] [当前帧号下的蛋白暴露表面的 SASA]”
}
close $myfile ;#清除内存
# 最好是再清理下选区占用的内存:
# $phob delete
# $phil delete
# 这个脚本的目的:在 SASA.dat 中输出每一帧蛋白的疏水、亲水和总 SASA
ex.11.16 fpssene.tcl
trace variable vmd_frame(1) w showarr ;# 使用回调函数,option 为监控variable,跟踪的变量为 vmd_frame(1),操作为写w,调用 showarr 命令
# 回顾 trace 函数:见 tcl_note.md 第9.1小节
# vmd_frame(i) 是 VMD 中的特殊变量,代表分子 ID=i 的体系当前帧号,其改变帧号时就会更新,被调用的函数应带一个参数。
# 这里 vmd_frame(1) 代表分子ID=1的帧号,因此载入的轨迹分子应该确保 ID 号为1,即在脚本载入后再导入分子
mol new ;# vmd 内置命令,创建一个新的空分子,作为绘图载体图层
proc showarr {args} {
# 这里一般来说需要显式声明 {变量的数组名 数组元素名 操作}
# 若填写为 args 可变参数(arguments,见 tcl_note.md 第6.3小节)
# 一般 tcl 会将上面 trace 得到的三个参数传递给 proc,直接写 args 照单全收,比较省事
global vmd_frame ;# 接收全局变量,才能得知当前的帧数,这样才能在后续的文本字符串中引用当前帧数
set ene(0) 0.00
set ene(1) 1.18
set ene(2) 3.21
set ene(3) 4.03
set ene(4) 5.02
# 假设这个体系为5帧,这里实际上输出到了各帧的能量,将能量定义在了 ene 数组中
# 后续文本会读取当前第几帧,随后将“目前帧号”作为数组元素导入,从而引用预设好的 ene 数组即可
graphics 0 delete all
# vmd 内置的绘图操作命令,有 graphics 和 draw
# draw 默认作图于 top 体系(因此需要更改当前的 top 体系的绑定)
# graphics 需要指定 分子ID,语法为 graphics [分子ID]
# 需要注意的是,graphics 0 delete [绘图操作返回的ID],这里是 all,删除绘图于分子ID号为0上的所有绘图操作
# 之所以要删除作图操作,是因为轨迹在不断播放,每一帧都会触发这个函数。如果不先清除上一帧画的时间,新的时间就会直接叠印在旧时间上面,几帧过去后,屏幕上就会变成一团糊涂的色块。
# 由此可见,该绘图的0号分子应该为 mol new 那一步创建的分子,这意味着:
# 该脚本需要在没载入真正的结构分子前,先载入此脚本,确保 mol new 创建分子号为0的载体图层
# 只有确保载体图层为0,上述回调函数跟踪的变量 vmd_frame(1) 才能反映真正载入的分子(此时分子ID为1)
graphics 0 color white ;# 设定之后绘制物件的颜色为白色,在 vmd 中 white 也可以用颜色的序号 8 来代替
graphics 0 text {0 0 0} "$ene($vmd_frame(1)) kcal/mol" size 3
# 创建文本的格式为 graphics [分子ID] text {x y z} "要显示的内容" size ... thickness ...
# 在0号分子的 (0,0,0) 处创建指定的文本字符串,字号大小为3
# 回顾关于数组元素的置换,见 tcl_note.md 第2.2.2小节
# 这里本质上是将帧数填入数组,查询以及预设好的 ene 数组能量值
}
# 此脚本的目的:播放轨迹时显示每帧结构对应的能量
# 能量定义在了 ene 数组里。
# 使用注意:
# 先运行此脚本(确保创建辅助图层的分子ID为0号)
# 然后再载入轨迹(确保要显示帧数的轨迹的分子ID为1号)
# 文字首先显示在原点(0,0,0)。需要固定(F)ID=1的体系后,平移ID=0的文字到达合适的位置;然后将文字层ID=0固定,再放开体系ID=1。
The commentators believe that setting the ene arrays here cannot be dynamically captured, which is not appropriate. The real molecular dynamics trajectory is tens of thousands of tons, and it is impossible to write it in the script manually. The first step is to ensure that the script is imported in a certain order, which is also a static. The following improved script therefore addresses two main issues:
- Tcl script dynamically reads external energy data files exported by gromacs' own analytics tool (Here we assume that it is extra-exported as
energy.txt) - Dynamic binding of real molecular ID avoid referring to hardcoding (you need to manually enter the molecular ID yourself)
- The user can automatically tell the current trajectory of the device by default to 1 PS per ton and adjust parameters manually.
The first is the "Fireflowers".
Preparation The data file is energy.txt . Suppose you have a text file that contains the order of the buttons stored in it (this can usually be extracted by a single click from the analytics tool NAMD or GROMACS):
energy.txt:
-1045.2
-1048.1
-1042.5
-1050.0
...
Two knowledge supplements:catch &string trim
- The following is a list of the most common types of capture:
[catch {code...} err]This line of code enables the built-in Tcl language Exception Handling) Capture commands It's a functionally equivalent to Python.try...exceptThe structure. It will try to Running large brackets in an independent execution context{}The code inside.- If Successful execution :
catchthe command itself would beReturns the integer0 - if Failure to execute :
catchI will Abnormalities in active interception thrown by operating systems The first is the "Firefinder" program, which is designed to prevent it from turning into a fatal error that causes the program to crash. At this point,catchReturns non-zero integers (usually1) And the bottom of the Detailed error information strings are written to the specified variableerr。 - Generally, we check if the file is open correctly (the error may be: misspelling of the file path, no file exists, no reading permissions, etc.) such as commands:
catch {set myfile [open file_path op] err}
- If Successful execution :
- String trim & date cleaning:
string trim $line- The wording:
string trim [需处理的string] ?chars? - Function: Its return value is the end of a string string from the end of a string that needs to be processed, strip off characters in a chars set which is treated after the string.
- When it is not explicitly specified which specific characters to strip,
string trimBy default, all border blank characters are removed The White Space Characters include:space(empty)- tab,
\t(horizontal notation) - newline,
\n(switching) - Carriage return,
\r((back to carriage sign) - For example:
string trim "abcde" {a d e} # 剔除掉字符串中包含后面 chars list 中的列表元素 bc string trim " def " # 不显式指定的时候直接返回 def string trimIt is often used to pre-process standard data, removing invisible interference characters in advance. Commonly used in conjunction withgets $file line, this command can be used directly withstring trim $line(using the default string trim setting) as it can obtain a single row of strings in a file and is temporarily stored in$line.
- The wording:
The improved version of fpssene.tcl
# 使用方法:
# 需要输入的参数:energy_monitor [mol_id (你要监控的真实轨迹分子ID)] [file_path (能量文本文件的路径)] [frame_step(播放的轨迹每帧对应多少ps,单位为ps,默认为每帧1ps)]
# 先声明全局变量,便于后续这几个参数能在不同的函数之间共享数据
global energy_list ;# 此变量用于将 energy.txt 里的数据提取为 list 并将其存放于该变量中
global text_mol_id ;# 此变量主要用于动态获取创建的图层的分子id,并存放于该变量中
global target_mol_id ;# 此变量主要是将目标轨迹的分子id存放于该变量中
global dt_ps ;# 这个变量关乎于目前播放的帧数对应多少间隔ps,免得和能量对应的帧数单位对不上
# 主函数:能量的数值读取(energy_list)与图层、跟踪器的建立(target_mol_id)
proc energy_monitor {mol_id file_path {frame_step 1.0}} {
# 定义 energy_monitor [mol_id (要监控的真实轨迹分子ID)] [file_path (能量文本文件的路径)] [frame_step(播放的轨迹每帧对应多少ps,单位为ps,默认为每帧1ps)]
global energy_list text_mol_id target_mol_id dt_ps vmd_frame ;# 先接受全局变量
set target_mol_id $mol_id ;# 输入的id参数绑定为动态的变量,是动态绑定的关键
set energy_list {} ;# 将其开始设置为列表
set dt_ps $frame_step ;# 给定播放帧数的步长,且后续回调函数会利用到,因此前面已先声明在全局变量中
# 1. 动态抓取:打开并读取外部能量文件
if {[catch {set myfile [open $file_path r]} err]} {
# 这里需要在里面加一个中括号变成命令置换
# catch {code...} err,其中 catch 是 tcl 内置的异常捕获命令
# catch 首先会尝试·独立执行· 上下文中 {} 内的 code
# 如果执行成功,那么 catch 则会返回整数 0
# 如果执行失败(例如:文件路径拼写错误、文件不存在、没有读取权限等),catch 将主动拦截由操作系统抛出的异常,阻止其转化为导致程序崩溃的致命错误。此时,catch 返回非零整数(通常是 1),并将底层的详细错误信息字符串写入到指定的变量 err 中
puts "错误:无法打开能量文件 $file_path"
return ;# 返回值提前结束程序
}
while {[gets $myfile line] >= 0} {
# 这一段的 code 可以回顾 tcl_note.md 中的第8.1小节
# gets $fp line 会返回其成功读到的字符数量,其 end of file 会返回-1,空行则返回0
# 由于我们要将每行的能量和后续的帧数进行对应,因此这里需要严格排除掉空行的情况
if {[string trim $line] != ""} {
# string trim $line 负责在数据进入内存前进行标准的数据预处理(Data Preprocessing),用于移除不可见的干扰字符
# string trim $line 默认设置下可以剔除空行,将读取到的能量追加到列表中;
# 需要注意的是 $line 是由于上一步我们已经将读取到的该行的字符串数量和内容临时存入 line 中了,因此可以调用 line
# 这里 if 语句指当 trim 过后的 line 不是空字符的时候,即认为有能量的数值,于是后续写入到 list 中
lappend energy_list [string trim $line] ;# 本代码的关键
# 前面我们创建的全局变量 energy_list 将作为 list,用于收纳能量的数值
}
}
close $myfile
puts "成功加载了 [llength $energy_list] 帧的能量数据!"
# 2. 动态分配:创建专门的文字图层,并让 VMD 告诉我们它的 ID,而不是硬编码的0号id
set text_mol_id [mol new] ;# 图层的id动态绑定的关键
mol rename $text_mol_id "Energy_Text" ;# 给这层图层起个名字,在GUI里更好看,也便于后续识别
# 3. 注册跟踪器,跟踪目标分子的帧数变化
# 先清理可能存在的旧追踪器,防止重复绑定,这个删除也可不写
trace vdelete vmd_frame($target_mol_id) w energy_display
# 添加新追踪器
trace variable vmd_frame($target_mol_id) w energy_display
puts "能量监控已开启,播放轨迹即可看到效果。"
}
# 回调函数:每当帧数变化时触发,打印相关信息到图层中(text_mol_id)
proc energy_display {args} {
global energy_list text_mol_id target_mol_id dt_ps vmd_frame ;# 先照例获取全局变量
# 1. 获取当前真实播放的帧数(current frame)
set curr_frame $vmd_frame($target_mol_id)
# 2. 从我们刚刚读取制作的列表(energy_list)中,提取当前帧对应行数的能量 (即当前帧将对应列表元素索引序号)
set curr_energy [lindex $energy_list $curr_frame] ;# 本代码的关键
# 上面此行是和 energ_list 联用的关键,将 energy.txt 处理成 list 之后与帧数一一对对应
# 由于 vmd 中的帧数从 0 开始,因此这里不必担心 lindex 是 0-based 计数的规则,因为是相匹配的
# 容错处理:如果轨迹帧数超过了能量文件里的行数,则显示 N/A 的报错
if {$curr_energy == ""} {
set curr_energy "N/A"
}
# 绘图逻辑,而 text_mol_id 我们一开始就定义为了 global 变量,并且在 energy_monitor 过程中已经定义其对应 [mol new]
graphics $text_mol_id delete all ;# 后续帧数更新调用 energy_display 的时候避免图层重叠
graphics $text_mol_id color white ;# 设定颜色为白色
set curr_time [expr {$curr_frame * $dt_ps}]
# 若用写法 [expr "$curr_frame"*"$dt_ps"] 虽然合理,在 Tcl 中调用 expr 时,Tcl 解析器会先进行一轮变量替换(把 $curr_frame 变成数字),然后再把拼接好的字符串扔给数学引擎去解析。
# 双引号双置换的写法不仅会拖慢几倍的计算速度,在遇到特殊字符时还极易引发致命报错。
# 因此为了减少变量替换造成的资源浪费,最好是改写为 [expr {$curr_frame * $dt_ps}],直接把这个算式原封不动交给底层的 C 语言数学引擎去算,让数学引擎自己去读取变量
graphics $text_mol_id text {0 0 0} "Frame: [format %7.1f $curr_time]ps | Energy: $curr_energy kcal/mol" size 3
}
ex.11.17 showtime.tcl
trace variable vmd_frame(1) w showtime ;# 使用回调函数,option 为监控 variable,跟踪的变量为 vmd_frame(1),操作为写w,调用 showtime 命令
# 回顾 trace 函数:见 tcl_note.md 第9.1小节
# vmd_frame(i) 是 VMD 中的特殊变量,代表分子 ID=i 的体系当前帧号,其改变帧号时就会更新,被调用的函数应带一个参数。
# 这里 vmd_frame(1) 代表分子ID=1的帧号,因此载入的轨迹分子应该确保 ID 号为1,即在脚本载入后再导入分子
mol new ;# vmd 内置命令,创建一个新的空分子,作为绘图载体图层
proc showtime {args} {
# 这里一般来说需要显式声明 {变量的数组名 数组元素名 操作}
# 若填写为 args 可变参数(arguments,见 tcl_note.md 第6.3小节)
# 一般 tcl 会将上面 trace 得到的三个参数传递给 proc,直接写 args 照单全收,比较省事
global vmd_frame ;# 接收全局变量,才能得知当前的帧数,这样才能在后续的文本字符串中引用当前帧数
graphics 0 delete all
# vmd 内置的绘图操作命令,有 graphics 和 draw
# draw 默认作图于 top 体系(因此需要更改当前的 top 体系的绑定)
# graphics 需要指定 分子ID,语法为 graphics [分子ID]
# 需要注意的是,graphics 0 delete [绘图操作返回的ID],这里是 all,删除绘图于分子ID号为0上的所有绘图操作
# 之所以要删除作图操作,是因为轨迹在不断播放,每一帧都会触发这个函数。如果不先清除上一帧画的时间,新的时间就会直接叠印在旧时间上面,几帧过去后,屏幕上就会变成一团糊涂的色块。
# 由此可见,该绘图的0号分子应该为 mol new 那一步创建的分子,这意味着:
# 该脚本需要在没载入真正的结构分子前,先载入此脚本,确保 mol new 创建分子号为0的载体图层
# 只有确保载体图层为0,上述回调函数跟踪的变量 vmd_frame(1) 才能反映真正载入的分子(此时分子ID为1)
graphics 0 color 8 ;# 设定之后绘制物件的颜色为序号8,在 vmd 中代表颜色为白色
graphics 0 text {0 0 0} "[format %7.1f [expr $vmd_frame(1)*1.0]]ps" size 4 thickness 2
# 创建文本的格式为 graphics [分子ID] text {x y z} "要显示的内容" size ... thickness ...
# 在0号分子的 (0,0,0) 处创建指定的文本字符串,字号大小为4,粗细为2
# 字符串的内容还使用了命令置换,$vmd_frame(1)*1.0:先是计算读取当前分子 1 的帧数,并乘以 1.0。这里的 1.0 是步长转换系数
#(假设你跑的 MD 轨迹是 1 帧 = 1.0 ps。如果是 1 帧 = 2.0 ps,这里就要改成 2.0)
# 还使用了 format 命令,对 $sel 指定的排版格式为 %7.1f (包含小数点总的7格,并且取小数点后一位)
}
# 此脚本的目的: 播放轨迹时显示每帧的时间
# 使用注意:
# 运行时假定轨迹每帧为 1ps 地写入一次
# 先运行此脚本(确保创建辅助图层的分子ID为0号)
# 然后再载入轨迹(确保要显示帧数的轨迹的分子ID为1号)
# 文字首先显示在原点(0,0,0)。需要固定(F)ID=1的体系后,平移ID=0的文字到达合适的位置;然后将文字层ID=0固定,再放开体系ID=1。
If you want to optimize the script (e.g. dynamic crawling id), refer to Ex.11.16 Improved version ..
ex.11.18 drawbox.tcl
proc drawbox {xmin ymin zmin xmax ymax zmax} {
draw color blue
draw line " $xmin $ymin $zmin " " $xmax $ymin $zmin "
draw line " $xmin $ymin $zmin " " $xmin $ymax $zmin "
draw line " $xmax $ymin $zmin " " $xmax $ymax $zmin "
draw line " $xmin $ymax $zmin " " $xmax $ymax $zmin "
draw line " $xmin $ymin $zmax " " $xmax $ymin $zmax "
draw line " $xmin $ymin $zmax " " $xmin $ymax $zmax "
draw line " $xmax $ymin $zmax " " $xmax $ymax $zmax "
draw line " $xmin $ymax $zmax " " $xmax $ymax $zmax "
draw line " $xmin $ymin $zmin " " $xmin $ymin $zmax "
draw line " $xmin $ymax $zmin " " $xmin $ymax $zmax "
draw line " $xmax $ymin $zmin " " $xmax $ymin $zmax "
draw line " $xmax $ymax $zmin " " $xmax $ymax $zmax "
}
# 所使用到的 vmd 内置语法为:
# draw line {x_1 y_1 z_1} {x_2 y_2 z_3} width 2
# 在(x_1,y_1,z_1)和(x_2,y_2,z_2)之间绘制粗度为2的连线。末尾甚至可以加上 style dashed 要求绘制虚线。
# 这个脚本的目的:定义绘制矩形盒子的命令(颜色为蓝色)。
# 输入例如 drawbox -2.0419 -5.9055 -3.7916 2.0420 5.9055 3.7916 即可绘制
ex.11.19 boxsel.tcl
proc drawbox {xmin ymin zmin xmax ymax zmax} {
draw color blue
draw line " $xmin $ymin $zmin " " $xmax $ymin $zmin "
draw line " $xmin $ymin $zmin " " $xmin $ymax $zmin "
draw line " $xmax $ymin $zmin " " $xmax $ymax $zmin "
draw line " $xmin $ymax $zmin " " $xmax $ymax $zmin "
draw line " $xmin $ymin $zmax " " $xmax $ymin $zmax "
draw line " $xmin $ymin $zmax " " $xmin $ymax $zmax "
draw line " $xmax $ymin $zmax " " $xmax $ymax $zmax "
draw line " $xmin $ymax $zmax " " $xmax $ymax $zmax "
draw line " $xmin $ymin $zmin " " $xmin $ymin $zmax "
draw line " $xmin $ymax $zmin " " $xmin $ymax $zmax "
draw line " $xmax $ymin $zmin " " $xmax $ymin $zmax "
draw line " $xmax $ymax $zmin " " $xmax $ymax $zmax "
}
# 先定义矩形盒子的绘制命令 drawbox
# 需手动输入选择区域中最小的 xyz 原子和最大的 xyz 原子坐标 {x_min y_min z_min x_max y_max z_maxs}
proc boxsel {region} {
# 定义 boxsel 过程,届时需要输入选择语句
set sel [atomselect top $region]
set tmp [measure minmax $sel]
# vmd 内置命令, measure minmax $sel 可显示 $sel 里面 x、y、z 坐标最小和最大的原子的坐标
# 此时返回的坐标类似于 {{x_min y_min z_min} {x_max y_max z_max}},为了便于分别,分别定义 minl 和 maxl
set minl [lindex $tmp 0]
set maxl [lindex $tmp 1]
set xmin [lindex $minl 0]
set ymin [lindex $minl 1]
set zmin [lindex $minl 2]
set xmax [lindex $maxl 0]
set ymax [lindex $maxl 1]
set zmax [lindex $maxl 2]
# 分别抓取,并构造出满足上述定义的 drawbox 命令
drawbox $xmin $ymin $zmin $xmax $ymax $zmax
}
# 脚本目的:根据 ·指定区域· 的原子最大、最小 xyz 坐标,绘矩形盒子将之扩住。
# 此脚本的使用方法:例如 boxsel "resname MOL"
# 在脚本撰写上来说,需要先定义 drawbox 命令
ex.11.20 drawaxes.tcl
set len 40 ;# 先设置轴的长度
set len2 [expr $len+40/10]
# len2 是轴上多出来的箭头的长度,一般设置为len 的 1/10
# 但由于这里是空间坐标上的,因此需要将 len2 定义为 len 加上 len 的 1/10,即 len2 = len + len/10 = len + 40/10
# 这里还涉及到了算符的优先级,这里/优先计算,因此返回 len2 为 44
# 建议写成 set len2 [expr $len + $len/10]
# 如果是想先算 $len+40 的话,则要写成 set len2 [expr ($len+40)/10],这样就会先算 $len+40 的结果,再除以 10,得到 len2 为 8
# expr ($len+40)/10 也可以写成 expr [expr $len+40]/10,expr 的嵌套也是允许的
draw color red
draw cylinder "0 0 0" "$len 0 0"
draw cone "$len 0 0" "$len2 0 0" radius 2 resolution 20
# cone 就是从 ($len,0,0) 到 ($len2,0,0) 的一个圆锥,radius 是底面半径,resolution 是圆锥底面圆的分段数,越大越圆润
draw color green
draw cylinder "0 0 0" "0 $len 0"
draw cone "0 $len 0" "0 $len2 0" radius 2 resolution 20
draw color blue
draw cylinder "0 0 0" "0 0 $len"
draw cone "0 0 $len" "0 0 $len2" radius 2 resolution 20
# 这个脚本的目的:在 3D 窗口中绘制较大的笛卡尔坐标
# 上述用到的 cyinder 用于绘制圆柱,cone 用于绘制锥形,由此不难想象其坐标轴的样子是如何的
ex.11.21 alignbond.tcl
proc alignbond {ind1 ind2} {
set atm1 [atomselect top "serial $ind1"]
set atm2 [atomselect top "serial $ind2"]
# 抓取选区的原子
set vecx [expr [$atm2 get x] - [$atm1 get x]]
set vecy [expr [$atm2 get y] - [$atm1 get y]]
set vecz [expr [$atm2 get z] - [$atm1 get z]]
# 获取上述两个原子连线的矢量
set sel [atomselect top all]
# 抓取整个选区
$sel move [transvecinv "$vecx $vecy $vecz"]
# 使用到 vmd 的内置命令,这里分别是 atomselect0 move [4x4矩阵] 对坐标系的坐标进行变换
# transvecinv {vec1 vec2 vec3} 返回将此向量指向 x 轴所需要的变换矩阵
}
# 此脚本目的:定义让指定两个原子对应的化学键平行于 x 轴的命令
# 使用方法:alignbond [原子index1] [原子index2]
# 更详细的推文介绍:让指定化学键平行于笛卡尔坐标轴的方法(www.sobereva.com/177)
# 有了这个脚本,就可以精确的让指定的化学键平行于坐标轴,而不用自己手动拖动(以免造成误差)
# 事实上,这两个原子也可以没有实际成建,他们仅仅只是用于定义连线的矢量而已
Ex.11.22 showtrj.tcl and showtrj2.tcl
proc showtrj {selection fps1 fps2 skip} {
set selnow [atomselect top $selection]
set selnext [atomselect top $selection]
# 先声明好后续的两个变量的取值的选区
set natm [$selnow num] ;# natm 作为计数器,通过 atomselect0 num 来获取选取原子的原子数量
for {set ifps $fps1} {$ifps<$fps2} {incr ifps $skip} {
$selnow frame $ifps
$selnext frame [expr {$ifps+$skip}]
# 分别修改其两个选区不同的帧号,且由于 for 循环,ifps 每轮增加的时候,下一个帧号也会更新
for {set iatm 0} {$iatm<$natm} {incr iatm} { ;# for 循环遍历选区内的所有原子
set xyznow [lindex [$selnow get {x y z}] $iatm]
set xyznext [lindex [$selnext get {x y z}] $iatm]
draw color red; draw line $xyznow $xyznext width 3
# 这个for循环以及这三行,是这个代码的精髓
# 由于遍历 iatm,因此可以通过 atomselect0 get {x y z} 获取原子坐标,但往往给出的是所有原子坐标的 list,再通过 lindex 抓取
# 成功抓取遍历的原子不同帧号的坐标后存放于 xyznow 与 xyznext
# 随后使用绘图命令,draw line 连线
}
puts "Frame $ifps done"
# 建议加上:
# $selnow delete
# $selnext delete
}
}
# 这是一个非常有用的脚本;
# 此脚本目的:将 ·运动轨迹连线· 来描绘所有粒子的运动路径
# 使用方法:showtrj [选择范围] [初始帧] [结束帧] [绘制频率]
# 使用输入举例:showtrj alpha 1 50 5
# ps:file/VMD/scripts/showtrj2.tcl 还会同时在每个点绘制小球
The following is a version of the showtrj2.tcl:
proc showtrj2 {selection fps1 fps2 space} {
set selnow [atomselect top $selection]
set selnext [atomselect top $selection]
set natm [$selnow num]
for {set ifps $fps1} {$ifps<$fps2} {incr ifps $space} {
$selnow frame $ifps
$selnext frame [expr $ifps+$space]
for {set iatm 0} {$iatm<$natm} {incr iatm} {
set xyznow [lindex [$selnow get {x y z}] $iatm]
set xyznext [lindex [$selnext get {x y z}] $iatm]
draw color red; draw line $xyznow $xyznext width 2
draw color orange; draw sphere $xyznext radius 0.15
# 这里我们可以学到画图时的上色逻辑,对于线而言是红色的,对于后续的球而言则是橙色的
if {$ifps==$fps1} {draw sphere $xyznow radius 0.15}
# 上面这行是为了弥补绘球的逻辑,因为上面都是绘制下一步的,而初始第一帧是没有所谓下一步的
# 由于 for 循环的 ifps 是从初始帧开始的,因此在第一轮循环时,ifps 就等于初始帧,此时就会在每个点上画一个球,后续循环则只在后续点上画球
}
puts "Frame $ifps done"
}
}
# 脚本目的:将 ·运动轨迹连线· 来描绘所有粒子的运动路径,此脚本会在每个点绘制小球
# 使用方法:showtrj [选择范围] [初始帧] [结束帧] [绘制频率]
# 使用输入举例:showtrj alpha 1 50 5
# ps:file/VMD/scripts/showtrj2.tcl 还会同时在每个点绘制小球
ex.11.23 linkCOM.tcl
draw delete all
draw color orange
# 先清理 top 体系的绘图层,并定义接下来的绘制的圆球的颜色
set nres [llength [lsort -unique [[atomselect top all] get residue]]]
# 上面这行代码有必要和下面的 set sel [atomselect top "resid $ires"] 结合起来看
# residue 获得残基编号,从0开始;resid 也是获得残基编号,从1开始,若结构文件里有残基号则与之一致
# residue 是 VMD 内部数据库另外给给残基分配的连续索引(Index),绝对连续,绝对不会断层。
# resid 是你在加载的坐标文件(比如 PDB 或 GRO 文件)里,真实写在那里的残基编号,例如 PDB 文件中间甚至可以有断层(比如 1, 2, 5, 6...)
# 上面这行代码实现了:自动获取当前整个体系中包含的“残基总数”,并将其赋值给变量 nres
# 先看 atomselect top all,选择全部原子,然后 atomselect0 get residue 获得 residue 残基编号,从0开始
# 由于获得的 residue 往往是 0 0 0... 1 1 1...(例如第一个 residue 是水分子,编号是0,那么其 H H O三个原子的 residue 编号都是0,而相同的水分子有一样的残基名但有不一样的残基编号)
# 我们只需要统计总的独立的残基数有多少个,因此 lsort -unique list 可以剔除掉重复的列表元素,得到 0 1 ...排序
# 又因为后续的 resid 从1开始,因此需要在加个 llength list获取列表长度,间接获得 resid 的最大值(residue 则会少1)
for { set ires 1 } { $ires <= $nres } { incr ires } {
# 遍历不同的残基编号(≦最大的残基编号);这里对结构文件有要求:必须高规整性,必须residue 0能对应resid 1,以此类推
# 这是由于 gmx 经过前处理生成的结构文件通常是 .gro 格式
# .gro 格式有一个强制的特性:它会无视原来 PDB 里的多条链和复杂编号,强制把全体系所有分子的 resid 重新从 1 开始、连续不断地排下去(1, 2, 3... 一直排到几万)
# 如果用外部的结构文件(例如 .pdb)的 resid,则需检查能否一一对应,是否有出现 resid 断层(如44跳到55),又或者不同 chain 重新计数不同的 resid (如 chain A 从 resid 1开始,chain B 从 resid 1开始)
# 若出现上述的那些 resid 不规整,无法适用情况,则十分有必要将脚本改为:
# for { set ires 0 } { $ires < $nres } { incr ires } {...}
# set sel [atomselect top "residue $ires"]
# 借助 vmd 独立的计数器 residue 才不会编号出错。
# 需要注意:如果是 residue 循环,循环条件应改为 < $nres 而不是 <= $nres,因为它是从 0 开始计数的。
set sel [atomselect top "resid $ires"]
set COM [measure center $sel weight mass] ;# 获取该选区的质心坐标,返回一个 {x y z} 的 list
set x($ires) [lindex $COM 0]
set y($ires) [lindex $COM 1]
set z($ires) [lindex $COM 2]
# 将各个残基质心的笛卡尔坐标写入 x、y、z 数组并绘制圆球,半径为1.5
# 如果提示 can't read "x(1)": variable isn't array,往往是VMD Tk 终端的内存残留上出现了问题
# 如果一个变量已经被定义成了普通变量(标量),你就绝对不能再用带括号的方式 $x(...) 把它当成数组来操作
# 解决方法:在 VMD Tk 终端里,先 unset x y z 来清除掉之前的变量定义,再重新运行脚本即可
draw sphere "$x($ires) $y($ires) $z($ires)" radius 1.5
$sel delete ;# 完成绘图目的后即时释放内存
}
draw color yellow ;# 定义连线的颜色
set crit 10 ;# 设置连线距离阈值(埃)
for { set ires 1 } { $ires <= $nres } { incr ires } {
for { set jres [expr $ires+1] } { $jres <= $nres } { incr jres } {
# 遍历所有残基对,这是一种遍历所有非重复对(N*(N-1)/2 次操作)的经典算法结构
# 你可能会困惑:如果是 resid 4 和 resid 9质心距离较近,那么这时候循环 n 和 n+1 岂不是循环不到了?
# 事实上,对于这类双循环的运行逻辑,set jres [expr $ires+1] 只是起跑线。
# 意思是,jres 从 ires 的下一个数字开始,只要没跑到 nres,那么 jres 的遍历就不会结束。因此是循环到 n 时,n 配对的 n+1 将从 n+1 循环到 n_max 为止
set dx2 [expr ($x($ires)-$x($jres))**2]
set dy2 [expr ($y($ires)-$y($jres))**2]
set dz2 [expr ($z($ires)-$z($jres))**2]
set dist [expr sqrt($dx2+$dy2+$dz2)]
# 计算上一部分的质心距离,若下面小于判断的距离阈值,则绘制圆柱连线
if { $dist<$crit } {
draw cylinder "$x($ires) $y($ires) $z($ires)" \
"$x($jres) $y($jres) $z($jres)" radius 0.5 ;# 连线的圆柱半径
# 若报错 need three numbers for a vector,往往是复制粘贴该代码到 Tk console 时,反斜杠后面的换行符被忽略,于是续行失败
# 这时候建议把上面的反斜杠删去
}
}
}
# 此脚本的目的:在 VMD 中将距离较近的分子质心连线的脚本(可视化哪些残基较为接近)
# 此脚本可以在体系中每个残基质心位置绘制一个圆球,并将质心距离小于特定值的质心之间连线,便于直观考察哪些残基之间距离比较近。
# 详细介绍的参考博文:sobereva.com/410
# 每次运行此脚本,就会自动删掉之前绘制的图形重新绘制一遍。如果是轨迹,当前在哪帧,就会按照哪帧的结构来绘制。
# 事实上,该脚本使用了双重 for 循环在 Tcl 层面上计算所有质心对的距离(复杂度为 O(N^2))。对于几千个氨基酸的体系,这会非常慢。
# 性能优化上,更为现代的角度,可以考虑 measure contacts 调用底层 cpp 进行优化
# 这个代码在 Tk console 运行时常遇见两个 bug:
# 1. can't read "x(1)": variable isn't array
# 解决方法:先 unset x y z 来清除掉之前的变量定义,再重新运行脚本即可(Tk console 有残留的 x 变量的定义)
# 2. need three numbers for a vector
# 解决方法:把 draw cylinder 后面的反斜杠删去,确保续行成功(由于复制粘贴时无法正常识别到反斜杠后的换行符)
ex.11.24 numinterbond.tcl
set i 27
set j 45
set n 1
while {1} {
# while {1} {...} 则代表判据永远为真 True,即 while {True} {...},一般代表无限循环。往往依赖内部条件才能跳出循环的无限循环。在 tcl 语言脚本中,while {1} {...} 一般会搭配 break 编写。
# 这里也可写 while {$n >= 1} {...}
# 此脚本的思路就是从 $i 原子间隔 $n 个化学键的原子的选区出发,循环遍历在该化学键数目内的 list 中是否含有 $j 原子
puts "Testing $n bonds..." ;# 这里将打印目前循环的间隔的键是多少
set sel [atomselect top "withinbonds $n of index $i"]
# withinbonds $n 的严格含义是“与目标原子相隔 $n 个化学键以内(包含正好 $n 个,以及少于 $n 个)的所有原子”
set exist [lsearch [$sel list] $j]
# 关于 lsearch 的相关知识可以查阅 tcl_note.md 第4.9小节
# lsearch [$sel list] $j 查询满足与 $i 原子化学键间隔 $n 个及以内的选区里,是否列表元素中有 $j。\
这里默认查询方式是 -glob,如果说查询得到返回其列表元素的索引 index,如果查询不到则一律返回-1
# 将其返回值存储为 exist,用于后面判据(只需要判断不是-1即可认为有匹配的 $j)
if { $exist!=-1 } {
puts "There are $n bonds between the two atoms"
break
# 如果在当前化学键间隔下遍历到了 $j,则 break 跳出循环并终止
}
incr n ;# 否则继续增加间隔的键数
}
# 这个脚本的目的:计算 index 为27和45的两个原子间间隔的化学键数
# 如需更换不同的 index atom,则自行修改 i 和 j 的默认值
# 这个脚本实际上有个问题,那就是 n 有可能实际循环到9999+,这时候应该最好是 while 的 boolean 增加其他的判断
ex.11.25 secstr_ratio.tcl
# 这个脚本的思路:VMD 获取的结构代号(如 C, E, T 等)实际上是利用底层算法识别出的蛋白质空间形态。通过 switch 语句,将这些形态分类并计数。
set residall [lsort -unique [[atomselect top protein] get resid]]
# lsort 对数组进行排序,参数 -unique 要求对列表元素去重(因为我们统计的是残基,但atomselect选取的是原子,必然会有一个片段单元有好几个resid一样的原子,因此需要去重),随后将这个 list 存到 resiall
# 此脚本由于要计算蛋白质,因此选区默认选取 protein,获得从1开始的残基编号(1-based)
# 由于后续我们需要使用 VMD 中的形态代号,下面我们先设定计数器,然后注释里会给出其相应的形态代号以及生物意义
set nres [llength $residall] ;# 这里计算的是选区内的蛋白质所含有的总的残基数(通常是氨基酸数),用于衡量蛋白质的长度
set ncoil 0 ;# C - Random Coil / 无规则卷曲;这是蛋白质中没有固定规则结构的柔性区域
set nextend 0 ;# E - Extended conformation / β-折叠或延伸链;氨基酸链伸展排列,常与其他链平行或反平行靠拢形成坚固的“平面板”(β-折叠),为蛋白提供强大的骨架支撑
set nturn 0 ;# T - Turn / 转角;蛋白质链发生方向扭转或折返的短小区域,是让长长的蛋白质链能够折叠成紧凑球体的关键
set nbridge 0 ;# B - Isolated Beta-bridge / 孤立 β-桥
set nalpha 0 ;# H - Alpha Helix / α-螺旋;蛋白质中最常见、最经典的弹簧状卷曲结构,既稳定又具有一定的弹性
set n310h 0 ;# G - 3-10 Helix / 3-10 螺旋;一种比经典α-螺旋更细、缠绕得更紧的螺旋,经常作为过渡结构出现在α-螺旋的开头或结尾处
set nPih 0 ;# I - Pi-helix / π-螺旋;一种比经典α-螺旋更粗、更松散的短螺旋,比较罕见,但往往出现在蛋白质发挥核心功能的关键结合位点上
# 上述都是一堆计数器的预设
foreach resid $residall {
set ressec [lindex [[atomselect top "resid $resid"] get structure] 0]
# 这是这个代码较为关键的一行,ressec 意思为 residue second structure 残基的二级结构
# 1. 由于上面的 residall 是全部的不重复原子去重后的残基编号,是一个大 list
# 而 foreach 可以遍历该 list 中的所有 resid 到变量 $resid 中,随后再选择语句 "resid $resid" 选定指定的残基号
# 2. $sel get structure 这个 vmd 内置命令可以获得二级结构;
# 然而,$sel get [property] 获得的是一个满足该条件的原子 list,例如一个丙氨酸正好处于一段 α-螺旋(形态代号为 H)中, 则返回:{H H H H H H H H H H}(列表中有 10 个 H,分别对应这个残基里的 N、CA、C、O 以及侧链原子)
# 3. 由于上述返回的是满足条件的原子的 list,因此只需要 lindex list 0 抓取一个元素即可(因为都会一样)
# 4. 最后,将抓取的元素存为 ressec,代表着这个 resid 对应的二级结构的形态代号
puts "$resid $ressec" ;# 打印出 [残基号] [二级结构的形态代号]
switch $ressec {
# switch 语句的使用方法可以回顾 tcl_note.md 第5.1.2小节
# switch 默认 -exact 的匹配方式,遍历到了相应的计数器就加1
C {incr ncoil}
E {incr nextend}
T {incr nturn}
B {incr nbridge}
H {incr nalpha}
G {incr n310h}
I {incr nPih}
}
}
# 下面相较于卢老师写的原版,expr 部分增加了 {} 来调用底层的 cpp 进行计算
puts "Number of protein residues: $nres"
puts "Number of coil: [format %5d $ncoil] Ratio: [format %4.1f [expr {double($ncoil)/$nres*100}]] %"
puts "Number of extended: [format %5d $nextend] Ratio: [format %4.1f [expr {double($nextend)/$nres*100}]] %"
puts "Number of turn: [format %5d $nturn] Ratio: [format %4.1f [expr {double($nturn)/$nres*100}]] %"
puts "Number of bridge: [format %5d $nbridge] Ratio: [format %4.1f [expr {double($nbridge)/$nres*100}]] %"
puts "Number of alpha helix:[format %5d $nalpha] Ratio: [format %4.1f [expr {double($nalpha)/$nres*100}]] %"
puts "Number of 3-10 helix: [format %5d $n310h] Ratio: [format %4.1f [expr {double($n310h)/$nres*100}]] %"
puts "Number of Pi-helix: [format %5d $nPih] Ratio: [format %4.1f [expr {double($nPih)/$nres*100}]] %"
# 这里的 format 的排版格是:%5d 前面的二级结构出现数量的参数输出格式为5位的十进制整数,如果不足则用空格来进行填充
# 后面的二级结构出现比例的排版格式是 %4.1f 浮点数格式,总的4位(包含小数点),保留小数点后1位,因此整数部分为2位,如果不足则用空格来进行填充
# 这个脚本的目的:计算蛋白质中各种二级结构出现的比例。
Ex.11.26 slview.tcl with the eval command
eval:- The syntax is as follows:
eval arg ?arg ...? evalThe command is one Used to construct and execute commands for TCL scripts- It is You can take one or more parameters and then combine all the parameters into a script separated by spaces, and then you can devaluate that script.
- In general,
evalThe function of the code is to force a string of text into a line of code and execute it. similar to string hard when a script is executed, it is usually done with the body of pure text after the following content is fully introduced and then executed with the body of pure text. Otherwise, sometimes we read the contents of a file and it is easy to integrate them into strings!
- The syntax is as follows:
getsIt is the core command for reading files in a row in Tcl. It is commonly used in the language ofgets <文件句柄> <变量名>The keyword is usually read in the file and then temporarily stored in the variable name after it.getsThe read-through punch is a line-by-line reading, assigning values to variables and executing a line of commands, which automatically moves a line down the file.
# 定义 sv 过程(保存 top 体系的视角和图形窗口尺寸)
proc sv {} {
set myfile [open view.txt w] ;# 写操作打开 view.txt,并且颁布文件ID
set view [molinfo top get {center_matrix rotate_matrix scale_matrix global_matrix}]
# vmd 内置命令: molinfo top get [property] 可以获得 top 体系的各种属性
# 上行代码提取的是 VMD 底层用来控制三维物体空间位置的 四个 4x4 变换矩阵 \
center_matrix rotate_matrix scale_matrix global_matrix
# center_matrix (居中/平移矩阵):记录了分子在 X、Y、Z 轴上被移动了多少距离(决定了分子在屏幕上的具体方位)
# rotate_matrix (旋转矩阵):记录了分子围绕各个轴旋转的角度。你在图形界面里用鼠标随意拖拽分子转动,改变的就是这个矩阵
# scale_matrix (缩放矩阵):记录了分子被放大或缩小的倍数(对应你滚动鼠标滚轮的操作)
# global_matrix (全局变换矩阵):用于处理整个场景的全局宏观视角变换
# 在 VMD (以及底层的 OpenGL 绘图引擎) 中,在屏幕上看到的任何一个分子的姿态,本质上都是分子原始坐标经过上述四个矩阵进行数学乘法运算后的结果
puts $myfile $view ;# 往 view.txt 中写入上述的 $view
puts $myfile [display get size]
# display get size 这个命令用于获取当前 VMD 图形显示窗口的实际像素尺寸(例如返回 {1024 768},则实际文本中则写入字符串 1024 768)
# 保证每张图的像素长宽严格一致是排版的基本要求,确保后期渲染的高度一致性
close $myfile ;# 关闭文件句柄(File Handle)并刷新缓冲区(Flush Buffer)
}
# 注意上述 sv 过程写入 view.txt 文件中的第一行是四个 4x4 矩阵;第二行是窗口尺寸大小
# 定义 lv 过程(读取之前 sv 过程保存的视角文件)
proc lv {} {
set myfile [open view.txt r] ;# 注意这里是读操作
# gets 是 Tcl 中用于逐行读取文件的核心命令。它的常见语法是 gets <文件句柄> <变量名>
# 一般是读取文件里的句柄,然后临时存于后面的变量名中
# 下面这两行的顺序很重要,因为 gets 是一行一行地读取,赋值给变量并执行完一行命令后,文件内部的“阅读指针”会自动下移一行
# 因此,这里实际上不需要全局变量 global view 或 winsize 的声明
gets $myfile view ;# 这里 gets 读取了前面 sv 过程写于第一行中的4个4x4矩阵,并将这一行的文本赋值于 view 变量中
gets $myfile winsize ;# 前面 sv 过程的第二行
# 这里 view 和 winsize 的名称都可以任意更改(他们只是 gets 工具人),其分别应用于后续两行不同的命令:
# set {矩阵1 矩阵2 矩阵3 矩阵4} $view,注意这里四个矩阵的名字不能更改,是要往 vmd 里设置的内部参数
# display resize $winsize 则将窗口尺寸设置为 sv 过程中写入的第二行
close $myfile ;# 颁布文件句柄的使用完都要刷新缓冲区
eval "display resize $winsize"
# eval 将后面的内容作为整个命令来执行(eval 可以接收多个参数,然后所有参数以空格隔开组合成一个脚本)
# 因此,这里 eval 的作用是将一串文本强制拼凑成一行代码并执行它(类似于字符串当成脚本执行)
# 这是由于变量 $winsize 里面装的是一个包含空格的字符串(比如 "1024 768")
# 因为我们是通过 gets 来获取文本第二行的,本质上 winsize 存储的是一个字符串
# 如果直接写 display resize $winsize,Tcl 解释器可能会把 "1024 768" 当成一个不可分割的单一参数传给 resize,从而 vmd 报错
# 例如 display resize "1024 768" 则直接报错!因为 vmd 要接收两个参数
# 因此,为了能让从文本读取的一行数值不被当作一长长的字符串
# 使用 eval 后,Tcl 会先把双引号里的变量替换掉,得到纯文本的 "display resize 1024 768",然后再把这句纯文本作为命令去执行
# 每个 ID 都赋予相同的视角
for {set i 0} {$i<[molinfo num]} {incr i} {
# molinfo num 的作用是显示并得到当前体系的总数目,for 循环就是为了赋予每个 ID 相同的视角
set id [molinfo index $i] ;# molinfo index/top 用于显示 index/top 体系在 VMD main 窗口中的序号,从0开始记
molinfo $id set {center_matrix rotate_matrix scale_matrix global_matrix} $view ;# 注入恢复视角所必需的四个矩阵
}
}
# 这个脚本的目的:自定义保存视角和恢复视角的命令。
# 使用方法:输入 sv,可将当前 top 体系的视角和图形窗口尺寸保存到当前目录下的 view.txt 中
# 输入 lv 可从中读取信息恢复当前所有体系的视角,同时还原图形窗口尺寸
# 利用这个脚本,可以在绘制一批体系时保证视角、图像尺寸精确一致
Ex.11.27 Chemical key count and join command in computing systems
expr (join [[atomselect top all] get numbonds] +)/2
The above command returns to a system of isolated ethylene molecules. 7 (Because the number of chemical bonds is 7)
Why return to the ethanol molecule 7?
The specific interpretation is as follows:
[[atomselect top all] get numbonds]First, the top system gets all the atoms in the polling station, then the top system gets all the atoms.$sel get numbondsThe list of all atomic integers. For this case, we're back.4 1 1 1 4 1 1 1(It is easy to understand that the carbon atom of ethylene has four entropy bonds and the H atom has one, according to the order of its entropy, as shown in the list above.) I am reminded once again:$sel get [property]The only thing that is available is the information about the properties of all the atoms that meet the conditions! )join list +: Thejoincommand is applied here, and can be seen The following article is a summary of the results: ;; briefly,joinThe command can combine all elements in the list together in a certain way;; for example the specific way here is+, so each list element in list{4 1 1 1 4 1 1 1}will be connected by+and thus return4+1+1+1+4+1+1+1- Finally, use
exprto perform actual calculations, remember to add/2to avoid repeating statistics
In fact, the above example can also be implemented by vecsum adding a conjunction: here vecsum: adding vector elements:
expr [vecsum [[atomselect top all] get numbonds]]/2
Ex.11.28 xyz2graph.tcl with the glob command
glob The rules of naming are very similar to what we're doing here. The global coordinate matching in section 4.9 。
# 下面这几行是设置渲染前的基本设置
mol default style CPK ;# mol 可对体系进行操作与设置显示方式
color Display Background white ;# 设置背景颜色为白色
display depthcue off ;# 避免图片雾蒙蒙的
axes location Off ;# 关闭 vmd 中坐标轴的显示
# 下面这段的是渲染的选择、导出同名格式 .tga 文件的逻辑
set allfiles [glob *.xyz]
# glob 是通配符匹配模式,我们在 tcl_note.md 的第4.9小节提到过
# 这里是 glob 当前目录下所有以 .xyz为后缀的文件并存为 allfiles(可以 pwd 查询当前目录)
# *:代表任意长度的任意字符串(包括空字符串)
foreach file $allfiles {
# 这段的 foreach 循环的逻辑本质上是借用所有当前目录下后缀为 .xyz 文件的名字,将名字存放至 $file 中进行遍历
mol new $file ;# 创建名为 $file 的新分子
puts "Rendering $file..." ;# 打印目前渲染的文件名
render TachyonInternal $file.tga ;# 以 TachyonInternal 渲染为 $file.tga 文件
mol delete top ;# 由于上面 mol new $file 势必会成为最新的 top,为了避免内存被占满,及时删除前面创建的体系
}
# 此脚本的目的:将当前目录下所有 xyz 文件渲染成同名但带 .tga 后缀的球棍模型(CPK)的图片
# 脚本名的意味:.xyz文件转换为图片
It is easy to see that if the script is executed, the output file name will become molecule.xyz.tga (((with two backlinks) after the original file is called molecule.xyz, and this line of code is executed. Although this does not affect the view, it is slightly redundant and unpretentious in file management! If you want to generate a very clean molecule.tga, you can use Tcl's file rootname command to strip the original .xyz backlinks. Here we propose an improved version that uses the file rootname $file command in tcl:
#####渲染出的文件名无.xyz的改良版本####
mol default style CPK ;# mol 可对体系进行操作与设置显示方式
color Display Background white ;# 设置背景颜色为白色
display depthcue off ;# 避免图片雾蒙蒙的
axes location Off ;# 关闭 vmd 中坐标轴的显示
set allfiles [glob *.xyz]
foreach file $allfiles {
mol new $file
puts "Rendering $file..."
set basenam [file rootname $file] ;# 通过 tcl 中的 file rootname 来获取文件名(去原后缀)
render TachyonInternal $basenam.tga ;# 此时渲染出来的文件名不会再包含 .xyz
mol delete top
}
Ex.11.29 Contigfrag.tcl & combine.sh
Before we begin to introduce this script, it is necessary to discuss what the purpose of this script is in real-world research: what is business logic and business needs? )。
Background: The first line of the normal .xyz file is
原子总数, the second line is注释行(don't want to write it is empty), and the third line starts with[原子名] [x] [y] [z]
Writing The purpose of this script is to have the atomic sequence number in each segment of the file .xyz continuous.,But there is no atomic numbering sequence in normal .xyz, what is the meaning of such an order?
In fact, the so-called continuity actually refers to It's not Add a row 1, 2, 3 to the .xyz file... It is a syntax of the sequence of the hydrogen physics lines that are used to align the atoms of the same fragment in the text. 。
Although standard .xyz The document does not write the serial number, but when programming and software read, the string string string itself is the atomic serial string (the implicit index). When any software (such as VMD, GROMACS, Gaussian) or programming language (Python, Tcl) reads standard .xyz files, they all follow a pattern of code. Rules for implicit indexing :
- The first line of the read coordinate (for .xyz, the number of lines that read the coordinate starts from the third line) is assigned to it in memory by Index = 1 ((or 0))
- The second line of the coordinates read, and assigned Index = 2
Suppose you have a system that contains two water molecules (H2O_A and H2O_B) if the file is in disordered order (non-consecutive):
行1:O (属于水A) -> 软件内部Index 1
行2:O (属于水B) -> 软件内部Index 2
行3:H (属于水A) -> 软件内部Index 3
If the file is in sequence by fragment:
行1:O (属于水A) -> 软件内部Index 1
行2:H (属于水A) -> 软件内部Index 2
行3:H (属于水A) -> 软件内部Index 3
The atomic sequence of the corresponding fragments in a physical sense has several advantages:
- Selection Logic (Selection Logic) is a method of selecting the number of atomic cuts and sequences. :
- Continuity: If you want to do a quantum chemistry calculation on the first water molecule alone, all you need to do is write in the input file: calculate atom 1-3 (which is an extremely efficient continuous array slice in the program)
- Inconsecutive: If the atom is scattered, you have to write: calculate atom 1, 5, 9. If the system had tens of thousands of atoms, this inconsistent indexing would make writing all subsequent scripts extremely painful, even exceeding the support limit for some outdated computing software.
- Topology generation is a method of topology generation and key judgement. :
- Many software rely on the continuity of the sequence of sequences of the sequence and the sequence to guess the chemical keys when reading pure
.xyzfiles without topological information.。 If a large molecule (like a protein chain) is The atomic number is cut to 78 in the file, and the software is easily confused when it comes to guess. The first is that the "symmetrical" and "symmetrical" chemistry of the whole simulation box could be drawn.
- Preparation for
.gro/.pdb:
.xyzThe format is often an intermediate transition format.- Subsequent research usually converts
.xyzto a file containing residual information.groor.pdbfor molecular dynamics simulation. - These advanced formats such as
.grostrictly require that the same residual/fragment atoms must be physically adjacent to each other.! if.xyzIt's not treated..groThe problem is that the resulting topological relationship is a corresponding error.
part A: contigfrag.tcl
set ifrag 0 ;# ifrag 作为不同片段的编号计算器,从序号0开始哪部分
while { 1 } {
# while {1} {...} 则代表判据永远为真 True,即 while {True} {...},一般代表无限循环。
# 往往依赖内部条件才能跳出循环的无限循环。在 tcl 语言脚本中,while {1} {...} 一般会搭配 break 编写。
set sel [atomselect top "fragment $ifrag"]
# 选择 top 体系的第 $ifrag 个片段,这里用到新的选择语句 "fragment $i"
if { [$sel num]==0 } {
# 由于目前没有明确的命令可以获取最大序号的片段是多少,因此这里利用 if 语句遍历到所选编号的片段选区原子数量为0,则说明没有后续的片段了
break ;# 因为选区原子检测为0,因此超过片段数目上限,结束循环
} else {
puts "Fragment $ifrag, number of atoms: [$sel num]"
# 打印结果:[目前的片段编号(0-based)] [此片段的原子数量]
$sel writexyz "[format %05d $ifrag].xyz"
# 使用 $sel writexyz "diy.xyz" 把当前所选原子以 xyz 格式(writexyz)写入到当前文件夹下的 diy.xyz 中
# 这里规定了写入的文件名字的格式是 $ifrag 参数为 %05d 十进制整数保持五位数,若有缺位则用0补齐,后缀为.xyz
# 所写入的文件格式是 xyz (实际上可以是 gro、pdb、trr等格式)
incr ifrag
}
} ;# 之后当前目录下就会有 00000.xyz、00001.xyz ...
# 此脚本的目的:让 xyz 文件中的每个片段内原子序号连续,此脚本主要是导出不同片段内原子序号 .xyz 文件
# 这个 tcl 脚本会把各个 fragment 里的原子写入到不同的 xyz 文件中,之后我们再利用 combine.sh 脚本即可合并成新的 xyz 文件,则里面的各个片段内的原子序号就是连续的了。
Since the above tcl script writes atoms in each fragment into different xyz files, then we can combine the combined.sh script into a new xyz file, so the atomic sequence of each fragment is continuous.
So, below we're going to combine.sh (based on the script of the bash interpreter)
part B: combine.sh
rm -f new.xyz # 强制删除(-f,force)当前目录下可能已经存在的 new.xyz 文件。这是为了防止多次运行脚本时,新数据追加到旧数据后面导致文件错乱。
for inf in *.xyz # 启动一个 for 循环。*.xyz 代表当前目录下所有的 .xyz 文件。
# 每次循环时,会把当前处理的文件名赋值给变量 inf。
do # do 表示循环体开始。
echo Processing $inf #在屏幕上打印出正在处理的文件名,起提示作用
awk '{if (NR>2) print}' $inf >> new.xyz # 关键
# 将 *.xyz 中第二行之后的行(即第三行开始的坐标部分)追加到 new.xyz 里
# awk 是一个强大的文本处理工具。NR 代表当前行号(Number of Record)
# if (NR>2) print 意思是:如果行号大于 2(即从第 3 行开始的纯原子坐标),就把这行打印出来
# >> new.xyz 意思是:将打印出来的内容追加(而不是覆盖)到 new.xyz 文件的末尾;
# 因为每个独立的 xyz 文件前两行都是原子总数和注释行,合并时必须把这些冗余的头部砍掉。
done # 结束 for 循环。
# 此时,new.xyz 里已经装满了所有片段的原子坐标,但缺少 xyz 格式必须的头两行(总原子数和注释行),因此下面代码是为了写上开头两行的
nline=`wc -l new.xyz |cut -d ' ' -f 1`
# 获得当前行数(即原子总数)。wc -l 是 word count 的一个选项,表示统计行数。它会输出类似 "123 new.xyz" 的结果,其中 123 就是行数。为了提取这个数字,我们用管道把 wc 的输出传给 cut 命令,cut -d ' ' -f 1 表示以空格为分隔符,提取第 1 个字段(即行数)。
sed -i '1s/^/'"$nline"'\n\n/' new.xyz
# sed -i 是流编辑器,用于直接修改文件内容
# '1s/^/' 意思是:在第 1 行的最开头(^ 代表行首)进行插入操作。
# "$nline"'\n\n/' 意思是:插入刚才算出的总原子数 $nline;
# 然后紧跟两个换行符 \n\n。
# 两个换行符就形成了一个已经写入了原子总数的第 1 行,和一个空白的第 2 行,并且指针此时停留在第三行
# 至此,上面这两行代码成功在已经写满原子坐标信息的 xyz 文件上插入了前两行,一行原子总数一行空白行
# 在当前目录下(pwd查询)创建 shell 脚本 combine.sh
# 脚本目的:执行此脚本后当前目录下的所有 xyz 文件就会合并为所需要的 new.xyz
# 此脚本要配合 contigfrag.tcl 一起使用(这个 tcl 脚本可以导出不同片段的 .xyz 文件,需配合 combine.sh 再合并成大文件)
# 补充: 正常 .xyz 文件第一行是原子总数,第二行是注释行(不想写则可空),第三行开始才是[原子名] [x] [y] [z]
In fact, we can also do without shell scripting and only use tcl scripting to achieve the following goals:
- The previous program needed Shell because the writexyz command of VMD generated an independent xyz file each time.
- In pure Tcl, we can bypass the process of generating small files, extracting the coordinates in bits directly from memory and writing them into a final new.xyz.
The following pure Tcl version addresses two main issues:
- Xyz files with sequential atomic sequences sorted and exported by clips
- No intermediate files are needed, and no Shell script support is required
#### 改进版本的 tcl 脚本的编写方式 ####
# 1. 准备工作:获取总原子数,并打开我们要写入的最终文件
set total_atoms [molinfo top get numatoms]
set outfile [open "new.xyz" w]
# 2. 写入 xyz 格式标准的前两行(替代了 Shell 里的 sed 命令)
puts $outfile $total_atoms
puts $outfile "Generated by pure Tcl script - Sorted by fragments"
set ifrag 0
# 3. 开始按片段循环
while { 1 } {
set sel [atomselect top "fragment $ifrag"]
set num [$sel num]
if { $num == 0 } {
# 如果选区内没有原子,说明片段遍历完毕,跳出循环
$sel delete
break
} else {
puts "Processing Fragment $ifrag, atoms: $num"
# 核心逻辑:直接获取该片段内所有原子的 元素名称(name)、x、y、z 坐标
set coords [$sel get {name x y z}]
# 遍历该片段的每一个原子,将其追加写入到 new.xyz 中(替代了 Shell 里的 awk 命令)
foreach atom $coords {
# 将列表中的数据分别提取出来
set atom_name [lindex $atom 0]
set x [lindex $atom 1]
set y [lindex $atom 2]
set z [lindex $atom 3]
# 下面这行是关键,因为跳过了生成小的片段文件,而是引入了标准的 .xyz 写入
# 使用标准的格式将原子坐标写入文件(%-4s 左对齐字符串,%10.5f 浮点数保留5位小数)
puts $outfile [format "%-4s %10.5f %10.5f %10.5f" $atom_name $x $y $z]
}
$sel delete ;# 及时释放内存
incr ifrag ;# 进入下一个片段
}
}
# 关闭文件并保存
close $outfile
puts "All done! Fragments successfully merged into new.xyz."
The following notes
It's all written! I hope you all learn to be happy! In fact, the official vmd web provides many programs or libraries for structural and trajectory analysis, some calling cpp and others calling python libraries. The resources can be extracted and accessed by themselves. I'm also currently learning Python, and I'll be launching a Python learning notebook that starts with 0, which is expected to be launched months after I'm optimized (which depends on whether I have plenty of time to experiment), and then maybe a Linux system learning notebook that starts with 0, but that's the end of it.