NaN does not equal to NaN August 31st, 2014

This is an important knowledge for logic expression. Below is the python code. 

>>> import numpy as np

>>> np.nan

nan

>>> np.nan==np.nan

False

>>> np.nan~=np.nan

  File "<stdin>", line 1

    np.nan~=np.nan

          ^

SyntaxError: invalid syntax

>>> np.nan!=np.nan

True

>>> 

Tags: python

Posted in Programming | Comments(0)»

from:http://www.alivelearn.net/?p=1156

Standard deviation (std): standard deviation of the sample
Standard error, or standard error of the mean (sem), is the standard deviation of the meansem=stdN 

Most errorbars in scientific publications refer to standard error. Quite often a T-test is accompanied to show the effect is significant. This makes sense if they try to compare if the mean is different. Sometimes - quite often in neuroimage - while the mean is significantly different, it is almost impossible to tell the difference on the individual level (or classify individual observation). If the authors used standard deviation, the errorbars would have been huge and figures got ugly.

教你如何做个defensive driver - 长,慎入!
发信站: BBS 未名空间站 (Tue Oct 19 18:38:21 2010, 美东)

这次密西根车祸,加上前一段时间的几起车祸,都是发生在大家身边血的教训。觉得车
版有必要来一次安全驾驶讨论,各位老中青斯基们贡献一下自己的经验和教训,大家互
相学习,能高高兴兴出门去,安安全全回家来。这里非常感谢前面一些同学分享自己的
驾驶技巧,但是感到有些经验会误导新手,象一位同学提到在雪天采取点刹,其实这样
做非常危险, 后面会提到。写一些自己的经验,抛砖引玉,大家集思广益,以后都能
安全驾驶,把事故消灭在萌芽状态。先说说自己的基本情况,本人莱温斯基,15年驾龄
,来美后学的车,接受过正规的驾驶安全培训(NASCAR退役的斯基们办的)。主要跟大
家分享一下从培训中学到的一些技巧, 实践中证明也是非常有用地。在谈任何安全驾
驶技巧之前,最重要的一点大家一定要明白,大家开车的目的是“安全抵达目的地和安
全回家”,这一点出门前要牢记再三。这也是为什么要做一个defensive d
river,翻成中文就是弟反思斯基,你看就是说小弟我要做一个不断反思的斯基。
有点长,看在辛苦码字的份上,有钱的给点赏钱,没钱的给个吆喝。

1.360度扫描
在开车之前,一定要在司机位置上做一次360度扫描,尤其不是自己经常开的车,譬如
象租的车。先调整好座位到自己最舒服的位置,尤其踩油门和刹车的腿脚。然后左中右
镜。调左中右镜的原则是要尽量没有盲点。教练教我们的方法是,调左镜,在司机位置
上坐直,头向左稍偏,调整镜子到能稍微看到后门把手。 右镜同样,只是头向右稍偏
。这样做可以有效看到左右两边的盲点。这可能和大家平时习惯不同, 镜子有点太向
外偏了。 其实你要是做一下目测,看一下中镜覆盖的范围和左右镜覆盖的范围,就能
注意到盲点基本上没有了,利用这三个镜子,你的视线能覆盖你车子周围360度。这个
方法非常类似于现在有卖的号称NASCAR用的无盲点中镜。镜子非常重要,如何利用这些
镜子换lane后面将提到。

2.刹车和ABS
轻踩油门起步,平稳驾驶,这个大家都知道,就不多废话了。下面主要来谈一下刹车。
刹车一定要给一个提前量。例如前方红灯,要在大约100米就开始踩,轻踩,稍微加一
点力,不要太重,一直这样踩下去,这样车子到红灯前会稳稳停下,而且不伤车。大家
可以做一下实验,你在50米内猛踩和100米外轻踩,效果是一样的。现在大部分的车都
有ABS,尤其是住在冬天有雨雪地区的同学,一定要有ABS。检查你的车有没有ABS很简
单,就是打火的时候看一下你的仪表盘,ABS灯亮的话,就表明你的车有ABS。A
BS在雨雪天防滑非常有用,关键是你一定要踩住刹车,而千万不要点刹。点刹造成的
后果是computer chip被你搞的不知道该干啥,一会让它刹,一会儿不刹
,换你也会头大。这样ABS一点作用都没有,就等于你的车没有防抱死功能。本斯基
亲眼看到在一雪天,由于前面车祸要刹车,跟在我后面的车没有ABS或可能点刹,结
果在路上打了一个转,就冲到路边了。还有一次本人自己经历,雪天地上有冰,前面车
祸,虽然100米外就开始踩,但路太滑根本停不住,牢记教练指导,死命踩,能听到
感觉到刹车在嘎嘎嘎作响(教练说这表明ABS在work),最终离前面一辆车不到
20厘米停下来,整个过程车子没有向两边滑一下。附带BSO一下,本人座驾是WS
N专用买菜车honda accord,十来年乐,没给俺带来什么麻烦。抗日斯基
们请轻轻地轻轻地拍呵。

