ESPResSo Summer School 2012

Similar documents
Exercise 1: Python Language Basics

Outline Basic concepts of Python language

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Introduction to Python

AWK: The Duct Tape of Computer Science Research. Tim Sherwood UC Santa Barbara

A Typing System for an Optimizing Multiple-Backend Tcl Compiler

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Introduction to Object-Oriented Programming

The Clean programming language. Group 25, Jingui Li, Daren Tuzi

6.170 Tutorial 3 - Ruby Basics

Web development... the server side (of the force)

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Exercise 4 Learning Python language fundamentals

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Running the shell. Tcl/Tk demo. Tcl stuff. Starting Tcl/Tk. If-then-else

13 File Output and Input

Introduction to Python

PHP Tutorial From beginner to master

Introduction to CloudScript

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Computational Mathematics with Python

grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print

Computational Mathematics with Python

A Crash Course on UNIX

Moving from CS 61A Scheme to CS 61B Java

Python Lists and Loops

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

Computational Mathematics with Python

FEEG Applied Programming 5 - Tutorial Session

Custom Javascript In Planning

Python Programming: An Introduction to Computer Science

Tel Scripting for Cisco IOS

TCL IVR API Version 1.0 Programmer s Guide

Microsoft Windows PowerShell v2 For Administrators

Advanced Bash Scripting. Joshua Malone

Chapter 5 Functions. Introducing Functions

[1] Learned how to set up our computer for scripting with python et al. [3] Solved a simple data logistics problem using natural language/pseudocode.

Command Line - Part 1

Chapter 15 Functional Programming Languages

Introduction to Matlab

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

An Incomplete C++ Primer. University of Wyoming MA 5310

Informatica e Sistemi in Tempo Reale

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

CS 106 Introduction to Computer Science I

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

1001ICT Introduction To Programming Lecture Notes

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Install Java Development Kit (JDK) 1.8

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Example of a Java program

J a v a Quiz (Unit 3, Test 0 Practice)

Windows PowerShell Essentials

PYTHON Basics

Final Exam Review: VBA

Object Oriented Software Design

For live Java EE training, please see training courses

Lecture 2 Notes: Flow of Control

Debugging Complex Macros

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

Number Theory and the RSA Public Key Cryptosystem

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MXwendler Javascript Interface Description Version 2.3

Facebook Twitter YouTube Google Plus Website

CellLine, a stochastic cell lineage simulator: Manual

Embedded Syslog Manager Configuration Guide, Cisco IOS XE Release 3SE (Catalyst 3850 Switches)

CHM 579 Lab 1: Basic Monte Carlo Algorithm

Maple Introductory Programming Guide

DTD Tutorial. About the tutorial. Tutorial

Object Oriented Software Design

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

Unix Scripts and Job Scheduling

PostgreSQL Functions By Example

MATLAB Basics MATLAB numbers and numeric formats

LABORATORY 117. Intorduction to VoiceXML (2)

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)


2/1/2010. Background Why Python? Getting Our Feet Wet Comparing Python to Java Resources (Including a free textbook!) Hathaway Brown School

Introduction to Python

Chapter 2 Writing Simple Programs

Moving from C++ to VBA

Programming Languages & Tools

Sources: On the Web: Slides will be available on:

Appendix: Tutorial Introduction to MATLAB

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Package HadoopStreaming

Writing cleaner and more powerful SAS code using macros. Patrick Breheny

Java Crash Course Part I

Transcription:

ESPResSo Summer School 2012 Introduction to Tcl Pedro A. Sánchez Institute for Computational Physics Allmandring 3 D-70569 Stuttgart Germany

http://www.icp.uni-stuttgart.de 2/26 Outline History, Characteristics, Online resources, Getting things running Variables, grouping and nested commands Math expressions Control structures Hands on! User defined commands Hands on! Lists and Arrays Hands on! Working with files, command line arguments, modularization Hands on!

http://www.icp.uni-stuttgart.de 3/26 History Tool command language, pronounced tickle or tee-see-ell John Ousterhout, Berkley, 1988 Originally invented for GUI programming (Tcl/Tk) Very successful language in the 1990s, adopted by many companies Not very active and popular anymore Some scientific programs still use Tcl/Tk, e.g. VMD and NAMD but most are slowly switching to Python...

http://www.icp.uni-stuttgart.de 4/26 Characteristics Interpreted scripting language, cross-platform (available almost everywhere), originally (and mainly used as) procedural Motto: Radically simple. Simple syntax No data types: all data treated as strings All operations are commands (=functions), including control structures Dynamic: everything can be (re-)defined easily, including source code Simple C-API, easy to extend and embed Free, open-source (BSD license) Current version 8.5.12 (July 27, 2012)

