Pythonでlife timeを解析

life timeというのは生存時間と訳できる。つまりある一定の数値域に「どれくらいの長さ」居るかということを測ります。この解析結果は「どの数値域」かという定義に依存します。

# time value
   0     3
   1     2
   2     3
   3     1
   4     0
   5     1
   6     4

たとえばこういうデータがあったとして、valueが1以下の時のlife timeを知りたいなら時刻3~5で1,0,1と変わっているのでlife timeは"3"とわかります。2以下とするなら、時刻1の時に2があるので、life timeは[1, 3]という配列になります。

今回はこれをぱぱっと解析してくれるpythonスクリプトを書きました。ほとんど前のヤツの使い回しだわ。

使い方は、

python lifetime.py <input> <ncolumn> <threshold>

入力データファイル名、列番号、定義域を指定します。今のところ、定義域は「ある実数値以下」という形になっているので範囲指定ではなく解析値の最大値を指定する形です。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys 
import os

if __name__ == '__main__':
  argvs = sys.argv
  argvc = len(argvs)
  if argvc != 4:
    print "python lifetime.py <input> <ncolumn> <threshold>"
    exit()
  else:
    infile = argvs[1]
    ncol = int(argvs[2])
    th = float(argvs[3])
    if not(os.path.exists(infile)):
      print "%s is NOT found !!" % infile
      exit()
    else:
      cnt = 0 
      nl = 0 
      f = open(infile, 'r')
      for line in f:
        nl += 1
        s = line[:-1].strip()
        if s == "" or s[0] == "@" or s[0] == "#":
          pass
        else:
          col = line[:-1].split()
          if len(col) < ncol:
            print "%s\n" % line
            print "line[%d] is NOT enought column number" % nl
            exit()
          else:
            if float(col[ncol-1]) < th: 
              if cnt == 0:
                print "%s " % line[:-1],
              cnt += 1
            else:
              if cnt > 0:
                print cnt
                cnt = 0
      f.close()