3.弯道技术
前面有个同学提到弯道要加速,才安全。本斯基不敢苟同,按照这个理论,岂不是弯道
上高速最安全。其实恰恰相反,弯道速度越快,越容易出去。平时经验也告诉大家,弯
道速度太快,感觉车在飘,感觉一不小心车子就飞出去了。教练的教导是,在弯道时,
要轻微带一下刹车,这样车轮和地面接触面积增大,摩擦力增大,车子行驶更平稳。雨
雪天弯道速度一定要慢,切记,切记!

4. 车距
平时在高速上和前面车距一定要保持3秒,这样能给你足够距离和时间反应做刹车动作
。怎么来计算这三秒呢?找一个参照物。例如前面车子刚经过一个路牌,然后你就象F
RIENDS里面的PHOBEE一样开始数one Mississippi, t
wo Mississippi, three Mississippi,这时如果
你的车子刚好经过这个路牌,表明你的车距刚好是安全车距。雨雪天的车距至少要5秒。

5. 恶劣气候
再强调一遍,雨雪天,速度一定要慢,刹车要提早,踩住刹车而非点刹让ABS工作。
如果路上有冰或下冰雨而你又是长途,如果是晚上,最好找最近的旅馆停下,第二天再
走。因为晚上根本看不清路上冰的情况,非常非常危险。记住,冰比雨雪要危险好几倍
。冬天早上上高速经常看到中间隔离带和路边上都是晚上冲进去的车。朋友亲身经历,
自恃技术高超,晚上路上有积雪非要上路,估计可能有暗冰盖在雪下边,结果冲进路边
沟里,幸好人未受伤。不要太相信自己的技术,尤其是恶劣气候下,技术没什么优势。
暴雨雪天,again,慢速,打上紧急双闪灯,这样后面的车能看到你,不至于撞上
。能找个exit下去,等小了再走最好。有人建议,暴雨天戴上墨镜,更能透过雨幕
看清前面道路,尤其是当你超大卡或大卡超你时,它溅起的水基本上让你什么也看不见
,非常危险,据说戴上墨镜会好很多,本斯基还没机会试过(住在只下雪,不下雨的地
区),据说很管用。
还有一个重要问题是一旦车在打滑怎么办?千万不要猛打方向盘,试图把车调整回来,
这样车肯定会在路上打转,最终飞出去。教练的指导是,眼睛看着前方,紧紧握住方向
盘,保持车一直向前方前进。

6. 大卡(这里指18轮的SEMI)
永远永远不要堵在它前面开,对于大卡司机来说,时间就是金钱,你挡他的道,就是堵
他财路,所以离他越远越好。超大卡时,要尽快离开它的盲区。 