http://www.icp.uni-stuttgart.de 5/26 Online resources Huge documentation and resources at the official website: http://www.tcl.tk http://wiki.tcl.tk/ Built-in commands quick reference: http://www.tcl.tk/man/tcl8.5/tclcmd/contents.htm Complete tutorial: http://www.tcl.tk/man/tcl/tutorial/tcltutorial.html Nice interactive offline tutorial for self-learning, written in Tcl/Tk: http://www.msen.com/~clif/tcltutor.html

http://www.icp.uni-stuttgart.de 6/26 Getting things running... Interactive consoles: Standard interpreter: tclsh Improved console: tkcon http://tkcon.sourceforge.net/ Script files: Usual extension: *.tcl Run from command line: $>tclsh mynicescript.tcl Executable scripts: prepend script with #!/usr/bin/tclsh

http://www.icp.uni-stuttgart.de 7/26 General syntax: command argument1 argument2... Hello world! Commands end with newline or semicolon ; "" or {} used to group arguments Arguments are represented as strings Comments start with # # This is a comment puts "Hello World!" puts "This is line 1"; puts "this is line 2" puts "Hello, World - In quotes" ;# This is a comment puts "Hello, World; - semicolon inside the quotes" puts {Hello, World in Braces} puts HelloWorld puts {Bad syntax example} # *Error* no semicolon!

http://www.icp.uni-stuttgart.de 8/26 Assignement command: set set variablename value set mymessage "Hello World!" puts $mymessage set a 1.0 puts $a+$a puts $a\n$a puts \$a puts $unknownvar Variables Variable substitution: before a command is executed all variables, referenced as $variablename, are substituted for its value Backslash \ prevents subtitution of the next character. Usual backslashed codes ( backslash-sequences ) exist \n, \t,... Unset variables are reported

http://www.icp.uni-stuttgart.de 9/26 Variable substitution and argument grouping Argument grouping via "": Variable substitution and backslash-sequences work Use for strings Argument grouping via {}: No substitution nor backslash-sequences Use for code blocks set mymessage "Hello World!" puts "Say $mymessage\nnext line puts {Say $mymessage\nnext line} set myfullmessage "Say $mymessage\nnext line puts $myfullmessage

http://www.icp.uni-stuttgart.de 10/26 Nested commands Command substitution: strings within square brackets [] are evaluated as commands Variable substitution works within command substitution Command substitution works within quotes, not within braces set y [set x "def"] ;# command set returns the assigned value set x "def" set z [set y $x] set z "[set x {This is a string within braces within quotes}]" set z {[set x "This is a string within quotes within braces"]}

http://www.icp.uni-stuttgart.de 11/26 Math: expression evaluation Mathematical operations computed with the command expr Expressions mostly like C operators and mathematical functions: +, -, *, /, %, pow, sin, cos,... puts "1+1 puts 1+1 puts [expr 1+1] puts [expr "1+1 ] puts [expr 1/2] puts [expr 1./2] set x 2 puts "$x plus $x is [expr $x+$x]" puts "The square root of $x is [expr sqrt($x)]" puts [expr pow($x,2)] puts [expr ($x+1) % 2]

http://www.icp.uni-stuttgart.de 12/26 Math: type conversion and random numbers Since all data is treated as a string, numbers should be transformed to and from strings slow numerics in Tcl!!!! Explicit type conversions: abs, int, double, round Tcl provides a pseudo-random number generator: rand(), srand() puts [expr double(1)] puts [expr rand()] ;# pseudo-random number (0., 1.) expr srand(1) ;# set seed for a reproducible sequence expr rand()

http://www.icp.uni-stuttgart.de 13/26 Control structures: conditionals The if command: if expr1 then body1 elseif expr2 then body2... else bodyn The words then and else are optional The test expressions following the word if are evaluated as in the expr command set x 1 if {$x == 1} {puts "x is 1"} else {puts "x is not 1"} # mind the spaces between arguments!!! if {$x == 1}{puts "x is 1"} if {$x == 1} { ;# this is more readable in scripts puts "x is 1" } else { puts "x is not 1" }

http://www.icp.uni-stuttgart.de 14/26 Control structures: loops The while command: while test body The for command: for start test next body The command break breaks a loop. The command incr increments the integer value of a variable set i 0 while {$i < 3} {puts $i; incr i} for {set i 0} {$i<3} {incr i} {puts $i} for {set i 0} {$i<3} {incr i} { puts $i }