7. 上高速并Lane和换Lane
好多人害怕上高速的那一段,尤其是traffic比较多的高速上,总担心后面车会
撞上来。这里告诉大家一个诀窍是,速度。从你拐进ramp开始上高速那一刻起,一
定要把速度提起来,至少到45-50MPH。大部分四缸的车,从20-30MPH
上40-50MPH是个坎,即使你使劲轰油门,速度还是上不来,而从40-50M
PH奔60-70MPH,一般的车踩油门基本上很快能上来。所以快并入高速前,速
度要至少保持到45-50MPH甚至更高,这时同时要向左看高速上车流情况。如果
靠你这边的Lane跟你平行或稍后50米有车,不要加速试图在他们之前并Lane
,他们速度比你快很多(65-75MPH),这样很危险。这时要稍微放慢一点点速
度或不加速,等他们过去。还有要充分利用并Lane前的和你要并的Lane平行的
100米,发现有些人喜欢上高速立刻就并Lane,这不见得是个好习惯。利用并L
ane前的100米,迅速加速(这时你在ramp上45-50MPH就能很快让你
上到60-70MPH),follow Lane自然并入。即使高速上车流量很大
,你也能并上去。否则及有可能你不得不停在ramp上。 本斯基就被一墨西哥大妈
堵过一次。并Lane前象大部分高速入口一样有100多米的Lane可以加速,车
流量比较大。结果前面的墨西哥大妈,上ramp速度就很慢,只有30MPH,到了
要并的100多米又不加速,结果不得不停在那儿,而且糟糕的是那里是个大弯道,有
小山挡住,所以根本看不到后面会不会有车飞速过来。结果堵了有20几分钟,才胆颤
心悸的上了高速。因为没有速度,不得不猛踩油门,害怕后面会有车冲过来,可怜俺那
匹雅阁老马,从没舍得这么轰它的油门。举这个例子,就是说明上高速前速度的重要性。
至于高速或local换Lane,简单唠叨几句,首先要看中镜,确信要换的Lan
e上后面没车高速冲来,然后快速看左镜(往左换)或右镜(往右换),确信车子附近
没车,然后迅速稍微甩头看一下确保没有盲点,这里甩头不用太深,当然这是在你前面
调镜子时候基本去掉盲点的基础上的。换的时候,轻打方向盘,不要打太猛,斜斜的“
刺”进去,俺特别喜欢这个刺字,是俺以前学车的师傅教的,形象的描述了什么叫sm
ooth地换Lane,每次俺换Lane的时候,都抑制不住地想到这个字,经常内
牛满面。如果后面有车,一般说法是要能从左或右镜看到它的两个大灯,我们教练说要
能从中镜看到后面车的大灯,实际上就是拉开更长距离换,避免给后面的人有cuto
ff的感觉。国内的斯基基本不甩头,只看左右镜,这跟国内的情况是相关的,不太适
用于北美。第一,国内速度一般较慢,尤其是local,即使撞到,不会出生命危险
;第二,国内斯基们都神经紧绷,知道前面这大叔不知道什么时候会cutoff,他
们都有心理准备做避让。请不要拿同样情况来套北美的大叔大妈们,不要期望他们能反
应过来让你。所以最好还是甩头看一下盲点。

8.高速紧急情况
高速上有时会撞到鹿或你前面的车突然急刹,这时候你基本上只有不到1秒的反应时间
,千万不要试图打方向盘换Lane避开它们。因为你跟本没有时间看你要换的Lan
e上的情况,假如后面是一大卡或稍微大点的车,基本必死无疑。教练教导的是使出吃
奶的劲死命踩刹车,把全身重量放上去,握住方向盘,让它撞。这样车子可能损坏严重
,但人基本上轻伤,如果司机和副驾位置有安全气囊,可能基本没事。记住,碰到任何
紧急情况,死命踩刹车,尽可能把速度降下来,而不是打方向盘试图避开。因为在碰撞
中,最重要的是速度,速度大,碰撞力就大。

9.ROAD RAGE
这个记得以前大家都讨论过,很多好的建议,记住前面开宗明义第一句话,“安全抵达
目的地和安全回家”。没必要和那些在你后面滴你,喊你asshole的孙子们计较
,跟他们拼命不值。以前参加过交警办的培训班,据他们说,他们查的车,50%都携
带武器。有一次,在一哥们车后备箱里,居然查着手雷。大家来这都是准备做一个有理
想,有文化,有道德,有纪律的四有新人地,没比较为了一些社会垃圾把命丢了。如果
高速上碰到这样的,赶紧找一高速出口下去。如果发现跟过来的话,立马打911报警
,记住自己出的是exit多少和哪条高速。高速上执勤条子很多,一般5分钟之内就
能赶到。