http://www.icp.uni-stuttgart.de 15/26 Hands on! Write a tcl script to calculate the center of mass of this system: 100 point particles in a square x-y lattice: {(X, Y)}={(1, 1); (1, 2);... ; (10, 9); (10, 10)} Mass depends on the product of the coordinates: Particles with even product X*Y have mass 2.0 ( even mass ) Particles with odd product X*Y have mass 1.0 ( odd mass ) 10 2 1......... 1 2 10

http://www.icp.uni-stuttgart.de 16/26 Adding new commands Command proc creates a new command proc commandname arguments body All variables in body are local (including arguments) except those explicitly declared global with global or upvar The new command returns to the caller a value optionally specified with return or the output of the last command found within body by default set myglobal "global"; set othervar "other" proc myproc {arg1 {arg2 "default"}} { global myglobal; puts "arg1 is $arg1"; puts "arg2 is $arg2" puts "Global var is $myglobal"; return "returned" } set result [myproc "first"]

http://www.icp.uni-stuttgart.de 17/26 Pass-by-reference to procs Pass-by-reference of variables to commands is emulated with upvar: proc myincr {arg1 {arg2 1}} { upvar $arg1 res set res [expr res + $arg2] return $res } set a 1 puts [myincr a]

http://www.icp.uni-stuttgart.de 18/26 Hands on! Rewrite your script using a command definition: Write a command to calculate the COM of the x-y square lattice system for NxN particles and arbitrary even and odd masses Particles with even product X*Y have even mass Particles with odd product X*Y have odd mass N 2 1......... 1 2 N

http://www.icp.uni-stuttgart.de 19/26 Lists A list is just an ordered collection of data, is the basic data structure in Tcl. Lists are strings, can be defined in many ways Data items can be accessed and extended with list commands: lindex, foreach, lappend, llength Lists can be nested set mylist "1 2 3", set mylist {1 2 3} puts [lindex $mylist 2]; puts [llength $mylist] foreach j $mylist {puts $j} lappend mylist 4 5 6; puts $mylist set myemptylist {} ; lappend myemptylist {Not empty anymore!!} set Nested {{1 2 3} {4 5 6}};set Nested [list "1 2 3" "4 5 6"] puts [lindex $mynestedlist 0 1]

http://www.icp.uni-stuttgart.de 20/26 set myarray(1) One puts $myarray(1) Arrays Associative arrays (lists of key-value pairs) can be defined either by putting the key within parentheses (): or from a list of key-value pairs using the array command: array set myarray [list 1 One 2 Two 3 Three] puts $myarray(1) Multidimensional arrays can be emulated using smart strings as keys: set myarray(1,1) {One One} puts $myarray(1,1)

http://www.icp.uni-stuttgart.de 21/26 Hands on! Rewrite your script using lists and/or arrays Write two separated commands, one to generate the positions and masses of the x-y lattice system and the other one to calculate the COM of a collection of arbitrary positions and masses passed as arguments

http://www.icp.uni-stuttgart.de 22/26 set fp [open "myfile.dat" "w"] puts $fp "1,2\n3,4\n" close $fp Working with files Get a I/O channel to access a file: open filename access where access sets the channel for reading (default), "r", writing, "w" or append "a". Read/write data with commands gets/puts. Close channel with close Parse lines of data read from files with command split set fp [open " cat /proc/cpuinfo"]; #open a pipe puts [gets $fp]; #read a line of data set fp [open "myfile.dat" "r"] set data [split [gets $fp] ","]; #split using, as delimiter

http://www.icp.uni-stuttgart.de 23/26 Command line arguments Number of command line arguments in global variable $argc Name of the script in global variable $argv0 List of command line arguments in global variable $argv puts "There are $argc arguments to this script" puts "The name of this script is $argv0" if {$argc > 0} { puts "Arguments are $argv" }

http://www.icp.uni-stuttgart.de 24/26 Modularization The source command loads and executes a Tcl script: source scriptname This allows to split a program in different files, useful for code reutilization and maintenance

http://www.icp.uni-stuttgart.de 25/26 Hands on! Write a more flexible and modularized version of the COM calculation program: Split the commands for the generation of the x-y lattice system and the calculation of the COM into separate scripts Write a main script which loads the splitted command scripts, generates the system according to command line arguments and makes the calculation Alternatively, make the lattice generator script an independent program that works with command line arguments and writes the system data into a file. Make the main COM script to load and parse the data file for the calculation

Thank you! http://www.icp.uni-stuttgart.de 26/26