10.安全带,打电话,喝酒,喜欢飙车的和其他
安全带,前排的就不多说了,后排的也要系。看过YouTube上车祸录像没,后排
没系安全带是怎么飞出去的,没看的赶紧看看去,回来写个观后感。
打电话和发短信的,马路杀手!尤其是看到中年大妈,开着SUV打电话的,赶紧离远
点。
喝酒的,同样,马路杀手九段!!!查到要蹲派出所和递解出境。据说,一瓶啤酒,2
小时内开车上路,体内酒精含量是超标的。
喜欢飙车的,又一个马路杀手。经常会碰到一些牛斯基,喜欢BSO自己飙车到120
MPG,如果是吹牛B,吹吹就算了,如果真这么干,还准备经常干,先想想自己的家
人,除非你是从石头里蹦出来。你拍拍屁股到另一个世界去了,留下你的父母亲人,白
发人送黑发人,好好想想吧。这话说的难听,糙了些,但理不糙。以前飚过就算了,以
后就别再干了。为自己安全,也为别人安全考虑。
国内口号是宁停3分,不抢一秒,这话灰常有道理。在红绿灯口和stop sign
左转和右转,自己不确定的情况下,千万不要采取任何动作,要到情况清楚了再动,没
必要为了抢那一点点时间。俺几次差点出事故,都是在关键时刻忍住了。举一个例子吧
,一次在stopsign左转,远处往我左转方向有车过来,如果我要抢这一秒的话
,虽然不会cutoff那辆车,但它可能不得不做刹车动作,当时忍了一下,就这一
下,才发现一辆SUV突然从我前方冲过,原来这辆SUV被车窗和挡风玻璃之间的接
缝给挡着了。俺当时冲出去的话,肯定被SUV撞个稀巴烂。
最后,再强调一下defensive driving,无论你技术多么高超,但马
路上有太多的杀手,所以一定要警惕,不要把自己的生命放到别人的手里。俺亲眼看到
大卡司机睡着了,在高速上晃来晃去。不要疲劳驾驶,每2-3小时的高速一定要休息
一下。发现要睡着了,一定要找地方停下,睡一会再走。平时开始时一定要养成好的习
惯,不要小看这些小习惯,关键时候可能就救了你一命。

先想到这么多,不对的地方,大牛们多多指教,欢迎补充,多多益善!

looping a folder in tcl October 17th, 2010

#!/bin/sh
# loopFolder.tcl \
exec tclsh "$0" ${1+"$@"}

set dirDepth 0
proc Subdirectory_ComputeInputFile {f} {
   # puts $f
    if {[file isdirectory $f]} {
        if {$::dirDepth > 0 } {
            return
        }
        set ::dirDepth 1
        foreach g [glob [file join $f *]] {
            Subdirectory_ComputeInputFile $g
        }
    } else {
        #puts $f
        # Find Subject Number
        set BaseName [file tail $f]
        set ExtensionName [file extension $BaseName ]
        set RootName [file rootname $BaseName ]
        puts $BaseName
#        scan $RootName "%c%2d%s" CellPass SubjectID DriveStr

#        puts "BaseName $BaseName    RootName:$RootName    ExtensionName:$ExtensionName"
        # Determin if this file is an input file or an .csv file
        if { $ExtensionName == ".log" } {
        puts "FN: $f"
            #ComputeInputFile $f
        }
        #if { [ lsearch $RootName "*-BaseWithTarget" ] >= 0 } { }
    }
}

set folder "SmartEye"
Subdirectory_ComputeInputFile $folder
#foreach f $argv {
#    set ::dirDepth 0
#    puts $f
#   Subdirectory_ComputeInputFile $f
#}

read and write file in tcl October 17th, 2010

#!/bin/sh
# readWholeFile.tcl \
exec tclsh "$0" ${1+"$@"}

#!/bin/sh
# readCSV.tcl \
# read and write by line.

#exec tclsh "$0" ${1+"$@"}

set IF_SE [open "short.csv" "r"]
set fo [open "output.csv" "w"]

set file_data [read $IF_SE]
#set b [split $file_data]

set data [split $file_data "\n"]
foreach line $data {
    puts $fo $line
}

close $fo
close $IF_SE

puts "hi"

The longest distance in the world is not that between life and death, but when I stand in front of you,yet you don't know that I love you

The furthest distance in the world is not when I stand in font of you, yet you can't see my love but when undoubtedly knowing the love from both yet cannot be togehter

The furthest distance in the world is not being apart while being in love, but when plainly can not resist the yearning, yet pretending you have never been in my heart
The furthest distance in the world is not ?but using one's indifferent heart,to dig an uncrossable river for the one who loves you

The farthest distance in the world Is not we cannot be together when we love each other But we pretend caring nothing even we know love is unconquerable

The farthest distance in the world Is not the distance between two trees
But the branches cannot depend on each other in wind even they grow from the same root
The farthest distance in the world Is not the braches cannot depend on each other, But two stars cannot meet even they watch each other
The farthest distance in the world Is not the track between two stars, But nowhere to search in a tick after two tracks join
The farthest distance in the world Is not nowhere to search in a tick,But doomed not to be together before they meet

The farthest distance in the world Is the distance between fish and bird, One is in the sky, another is in the sea

世界上最远的距离
不是生与死的距离
而是我站在你的面前
你却不知道我爱你

世界上最远的距离
不是我站在你的面前
你却不知道我爱你
而是爱到痴迷
却不能说我爱你

世界上最远的距离
不是我不能说我爱你
而是想你痛彻心脾
却只能深埋心底

世界上最远的距离
不是我不能说我想你
而是彼此相爱
却不能够在一起

世界上最远的距离
不是彼此相爱
却不能在一起
而是明明无法抵挡这一股气息
却还得装作毫不在意

世界上最远的距离,
不是明明无法抵挡这一股气息
却还得装作毫不在意
而是用一颗冷漠的心
在你和爱你的人之间
掘了一条无法跨越的沟渠

世界上最远的距离
不是树与树的距离
而是同根生长的树枝
却无法在风中相依

世界上最远的距离
不是树枝无法相依
而是相互了望的星星
却没有交汇的轨迹

世界上最远的距离
不是星星之间的轨迹
而是纵然轨迹交汇
却在转瞬间无处寻觅

世界上最远的距离
不是瞬间便无处寻觅
而是尚未相遇
便注定无法相聚

世界上最远的距离
是鱼与飞鸟的距离
一个在天
一个却深潜海底
Posted in Life | Comments(444)»

//by Jibo He @ UIUC
// 6 Oct. 2010
// get the workload ratings in ScaleRating_S1-8.xls, and put them into TrialReport

import java.io.*;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExpExcel {
    public static void main(String args[]) {
        try {
            Workbook trialReport = Workbook.getWorkbook(new File(
                    "TrialReport_S1-8.xls"));

            String filePath = "TrialReportScale_S1-8.txt";
            File file = new File(filePath);
            FileWriter fw = new FileWriter(file); // 创建文件字符输出流
            BufferedWriter bw = new BufferedWriter(fw); // 使用缓冲数据流封装输出流

            Sheet trialSheet = trialReport.getSheet(0);
            int trial_NRow = trialSheet.getRows();

            for (int row = 1; row < trial_NRow; row++) {
                Cell[] arow = trialSheet.getRow(row);
                String RECORDING_SESSION_LABEL = arow[0].getContents();
                String block = arow[8].getContents();
                String practice = arow[11].getContents();
                // System.out.printf("%s,%s,%s\n", RECORDING_SESSION_LABEL,
                // block,practice);

                String[] ratings = new String[4];
                ratings = Search(RECORDING_SESSION_LABEL, block, practice);
                // System.out.printf("found %s,%s,%s\n", ratings[1],
                for (int i = 0; i < arow.length; i++) {
                    bw.write(arow[i].getContents());
                    bw.write("\t");
                }
                bw.write(ratings[1]);
                bw.write("\t");
                bw.write(ratings[2]);
                bw.write("\t");
                bw.write(ratings[3]);
                bw.newLine();
                bw.flush(); // 刷新缓冲区

            }

            trialReport.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static String[] Search(String ID, String block, String practice) {
        String[] ratings = new String[4];
        ratings[1] = "-1";
        ratings[2] = "-1";
        ratings[3] = "-1";
        try {
            Workbook scale = Workbook.getWorkbook(new File(
                    "ScaleRating_S1-8.xls"));
            Sheet scaleSheet = scale.getSheet(0);

            int NRow = scaleSheet.getRows();
            for (int row = 0; row < NRow; row++) {
                Cell[] arow = scaleSheet.getRow(row);
                String ID_scale = arow[0].getContents();
                String block_scale = arow[2].getContents();
                String practice_scale = arow[5].getContents();
                if (ID_scale.equals(ID) && block_scale.equals(block)
                        && practice_scale.equals(practice)) {
                    String TimeLoad = arow[27].getContents();
                    String MentalEffort = arow[28].getContents();
                    String StressLoad = arow[29].getContents();

                    ratings[1] = TimeLoad;
                    ratings[2] = MentalEffort;
                    ratings[3] = StressLoad;
                    // System.out.printf("%s,%s,%s\n", ID_scale,
                    // block_scale,practice_scale);
                    break;
                }
            }

            scale.close();
        } catch (Exception e) {

            System.out.println(e);
        }

        return ratings;

    }

    public static void formatPrint(String[][] outputArray) {
        // System.out.println(outputArray.length);
        int ncols = outputArray[0].length;
        int nrows = outputArray.length;
        System.out.printf("%d,%d\n", ncols, nrows);

        try {
            WritableWorkbook output = Workbook.createWorkbook(new File(
                    "TrialReportScale.xls"));
            WritableSheet outputSheet = output.createSheet(" rawdata ", 0);

            // System.out.printf("%s,%s", outputArray[0][0], outputArray[0][1]);

            for (int row = 1; row < nrows; row++) {
                for (int col = 1; col < 4; col++) {
                    // System.out.printf("%d,%d\n",row,col);
                    // System.out.println(outputArray[row][col]);

                    try {
                        float f = Float.valueOf(outputArray[row][col].trim())
                                .floatValue();
                        outputSheet.addCell(new jxl.write.Number(col, row, f));

                        // System.out.printf("%d,%d\n",row,col);
                    } catch (NumberFormatException nfe) {
                        outputSheet.addCell(new Label(col, row,
                                outputArray[row][col]));

                        // System.out.println("NumberFormatException: " +
                        // nfe.getMessage());
                    }
                }

            }

            output.write();
            output.close();
            System.out.println("writing finished");
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}

A brief Tcl Tutorial October 8th, 2010

Tcl Tutorial


 

Introduction

This is a very short introduction to the Tcl script language. If you just can't wait, I hope this will make you able to read and to understand simple Tcl code.

In many points, Tcl is similar to C, especially for loop structures, function definitions and mathematical or conditional expressions. In other points, such as expression evaluation and list data structures, you will notice that Tcl has inherited from the benefits of the Scheme language.

In Tcl, all data is represented as strings.

Commands evaluation

Each Tcl command call is a sentence of the form : command arg1 arg2 arg3 ...

The Tcl evaluator take each word of this sentence and evaluate it. After evaluation of each word, the first word (command) is considered to be a function name and this function is executed with as arguments the following words.

To evaluate a word, the interpretor has to do the following substitutions in the word string :

  • If the word is surrounded by " ", this word may contain spaces, but substitution is still applicable inside the quotations. Inside the quotation, there may be spaces and carriage returns.
  • If a word is surrounded by { }, this word is unaffected (substitution is thus not applicable on this word). Inside the braces, there may be spaces and carriage returns. Moreover, the { } braces may be nested.
  • If a part of the word is surrounded by [ ], this part is considered as a command sentence : the text within the brackets is evaluated as a Tcl command and replaced with the result.
  • where substitution is applicable, every string beginning with $ is replaced with the variable represented by this string. This string is ended by a space, a '-' or a ','.

Examples

  1. set a "World !"
    In the evaluation of the 3 words 'set', 'a' and '"World !"', no substitution has to be done, only the " " are removed. The command 'set' is then executed with as parameters 'a' and 'World !'. This command tell Tcl to define a new variable 'a' (if not already defined) and to set its value to 'World !'.
  2. set b "Hello $a"
    Set the variable 'b' to 'Hello World !'. Here, the variable substitution has occurred inside the second parameter where the variable 'a' is replaced by its value.
  3. set c [string range $b 0 3]
    Set the variable c to 'Hell', which is the 4 first letters of 'Hello World !'. In this case, The part between [ ] has been executed as a command

If you want to break a command sentence in lines you can only do it inside the { } brace or in the " " quotation or you can break the line with a '\' at the end of any break line.

Example


if {$c == "Hell"} {
   puts "Oh god !"
} else {
   puts "Peace !"
}

This test the value of the variable c. If it is the string 'Hell' it prints 'Oh god !' on screen, otherwise, it prints 'Peace !'. In this sentence, Tcl see 5 words :

  • 'if' is the first : nothing to be evaluated.
  • '$c == "Hell"' is the second : because of the surrounding curly braces, there is no further evaluation on this word.
  • 'puts "Oh god !"' : for the same reason, no further evaluation
  • 'else' : nothing to do.
  • 'puts "Peace !"' : no further evaluation.

The first word, 'if' is seen as the command and this command is executed with as parameters the 4 following words. That is later that the condition '$c == "Hell"' is evaluated, during the execution of the if command.

Notice where we placed the line breaks (inside the { }).

Strings and Lists

Under Tcl, the value of each variable is stored as a string. Even if you want to save a number in a variable, this number is transformed into a string.

As a special type of string, the list deserve a special attention in data representation in Tcl. The list is nothing more than a string with, as elements separator, the space. A list may contains sublists.

Example


% set list {12 {78 5} 45 "Im a not a number"}
12 {78 5} 45 "Im a not a number"
% set sublist1 [lindex $list 1]
78 5
% set sublist2 [lindex $list 3]
Im a not a number
% lindex $sublist2 2
not

Mathematics expression

Whereas all variables are of type string, the mathematical operations internally uses float and integer number representation to produce their results. The command that calculate mathematical expression is 'expr'.

Example


% set result [expr (4+6)/4]
2
% set result [expr (4.0+6)/4]
2.5

In the first calculation, the interpretor has used the integer number representation. In the second, it has used the float number representation.

How to display something ?

To display a string, you can use the command 'puts'

Example


% set variable 255
% puts "The number $variable"
The number 255
% puts [format "The number %d is equal to 0x%02X" \
  $variable $variable]
The number 255 is equal to 0xFF

As it can be seen in the previous example, the command format is very similar to the C command 'printf'.

Control flow

The following commands are similar to the C equivalent. Only 'foreach' has no C equivalent (have a look at the example to see what it do).

  • if {...condition...} {...body...}
  • while {...condition...} {body}
  • for {... init ...} {...condition...} {...increment...} {...body...}
  • foreach varnames {...list...} {...body...}

the '...condition...' is evaluated in the same way that it should be with command 'expr'.

Examples

  1. while
    
    % while {$i<4} {
    > puts "$i*$i is [expr $i*$i]"
    > incr i
    > }
    0*0 is 0
    1*1 is 1
    2*2 is 4
    3*3 is 9
    
  2. for
    
    % for {set i 0} {$i<4} {incr i} {
    > puts "$i*$i is [expr $i*$i]"
    > }
    0*0 is 0
    1*1 is 1
    2*2 is 4
    3*3 is 9
    
  3. foreach
    
    % set observations \
      {Bruxelles 15 22 London 12 19 Paris 18 27}
    Bruxelles 15 22 London 12 19 Paris 18 27
    % foreach {town Tmin Tmax} $observations {
    > set Tavg [expr ($Tmin+$Tmax)/2.0]
    > puts "$town $Tavg"
    > }
    Bruxelles 18.5
    London 15.5
    Paris 22.5
    

Array

Arrays are always unidimensional but the index is a string. If you use a separator in the index string (such as ',', '-'), you can get the same effect than with a multidimensional array in other languages.

Example


% set observations \
  {Bruxelles 15 22 London 12 19 Paris 18 27}
Bruxelles 15 22 London 12 19 Paris 18 27
% foreach {town Tmin Tmax} $observations {
set obs($town-min) $Tmin
set obs($town-max) $Tmax
}
% parray obs
obs(Bruxelles-max) = 22
obs(Bruxelles-min) = 15
obs(London-max)    = 19
obs(London-min)    = 12
obs(Paris-max)     = 27
obs(Paris-min)     = 18

Procedures

Procedures are the equivalent of the C functions.

Example


% proc sum2 {a b} {
>  return [expr $a+$b]
> }

if a procedure does not contain any 'return' statement, the default return value is the return value of the last evaluated function in this procedure. So the following script is perfectly equivalent :


% proc sum2 {a b} {
>   expr $a + $b
> }

To call the 'sum2' function, we do the following :


% sum2 12 5
17

The special argument name 'args' contains a list with the rest of the arguments

Example


% proc sum {args} {
>   set result 0
>   foreach n $args {
>      set result [expr $result+$n]
>   }
>   return $result
> }
% sum 12 9 6 4
31

it is also possible to specify default parameters. So, if you don't specify the last parameters, the default values will be substituted.

Example


% proc count {start end {step 1}} {
>   for {set i $start} {$i<=$end} {incr i $step} {
>     puts $i
>   }
> }
% count 1 3
1
2
3
% count 1 5 2
1
3
5

If you want to use global variables in a function, you have to declare it as global.

Example


% set global_counter 3
% proc incr_counter {} {
>    global global_counter
>    incr global_counter
> }
% incr_counter
4
% set global_counter
4

You can also declare a table as global.

Example


% set counter(value) 3
% set counter(active) 1
% proc incr_counter {} {
>    global counter
>    if {$counter(active)} {
>       incr counter(value)
>    }
> }
% incr_counter
4
% set counter(active) 0
0
% incr_counter
4

Eval

The 'eval' command

  • concatenate all its arguments in one string
  • splits this string using spaces as separators
  • evaluate the command sentence formed by all the substrings

In the following example, we used the function 'sum' that we have already defined.

Example


%  proc average {args} {
>     return [expr [eval sum $args] / [llength $args]] 
>  } 
% average 45.0 65.0 78.0 55.0
60.75

If you had omitted the 'eval' command in the previous example, the 'sum' procedure would have returned an error because 'sum' should be called with only one string argument (in the previous example, this argument would have been '45.0 65.0 78.0 55.0') while 'sum' is expecting numerical arguments.

uplevel, upvar

With the 'upvar' command, you can access a variable which belongs to a higher level of the procedure call stack.

Example


% proc decr {n steps} {
>   upvar $n upa
>   set upa [expr $upa - $steps]
> }
% set nb 12
12
% decr nb 3
9
% puts $nb
9

In the previous example, the parameter 'n' gets the value 'nb' (the string 'nb' !) if we type 'decr nb 3'. The command 'upvar $n upa' means that the variable 'upa' becomes a synonym to the variable 'nb' (coming from a higher level of the stack).

With the 'uplevel' command, you can evaluate something on higher level in the stack.

Example


% proc do {todo condition} {
>   set ok 1
>   while {$ok} {
>     uplevel $todo
>     if {[uplevel "expr $condition"]==0} {set ok 0}
>   }
> }
% set i 0
0
% do {
puts $i
incr i
} {$i<4}
0
1
2
3

Inside the procedure 'do', the evaluation of the script 'todo' and the conditional 'condition' has to made on a higher level of stack (in the same way that if they were evaluated from out of 'do').

error and catch

If you insert an 'error' command in your code, this command will stop the execution of your script and return the error message that follow the 'error' command. With the command 'catch', you can also intercept a error to avoid that your script stops on an error.

If 'catch' return 0, it means that no error occurred while evaluating the script send as parameter of catch. If 'catch' return 1, it means that an error occurred.

Example


% proc div {a b} {
>   if {$b==0} {
>      error "divided by zero"
>   } else {
>      return [expr $a/$b]
>   }
> }
% div 8 3
2
% div 8 0
divide by zero
% catch {div 8 3}
0
% catch {div 8 0}
1
% catch {set result [div 8 3]}
0
% catch {set result [div 8 0]}
1

The last call is completely equivalent to


catch {div 8 3} result

Here are some good tcl tutorials.

http://users.belgacom.net/bruno.champagne/tcl.html

http://www.tcl.tk/man/tcl/tutorial/Tcl13.html

 

expr {sin($x+$y)}

set randNum [expr { int(100 * rand()) }]

% proc sum2 {a b} {
>  return [expr $a+$b]
> }


--------------my  TCL code for velocity change----------

#data based on Dastrup et al.(2009) and Andersen & Ni (2005).



set phase1 [expr rand()]
set phase2 [expr rand()]
set t=0
set v10 [expr 1.726*[expr sin($phase1)]]
set v20 [expr 2.417*[expr sin($phase2)]]
set v30 [expr 0-$v10-$v20]
set phase3 [expr asin([expr $v30/6.072])]

proc velocity1 {t} {
return [expr 1.726*[expr sin([expr 0.117*$t+$::phase1])]]
}
proc velocity2 {t} {
return [expr 2.417*[expr sin([expr 0.083*$t+$::phase2])]]
}
proc velocity3 {t} {
return [expr 6.072*[expr sin([expr 0.033*$t+$::phase3])]]
}
proc velocitySum {t} {
return [expr [eval velocity1 $t]+[eval velocity2 $t]+[eval velocity3 $t]]
}

 

------------------MATLAB equivalents of the above TCL code---------

%     y(t) = A \cdot \sin(\omega t + \phi)
%
% where:
%
%     * A, the amplitude, is the peak deviation of the function from its center position.
%     * ω, the angular frequency, specifies how many oscillations occur in a unit time interval, in radians per second
%     * φ, the phase, specifies where in its cycle the oscillation begins at t = 0.
%           o When the phase is non-zero, the entire waveform appears to be shifted in time by the amount φ/ω seconds. A negative value represents a delay, and a positive value represents a "head-start".


t=1:1000;
phase1=rand();
phase2=rand();
v1=1.726*sin(0.117*t+phase1);
v2=2.417*sin(0.083*t+phase2);

phase3 = asin((0-1.726*sin(phase1)-2.17*sin(phase2))/6.072);
v3=6.072*sin(0.033*t+phase3);
plot(t,v1+v2+v3)
hold on
plot(t,v1,'r')
hold on
plot(t,v2,'k')
hold on
plot(t,v3,'g')

 

 

 

Hello world! June 25th, 2010

Welcome to Jibo's blog. This is my new home.

 

Jun, 25, 2010

in Toronto, Canada

Posted in | Comments(467)»