code
stringlengths
1
1.72M
language
stringclasses
1 value
# Create your views here.
Python
# -*- coding:utf-8 -*- import wolfox.lib.codeblock import function2block import wolfox.foxit.utils.vdict as vdict CTYPE = {'ONE':1,'ALL':2,'CATALOG':2} #normal为与具体stock数据无关的计算 CALCED,GLOBAL,ALL,ALLCATALOG = 'CACLED','GLOBAL','ALL','ALLCATALOG' class Context(object): ''' Task内部context组织 data meta_data: catalogsubject_name ==> catalogs的dict 每个catalog是一个(catalogname,set)对 需要虚拟出一个 ALL ==>{'ALL':set1,'ALLCATALOG':set2} temp 以values或'GLOBAL'为key的dict. GLOBAL是指与values无关的函数计算所得的结果(如catalog指数,stockcode的全局排序号) 每个值元素为stock_code或'CAT%d' % cat_id或'ALL'或'CALCED'为key的dict. 对于从CATALOG/ALL类型计算函数得到的registered结果,如果为二维数组则分解到stock_code列,一维则直接挂到'CAT%d'/all下 其中的每个值元素的结构为变量名为key的dict,如key为'ma5','order'之类的 对于直接的索引,获得的即为向量或相应数据 对于由CATALOG/ALL分解到stock的 如果是CATALOG分解来的,得到的是一个列表,其中的每个元素是(catalog_name,catalog自身的排名,data) 如果是ALL/ALLCATALOG分解来的,直接得到向量数组 对于CALCED,数据为name==>value的dict. 从广义来说,stock_code,catalog_name,ALL,ALLCATALOG都是同种性质的,都代表着广义的股票名 而values和GLOBAL也是同种性质,都代表着与参数相关的设置 CALCED是另类的,处于values之下时,属于values相关的标量数据;处于GLOBAL之下时,属于values无关的标量数据 但是这里并没有刻意去区分这个标量数据是怎么计算出来的.但是理论上,标量数据不应该从向量得到 经过考虑,去掉CALCED相关的东西,如果需要,在配置文件设定args时来计算(去eval为string的arg) 要求外部在初始化时设定好data和meta_data 特别是meta_data,需要设定好all和allcatalog这两个特殊的catalog ''' def __init__(self,data,meta_data): self.data = data self.meta_data = meta_data self.temp = vdict() def get_stocks(self): return self.data.keys() def get_datas(self,stock_code,names): return self._match(self.data,names) def get_temp_datas(self,key,stock_code,names): vback = self.temp.setdefault(key,vdict()).setdefault(stock_code,vdict()) return self._match(vback,names) def set_temp_datas(self,key,stock_code,pairs): vback = self.temp.setdefault(key,vdict()).setdefault(stock_code,vdict()) vback.update(pairs) def get_catalogs(self,csname): ''' 返回 catalog_name,set(stock_code) 的元组Set ''' return self.meta_data[csname].catalogs def get_subject_type(self,csname): return self.meta_data[csname].ctype #内部函数 def _match(self,data,names): return dict([(name,data[name]) for name in names]) #两个快捷方式 def get_global_datas(self,stock_code,names): return self.get_temp_datas(GLOBAL,stock_code,names) def set_global_datas(self,stock_code,pairs): return self.set_temp_datas(GLOBAL,stock_code,pairs) #另两个常用的快捷方式 def get_independent_datas(self,stock_code,names): vback = self.get_datas(stock_code,names) vback.update(self.get_global_datas(stock_code,names)) return vback def get_independent_datas(self,args,stock_code,names): vback = self.get_independent_datas(stock_code,names) vback.update(self.get_temp_datas(args,stock_code,names)) return vback class Task(object): ''' 核心任务类 负责接受script和相应的参数组 给出验证script合法性的方法 按照参数组和传入的背景数据对象(可能缓存)执行任务 要求脚本中变量名不要和全局变量名和register变量名重复,否则结果难以预料 ''' header = ''' # -*- coding: utf-8 -*- import re import logging from wolfox.foxit.calculator import * logger = logging.getLogger('foxit.dune.controller') ''' def __init__(self,script,arg_fields,args_list,predefined): ''' script: 脚本对象,为string. 其中只允许一层 arg_fields为自由变量名列表 args_list 为变量值列表,其中的每个元素为与arg_fields对应的值元组 predefined为name==>value的dict,为预定义的常量 ''' assert (not arg_fields and not args_list) or len(arg_fields) == len(args_list[0]) #如果存在自由变量,则必有args_list self.script = script self.arg_fields = arg_fields self.args_list = [tuple(args) for args in args_list] #元素转换为tuple以备用作dict的key self.predefined = predefined self.cobject = compile(self.header + self.script,'<string>','exec') self.functions = [] self.globals = self._prepare() #脚本中的全局变量 self.item_names = self._get_data_item_names() self.context = Context() def _prepare(self): ''' 执行脚本,过程中用到了calc这个decorator,因此又会更新self,functions ''' g = {'calc':self.calc} l = {} exec self.cobject in g,l self.functions.sort() #按order来 return l def reset_values(self,args_list): ''' 重新设置args_list''' self.args_list = args_list def reset_predefined(self,predefined): ''' 如默认指数,特定常量(如ctype类型 NORMAL,ALL,GROUP)等 ''' self.predefined = predefined def is_valid(self): ''' predefines为预定义的global变量集合 验证每个calc function中用到的变量(co_names)是否有指定变量,输出变量是否是内部变量(co_varnames) 可能会抛出NameError ''' spre = set(predefined.keys) svar = set(self.arg_fields) sglobal = set(self.globals.keys) sglobal.update(spre) sglobal.update(svar) is_valid = True for nth,func in self.functions: snames = set(func.func_code.co_names) if not snames.issubset(sglobal): raise NameError,u'function %s 所用变量不存在' % func.func_code.co_name souts = set(func.register) if not souts.issubset(set(func.func_code.co_varnames)): raise NameError,u'function %s 输出的变量不存在' % func.func_code.co_name sglobal.update(souts) #outs部分添加到全局变量集合 return True def _get_data_item_names(self): ''' 计算实际用到的data item_names ''' item_names = set([]) svar = set(self.arg_fields) for nth,func in self.functions: item_names.update(svar.intersection(set(func.func_code.co_names))) return list(item_names) def run(self,context): ''' context:设置脚本执行globals的dict 执行过程中的结果输出也在此步完成 这里区分ALL和Catalog的原因是在后续处理上有所不同。虽然可以不区分,在run_group函数里面判断是哪个subject 但是为使使用时有明确区别,用ALL/CATALOG来区分这些不同。 ''' sglobal = self.globals.copy() sglobals.update(self.predefined) for nth,func in self.functions: if func.ctype = CTYPE['ONE']: self.run_one(func,sglobals,conext) elif func_ctype = CTYPE['CATALOG']: self.run_group(func,sglobals,context,subjects) elif func_ctype = CTYPE['ALL']: self.run_all(func,sglobals,context) #decorator定义. 因为calc中要用到task的实例来保存script中的函数信息,但在脚本中无法隐式得到这个实例,因此直接定义在task中 def calc(self,order,ctype=CTYPE['ONE'],register=(),subjects=(),once=False): ''' subjects只对ctype='CATALOG'才有意义 once表明该函数是否对arg_list有依赖.若为True,则只须计算一次 ''' def real_dec(f): f.once=once f.register = register f.ctype = ctype f.subjects = subjects function2block(f) self.functions.append(order,new_func) return f return real_dec def run_one(self,func,sglobals,context): my_globals = sglobals.copy() gnames = func.func_code.co_names if func.once == True: for stock_code in context.get_stocks(): my_globals.update(self.context.get_independent_datas(stock_code,gnames)) #每次都会覆盖之前的同名变量 my_locals = {} exec func.func_code in my_globals,my_locals self.context.set_global_datas(stock_code,[(varname,my_locals[varname]) for varname in func_register]) else: #逐个执行. 对脚本的变量集合逐个执行每个股票 for args in self.args_list: my_globals.update(zip(self.arg_fields,args)) for stock_code in context.get_stocks(): my_globals.update(self.context.get_dependent_datas(args,stock_code,gnames)) #每次都会覆盖之前的同名变量 my_locals = {} exec func.func_code in my_globals,my_locals self.context.set_temp_datas(args,stock_code,[(varname,my_locals[varname]) for varname in func_register]) def run_group(self,func,sglobals,context,subjects): #逐组执行 my_globals = sglobals.copy() gnames = func.func_code.co_names for subject in subjects: for name,catalog in context.get_catalogs(subject): if func.once == True: pass else: for args in self.args_list: my_globals.update(zip(self.arg_fields,args)) def run_all(self,func,sglobals,context): subject = 'ALL' my_globals = sglobals.copy() gnames = func.func_code.co_names for name,catalog in context.get_catalogs(subject): if func.once == True: pass else: for args in self.args_list: my_globals.update(zip(self.arg_fields,args))
Python
# -*- coding:utf-8 -*- #depreated 已经被废弃 import unittest import numpy from wolfox.foxit.dune.dyn_service import * from wolfox.foxit.dune.models import XDayQuote from wolfox.foxit.dune.test_common import prepare,clean class DynDataTest(unittest.TestCase): def setUp(self): prepare() def tearDown(self): clean() def test_init(self): ds1 = DynData(XDayQuote,excluded_fields=('id','tstock'),order_fields=('tdate',),mandatory_fields=('tdate',),condition_functor=lambda stock_id,begin,end : ' tstock_id = %d and tdate>=%d and tdate<=%d' % (stock_id,begin,end)) self.assertEquals('dune_xdayquote',ds1.table_name) self.assertEquals(set(['topen','tclose','thigh','tlow','tdate','tamount','tvolume','tavg']),ds1.fields) def test_set_required_fields(self): ds1 = DynData(XDayQuote,excluded_fields=('id','tstock'),order_fields=('tdate',),mandatory_fields=('tdate',),condition_functor=lambda stock_id,begin,end : ' tstock_id = %d and tdate>=%d and tdate<=%d' % (stock_id,begin,end)) ds1.set_required_fields('topen','tclose') self.assertEquals(set(['topen','tclose','tdate']),ds1.required_fields) self.assertRaises(AssertionError,ds1.set_required_fields,'tstock') #字段不在允许范围内 self.assertRaises(AssertionError,ds1.set_required_fields,'id') #字段不在允许范围内 self.assertRaises(AssertionError,ds1.set_required_fields,'t_none') #字段非法 def test_records2arrays(self): ds1 = DynData(XDayQuote,excluded_fields=('id','tstock'),order_fields=('tdate',),mandatory_fields=('tdate',),condition_functor=lambda stock_id,begin,end : ' tstock_id = %d and tdate>=%d and tdate<=%d' % (stock_id,begin,end)) ds1.set_required_fields('topen','tclose') #print ds1.required_fields records = [(100,20010101,101),(110,20010102,111),(120,20010103,121)] rev = ds1.records2arrays(records) #先验证数据类型 self.assertEquals(numpy.ndarray,type(rev['topen'])) self.assertEquals(numpy.ndarray,type(rev['tclose'])) self.assertEquals(numpy.ndarray,type(rev['tdate'])) #再验证数据 self.assertEquals([100,110,120],list(rev['topen'])) self.assertEquals([101,111,121],list(rev['tclose'])) self.assertEquals([20010101,20010102,20010103],list(rev['tdate'])) def test_records2arrays_zerosize(self): ds1 = DynData(XDayQuote,excluded_fields=('id','tstock'),order_fields=('tdate',),mandatory_fields=('tdate',),condition_functor=lambda stock_id,begin,end : ' tstock_id = %d and tdate>=%d and tdate<=%d' % (stock_id,begin,end)) ds1.set_required_fields('topen','tclose') #验证size为0的情况 records = [] rev = ds1.records2arrays(records) #先验证数据类型 self.assertEquals(numpy.ndarray,type(rev['topen'])) self.assertEquals(numpy.ndarray,type(rev['tclose'])) self.assertEquals(numpy.ndarray,type(rev['tdate'])) #再验证数据 self.assertEquals([],list(rev['topen'])) self.assertEquals([],list(rev['tclose'])) self.assertEquals([],list(rev['tdate'])) def test_get_arrays(self): ds1 = DynData(XDayQuote,excluded_fields=('id','tstock'),order_fields=('tdate',),mandatory_fields=('tdate',),condition_functor=lambda stock_id,begin,end : ' tstock_id = %d and tdate>=%d and tdate<=%d' % (stock_id,begin,end)) ds1.set_required_fields('topen','tclose') rev = ds1.get_arrays('SH00000X',0,99999999) #先验证数据类型, 因为是真实测试,所以尽管records2arrays中验证了(为虚拟测试),这里仍然验证为上 self.assertEquals(numpy.ndarray,type(rev['topen'])) self.assertEquals(numpy.ndarray,type(rev['tclose'])) self.assertEquals(numpy.ndarray,type(rev['tdate'])) #再验证数据 self.assertEquals([12000,0],list(rev['topen'])) self.assertEquals([12500,0],list(rev['tclose'])) self.assertEquals([20070705, 20080705],list(rev['tdate'])) class BasicDataTest(unittest.TestCase): def setUp(self): prepare() def tearDown(self): clean() def test_init(self): b1 = BasicData(StockCode,('id','total_size','outstanding_size'),u" exchange_id in ('上海证券交易所','深圳证券交易所')") self.assertEquals('dune_stockcode',b1.table_name) def test_get_records(self): b1 = BasicData(StockCode,('id','total_size','outstanding_size')," exchange_id in ('SHSE','SZSE')") records = b1.get_records() self.assertTrue(len(records)>0) self.assertTrue('SH00000X' in records) self.assertTrue('SH00TEST' not in records) self.assertEquals((0,0),records['SH00000X'][1:]) class ModuleTest(unittest.TestCase): def setUp(self): prepare() def tearDown(self): clean() def test_daysource(self): for s in dyn_source: #通透性测试 s.set_required_fields() #确认默认情况下字段之间的包含关系 s.get_arrays('SH00000X') def test_basicsource(self): for s in basic_source: #通透性测试 s.get_records()
Python
# -*- coding: utf-8 -*- ''' 基本的批量数据操作 SqlStore: 基本上以纯sql实现 NormalStore: 以Django Orm实现 这里有两个问题: 1. sqlite的事务独占访问问题. 当django/sql事务未完成时,sqlite文件不能以写模式再次打开 2. 如果SqlStore的Conn不是从Django得到的,而是直接针对db文件打开。则可能一个较大跨度中的操作不是在同一个连接中, 也相当于在两个互相隔离的事务里,这些操作的相互直接的逻辑影响无法得到(比如先同步code在导入数据). 这个问题比较严重。因此,需要完全基于sql或完全基于django(但可以从中得到connection)的解决方案 目前,传入到SqlStore的Conn,也必须是从Django得到的。否则有逻辑问题。 但是,django的conn使用方式比原始的connection大概要慢3倍 ''' import logging import sqlite3 from django.db import transaction from wolfox.foxit.dune.models import StockCode,Corporation,StockCodeHistory,Mapping,SDayQuote,XDayQuote,PowerInfo,Report,CatalogSubject,Catalog from wolfox.foxit.base.common import createQuoteFromDb,createXInfoFromDb,DataObject logger = logging.getLogger('foxit.dune.store') class SqlStore(object): '''sql实现,只处理日行情数据 ''' def __init__(self,conn): self.conn = conn def query(self,conn,sql): cursor = conn.cursor() cursor.execute(sql) return cursor.fetchall() def query2(self,conn,sql,*args): #特定于django,即这个函数的sql中只支持format方式,并且只支持%s cursor = conn.cursor() cursor.execute(sql,args) return cursor.fetchall() def get_codes_id_map(self,conn): id_codes = self.query(conn,"select id,code from dune_stockcode") code2id = dict([(r[1],r[0]) for r in id_codes]) id2code = dict([(r[0],r[1]) for r in id_codes]) return code2id,id2code def get_id2code(self): #初始化不能在__init__中,会导致django测试问题,因为只是全局初始化一次,因此竞争情况较少出现 try: return self.id2code except: self.reset_code_id_mapping(self.conn) return self.id2code def get_code2id(self): try: return self.code2id except: self.reset_code_id_mapping(self.conn) return self.code2id def reset_code_id_mapping(self,conn): self.code2id,self.id2code = self.get_codes_id_map(conn) def organize_tuples2quotes(self,quotes): ''' 将fetchall返回的9元组记录集合转换为Quote,并按照tstock组织成dict 这样就不需要在order by中添加code了 ''' records_map = {} for tstock,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount in quotes: cur = createQuoteFromDb(tstock,tdate,topen,tclose,thigh,tlow,tvolume,tamount,tavg) records_map.setdefault(tstock,[]).append(cur) return records_map def organize_tuples2quotes2(self,quotes): ''' 将fetchall返回的9元组记录集合转换为Quote,并按照tstock组织成dict 按照已经按tstock,date排序的方式走 效率提高很大 ''' records_map = {} curlist = None curstock = '' for tstock,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount in quotes: cur = createQuoteFromDb(tstock,tdate,topen,tclose,thigh,tlow,tvolume,tamount,tavg) if not curlist or curstock != tstock: curlist = records_map.setdefault(tstock,[]) curstock = tstock curlist.append(cur) return records_map def organize_tuples2quotes2_b(self,quotes): ''' 将fetchall返回的9元组记录集合按照tstock组织成dict,不再做转换 按照已经按tstock,date排序的方式走 因为去掉了生成记录的部分,效率提高很大 ''' records_map = {} curlist = None curstock = '' for quote in quotes: if not curlist or curstock != quote[0]: curlist = records_map.setdefault(quote[0],[]) curstock = quote[0] curlist.append(quote) return records_map def organize_tuples2quotes2_c(self,quotes): ''' 将fetchall返回的9元组记录集合按照tstock组织成dict,不再做转换 按照已经按tstock,date排序的方式走 效率和b比没有提高,估计list的extend实现不比append高效。 ''' records_map = {} if not quotes: return records_map curstock = quotes[0][0] i,k=0,0 for quote in quotes: if curstock != quote[0]: curlist = records_map.setdefault(curstock,[]) curlist.extend(quotes[k:i]) curstock = quote[0] k=i i+=1 curlist = records_map.setdefault(quotes[-1][0],[]) curlist.extend(quotes[k:]) #最后一组 return records_map remove_squotes_sql = "delete from dune_sdayquote where tdate between %d and %d" def remove_squotes(self,conn,begin=0,end=99999999): ''' 删除指定时间范围内的的原始记录. 删除时间范围 [begin,end) ''' cursor = conn.cursor() cursor.execute(self.remove_squotes_sql % (begin,end)) #cursor.close() #django文档中没有指出需要关闭这个cursor def remove_squotes2(self,conn,stocks,begin=0,end=99999999): ''' 删除指定stocks,时间范围内的原始记录. stocks为stockname列表 删除时间范围 [begin,end) ''' condition = ' and sstock in (%s)' % ','.join(["'%s'" % stock for stock in stocks]) #如果stocks为空,则为(),也符合sql语法 cursor = conn.cursor() cursor.execute((self.remove_squotes_sql + condition) % (begin,end)) def remove_xquotes(self,conn,begin=0,end=99999999): ''' 删除指定时间范围内的的Xed记录. source=1为分析家 删除时间范围 [begin,end) ''' cursor = conn.cursor() cursor.execute('delete from dune_xdayquote where tdate between %d and %d - 1' % (begin,end)) #cursor.close() #django文档中没有指出需要关闭这个cursor def remove_xquotes2(self,conn,stocks,begin=0,end=99999999): ''' 从dune_xdayquote删除数据 stocks为stock_codes source=1为分析家 删除时间范围 [begin,end) ''' cursor = conn.cursor() subquery = 'select id from dune_stockcode where code in (%s)' % ','.join(["'%s'" % stock for stock in stocks]) #如果stocks为空,则为(),也符合sql语法 cursor.execute('delete from dune_xdayquote where tstock_id in (%s) and tdate between %d and %d-1' % (subquery,begin,end)) def get_latest_squote_day(self,conn,period='day'): cursor = conn.cursor() cursor.execute('select max(tdate) from dune_s'+period+'quote') return cursor.fetchone()[0] or 0 #如果为None则返回0. 当不存在符合条件的纪录时,sqlite3返回的是None def get_latest_xquote_day(self,conn,period='day'): cursor = conn.cursor() cursor.execute('select max(tdate) from dune_x'+period+'quote') return cursor.fetchone()[0] or 0 #如果为None则返回0. 当不存在符合条件的纪录时,sqlite3返回的是None def get_latest_hour_squote_day(self,conn): return self.get_latest_squote_day(conn,period='hour')/100 def get_latest_hour_xquote_day(self,conn): return self.get_latest_xquote_day(conn,period='hour')/100 def get_latest_xquote_close(self,conn,stock,dfrom='29000101'): cursor = conn.cursor() cursor.execute('select tclose from dune_xdayquote where tdate = (select max(tdate) from dune_xdayquote where tdate < %d and tstock_id=%d) and tstock_id=%d' % (dfrom,stock,stock)) tcs = cursor.fetchone() return tcs[0] if tcs else 0 #如果为None则返回0. 当不存在符合条件的纪录时,sqlite3返回的是None def add_squotes(self,conn,quotes,period='day'): ''' 成批导入数据(pyformat风格). 功能同add_squotes_tuple quotes为元素是tcommon.Quote类型对象的列表 source_id=1是分析家数据源 由调用方决定事先是否需要先执行同时间段的清理工作 这类直接的sql字符串实现的方式,性能上和安全性上不如类似于prepared statement的方式,但是消除了不同的驱动以及django自身所带来的parameters style不同的问题 ''' #logger.debug('get cursor......') cursor = conn.cursor() sql = "insert into dune_s"+period+"quote(sstock,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount) values('%(tstock)s',%(tdate)s,%(topen)s,%(tclose)s,%(thigh)s,%(tlow)s,%(tavg)s,%(tvolume)s,%(tamount)s)" #logger.debug('begin add quote......') for nth,quote in enumerate(quotes): #print u'导入第%d条:%s' % (nth+1,quote) #if (nth + 1)%1000 == 1: # logger.debug(u'导入第%d条:%s',nth+1,quote) cursor.execute(sql % quote) #cursor.close() #django文档中没有指出需要关闭这个cursor def add_hour_squotes(self,conn,quotes): self.add_squotes(conn,quotes,period='hour') def add_quotes(self,conn,quotes,period='day'): ''' 成批导入数据(pyformat风格). 由调用方决定事先是否需要先执行同时间段的清理工作 对存在对应stockcode记录的quote,转移到xdayquote 反之转移到sdayquote 这类直接的sql字符串实现的方式,性能上和安全性上不如类似于prepared statement的方式,但是消除了不同的驱动以及django自身所带来的parameters style不同的问题 ''' logger.debug('get cursor......') cursor = conn.cursor() ssql = "insert into dune_s"+period+"quote(sstock,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount) values( '%(tstock)s',%(tdate)s,%(topen)s,%(tclose)s,%(thigh)s,%(tlow)s,%(tavg)s,%(tvolume)s,%(tamount)s)" xsql = "insert into dune_x"+period+"quote(tstock_id,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount) values( '%(tstock)s',%(tdate)s,%(topen)s,%(tclose)s,%(thigh)s,%(tlow)s,%(tavg)s,%(tvolume)s,%(tamount)s)" logger.debug('begin add quote......') #print 'code...................' self.reset_code_id_mapping(conn) #for code in self.code2id:print code for nth,quote in enumerate(quotes): #print u'导入第%d条:%s' % (nth+1,quote) #print quote.tstock if (nth + 1)%1000 == 1: logger.debug(u'导入第%d条:%s',nth+1,quote) if quote.tstock in self.code2id: quote.tstock = self.code2id[quote.tstock] #print xsql % quote cursor.execute(xsql % quote) #to xdayquote else: #to sdayquote #cursor.execute(ssql % quote) self.add_squotes(conn,[quote],period=period) #cursor.close() #django文档中没有指出需要关闭这个cursor def add_hour_quotes(self,conn,quotes): self.add_quotes(conn,quotes,period='hour') def add_squotes_tuple(self,conn,quotes): ''' 成批导入数据(tuple风格),容易出错 quotes为元素是tcommon.Quote类型对象的列表 source_id=1是分析家数据源 由调用方决定事先是否需要先执行同时间段的清理工作 这类直接的sql字符串实现的方式,性能上和安全性上不如类似于prepared statement的方式,但是消除了不同的驱动以及django自身所带来的parameters style不同的问题 ''' cursor = conn.cursor() sql = "insert into dune_sdayquote(sstock,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount) values('%s',%d,%d,%d,%d,%d,%d,%d,%d)" for quote in quotes: #print sql % quote.to_tuple() cursor.execute(sql % quote.to_tuple()) #cursor.close() #django文档中没有指出需要关闭这个cursor def transfer_xquotes(self,conn,begin=0,end=99999999): '''从DayQuote向XDayQuote倒数据. [begin,end)为时间区间 1为分析家数据源. 必须保证sdayquote的sstock等于标准代码 由调用方决定事先是否需要先执行同时间段的清理工作 ''' cursor = conn.cursor() cursor.execute("insert into dune_xdayquote(tstock_id,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount) " " select ds.id,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount" " from dune_sdayquote sq" " join dune_stockcode ds on ds.code=sq.sstock" " where ds.id in (select id from dune_stockcode where stype_id in('STOCK','FUND','INDEX')) " " and tdate between %s and %s - 1",(begin,end)) def transfer_xquotes2(self,conn,stocks,begin=0,end=22000101,period='day',dfunc=lambda d:d): '''从DayQuote向XDayQuote倒数据. stocks为指定的标准代码的code集合,对这些code,不再判断是否是合适的stock type [begin,end)为时间区间 1为分析家数据源. 必须保证sdayquote的sstock等于标准代码 由调用方决定事先是否需要先执行同时间段的清理工作 ''' cursor = conn.cursor() str_stocks = '(%s)' % ','.join(["'%s'" % stock for stock in stocks]) #如果stocks为空,则为(),也符合sql语法 cursor.execute("insert into dune_x"+period+"quote(tstock_id,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount) " " select ds.id,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount" " from dune_s"+period+"quote sq " " join dune_stockcode ds on ds.code = sq.sstock " " where sq.sstock in " + str_stocks + " and tdate between %s and %s - 1 " ,(dfunc(begin),dfunc(end))) def transfer_hour_xquotes2(self,conn,stocks,begin=0,end=22000000): self.transfer_xquotes2(conn,stocks,begin,end,period='hour',dfunc=lambda d:d*100) find_squotes_sql = "select sstock as code,tdate,topen,tclose,thigh,tlow,tavg,tvolume,tamount" \ " from dune_sdayquote" \ " where tdate between %s and %s - 1 " order_by = " order by code,tdate" def get_squotes(self,conn,begin=0,end=99999999): '''检索指定时间范围内的原始行情数据 [begin,end)为时间区间 1为分析家数据源. 返回值为{source_code:records}这样的字典 ''' quotes = self.query(conn,(self.find_squotes_sql + self.order_by) % (begin,end)) return self.organize_tuples2quotes2(quotes) def get_squotes2(self,conn,stocks,begin=0,end=99999999): '''检索指定时间范围内指定股票的原始行情数据 stocks为source_code的列表 [begin,end)为时间区间 1为分析家数据源. 返回值为{source_code:records}这样的字典 ''' condition = 'and sstock in (%s)' % ','.join(["'%s'" % stock for stock in stocks]) #如果stocks为空,则为(),也符合sql语法 quotes = self.query(conn,(self.find_squotes_sql + condition + self.order_by) % (begin,end)) return self.organize_tuples2quotes2(quotes) find_xquotes_sql = "select code,tdate,topen,tclose,thigh,tlow,tavg,cast(tvolume+0.5 as int),tamount" \ " from dune_xdayquote dx" \ " join dune_stockcode dc on dc.id = dx.tstock_id" \ " where tdate between %s and %s - 1 " def get_xquotes(self,conn,begin=0,end=99999999): '''检索制定时间范围内的已经除权的行情数据 [begin,end)为时间区间 返回值为{source_code:records}这样的字典 ''' quotes = self.query(conn,(self.find_xquotes_sql + self.order_by) % (begin,end)) return self.organize_tuples2quotes2(quotes) def get_xquotes2(self,conn,stocks,begin=0,end=99999999): '''检索制定时间范围内的已经除权的行情数据 stocks为standard_code的列表 [begin,end)为时间区间 返回值为{source_code:records}这样的字典 ''' #print stocks return self.organize_tuples2quotes2(self._fetch_xquotes2(conn,stocks,begin,end)) def _fetch_xquotes2(self,conn,stocks,begin=0,end=99999999): '''检索制定时间范围内的已经除权的行情数据 stocks为standard_code的列表 [begin,end)为时间区间 返回值为{source_code:records}这样的字典 ''' condition = 'and code in (%s)' % ','.join(["'%s'" % stock for stock in stocks]) #如果stocks为空,则为(),也符合sql语法 #print condition quotes = self.query(conn,(self.find_xquotes_sql + condition + self.order_by) % (begin,end)) #print len(quotes) return quotes def ref_sql(self,period='day'): return '''select dx.topen,dx.tclose,dx.thigh,dx.tlow,dx.tavg,dx.tamount,cast(dx.tvolume+0.5 as int) from dune_x'''+period+'''quote base left join dune_x'''+period+'''quote dx on dx.tdate=base.tdate and dx.tstock_id = %(stock_id)s where base.tstock_id=%(base_id)s and base.tdate between %(begin)s and %(end)s order by base.tdate ''' #volume中的数据可能为非整型,需要转换 def get_refbased_xquotes(self,conn,base_id,stock_id,begin=0,end=99999999): ''' 获取基于ref的行情数据,其中base_id为参考序列的id,stock_id为实际序列的id 返回的序列长度为base_id代表的序列在该时间段内的长度 base.tdate不必要出现 ''' end -= 1 #满足[begin,end)的惯例 sql = self.ref_sql('day') % locals() logging.debug('get_refbased_xquotes:%s' % sql) return self.query(conn,sql) def get_refbased_hour_xquotes(self,conn,base_id,stock_id,begin=0,end=99999999): ''' 获取基于ref的小时行情数据,其中base_id为参考序列的id,stock_id为实际序列的id 返回的序列长度为base_id代表的序列在该时间段内的长度 base.tdate不必要出现 ''' begin = begin * 100 end = end * 100 end -= 1 #满足[begin,end)的惯例 sql = self.ref_sql(period='hour') % locals() logging.debug('get_refbased_hour_xquotes:%s' % sql) return self.query(conn,sql) def add_stock_to_catalog(self,conn,name,subject,stocks): '''向板块中添加成员 name: 板块名. 如果板块不存在,则会创建该板块 subject: 板块类别名 stocks: 标准stockcode列表,为板块成员 调用者需要确保stocks中的成员都不是板块的老成员,否则会抛出IntegrityError ''' cs = CatalogSubject.objects.get(name=subject) nc,created = Catalog.objects.get_or_create(name=name,defaults={'subject':cs}) #nc,created = Catalog.objects.get_or_create(name=name,subject=cs) #这样会抱错DoesNotExist: Catalog matching query does not exist.,貌似是给的条件太多了,name本身是unique的. 也可能是django自己的问题 condition = ' code in (%s)' % ','.join(["'%s'" % stock for stock in stocks]) #如果stocks为空,则为(),也符合sql语法 sql = "insert into dune_stockcode_catalogs(stockcode_id,catalog_id)" \ " select ds.id,'%s'" \ " from dune_stockcode ds " \ " where %s " \ % (nc.id,condition) cursor = conn.cursor() cursor.execute(sql) def xit_old(self,conn,xinfos): '''反向除权(20090518之前的除权方式) xinfos为PowerInfo对象的列表。必须满足xinfo.state=0. 里面不检验 反向除权(即当前价不变,更动除权前的价量)计算公式 按照成交金额不变的模式来计算 配送股价格:cur = (old + pgbl*pgj)/(1+sgbl+pgbl) 我们现在以1/1000作为pgbl和sgbl的基本单位 实际上是 (old*1000 + pgj*pgbl) /(1000+pgbl+sgbl) 分红价格:cur = old - fhbl 因为配送股和分红同时的话,则先分红再送配,所以组合之后有: newprice = ((oldprice-fh)*1000 + pgj*pgbl) /(1000 + pgbl + sgbl) = (oldprice-fh) * (1000/(100+pgbl+sgbl)) + pgj*pgbl/(1000+pgbl+sgbl) 设 x = 1000/(1000+pgbl+sgbl) y = pgj*pgbl/(1000+pgbl+sgbl) 则 newp_rice = (oldprice - fh) * x + y Amount保持不变, new_volume=amount/new_avg_price ''' cursor = conn.cursor() for nth,xinfo in enumerate(xinfos): try: b = 1000.0 + xinfo.pgbl + xinfo.sgbl x = 1000/b y = xinfo.pgj * xinfo.pgbl / b if (nth+1)% 10 == 1: print u'%d : %s除权,executeday:%d,x=%s,y=%s,fhbl=%s' % (nth,xinfo.tstock.code,xinfo.execute_day,x,y,xinfo.fhbl) sql = "update dune_xdayquote set topen = cast((topen - %(fhbl)s)*%(x)s+%(y)s + 0.5 as int),tclose = cast((tclose - %(fhbl)s)*%(x)s + %(y)s + 0.5 as int),thigh = cast((thigh - %(fhbl)s)*%(x)s + %(y)s + 0.5 as int),tlow = cast((tlow - %(fhbl)s)*%(x)s + %(y)s + 0.5 as int),tavg = cast((tavg-%(fhbl)s)*%(x)s + %(y)s + 0.5 as int),tvolume = cast(tavg * tvolume/((tavg-%(fhbl)s)*%(x)s + %(y)s) + 0.5 as int) where tstock_id=%(stock)s and tdate < %(end)s" \ % {'stock':xinfo.tstock.id,'end':xinfo.execute_day,'fhbl':xinfo.fhbl,'x':x,'y':y} #print sql cursor.execute(sql) xinfo.day_state = 1 #print 'save xinfo',xinfo.tstock.code,xinfo.execute_day xinfo.save() except sqlite3.IntegrityError,inst: logger.warning(u'股票 %s 除权出错' % xinfo.tstock.code) def xit(self,conn,xinfos,period='day',dfunc=lambda d:d): '''反向的比例除权 xinfos为PowerInfo对象的列表。必须满足xinfo.state=0. 里面不检验 反向除权(即当前价不变,更动除权前的价量)计算公式 以除权日的前一个交易日收盘价为基准计算比例 oldprice = 基准日价格 newprice = ((oldprice-fh)*1000 + pgj*pgbl) /(1000 + pgbl + sgbl) = (oldprice-fh) * (1000/(100+pgbl+sgbl)) + pgj*pgbl/(1000+pgbl+sgbl) 设 x = 1000/(1000+pgbl+sgbl) y = pgj*pgbl/(1000+pgbl+sgbl) 则 newprice = (oldprice - fh) * x + y 复权比例 xrate = newprice / oldprice 这样,所有的除权日之前的价格,都按照 price * xrate 来计算 而Amount保持不变, new_volume=amount/new_avg_price=amount/(old_avg*xrate) = old_volume / xrate ''' cursor = conn.cursor() state_name = period + '_state' for nth,xinfo in enumerate(xinfos): try: b = 1000.0 + xinfo.pgbl + xinfo.sgbl x = 1000/b y = xinfo.pgj * xinfo.pgbl / b if (nth+1)% 10 == 1: print u'%d : %s除权,executeday:%d,x=%s,y=%s,fhbl=%s' % (nth,xinfo.tstock.code,xinfo.execute_day,x,y,xinfo.fhbl) ori_close = self.get_latest_xquote_close(conn,xinfo.tstock.id,xinfo.execute_day) new_close = (ori_close - xinfo.fhbl) * x + y if ori_close > 0 and new_close > 0: xrate = new_close / ori_close else: xrate = 1 logger.warning(u'警告,ori_close=0或new_close=0,stock_id=%s,execute_day=%s,ori_close=%s,new_close=%s,b=%s,x=%s,y=%s,fhbl=%s' % (xinfo.tstock.id,xinfo.execute_day,ori_close,new_close,b,x,y,xinfo.fhbl)) #print xrate,ori_close,new_close sql = "update dune_x"+period+"quote set topen = cast(topen * %(xrate)s + 0.5 as int),tclose = cast(tclose * %(xrate)s + 0.5 as int),thigh = cast(thigh * %(xrate)s + 0.5 as int),tlow = cast(tlow * %(xrate)s + 0.5 as int),tavg =cast(tavg * %(xrate)s + 0.5 as int),tvolume = cast(tvolume / %(xrate)s + 0.5 as int) where tstock_id=%(stock)s and tdate < %(end)s" \ % {'stock':xinfo.tstock.id,'end':dfunc(xinfo.execute_day),'xrate':xrate} cursor.execute(sql) #print sql #xinfo.state = 1 setattr(xinfo,state_name,1) #print 'save xinfo',xinfo.tstock.code,xinfo.execute_day,sql xinfo.save() except sqlite3.IntegrityError,inst: logger.warning(u'股票 %s 除权出错' % xinfo.tstock.code) def xit_hour(self,conn,xinfos): #小时除权 self.xit(conn,xinfos,period='hour',dfunc=lambda d:d*100) def gbjg(self,conn): #股本结构 cursor = conn.cursor() sql = '''select x.sid,tpm,dr.zgb,dr.ag from (select tstock_id as sid,ag,max(tperiod) as tpm from dune_report group by tstock_id) as x,dune_report dr on dr.tstock_id = x.sid and dr.tperiod=tpm''' jgs = self.query(conn,sql) rev = [] for jg in jgs: dobj = DataObject() dobj.id = jg[0] dobj.date = jg[1] dobj.zgb = jg[2] dobj.ag = jg[3] rev.append(dobj) return rev class NormalStore(SqlStore): '''django实现的部分 ''' def __init__(self): from django.db import connection SqlStore.__init__(self,connection) def add_stock_to_catalog2(self,name,stocks): '''向板块中添加成员 name: 板块名. 必须存在该板块 stocks: 标准stockcode列表,为板块成员 插入前stocks中成员若已经属于该板块,无异常. 相当于noop(pass)操作 ''' #print name catalog = Catalog.objects.get(name=name) #如果板块不存在,这里会抛出异常 stock_set = StockCode.objects.all() stockcodes = set(stock_set.values_list('code')) #每个元素为(code,)形式的元组 #[stock_set.get(code = code).catalogs.add(catalog) for code in stocks if (code,) in stockcodes] [catalog.stocks.add(stock_set.get(code = code)) for code in stocks if (code,) in stockcodes] def get_stockmap(self): try: self.stockmap except AttributeError: self.stockmap = dict([(stock.code,stock) for stock in list(StockCode.objects.all())]) rev = self.stockmap return rev def add_stock_to_catalog3(self,name,stocks): '''向板块中添加成员. 2太慢,故作优化 name: 板块名. 必须存在该板块 stocks: 标准stockcode列表,为板块成员 插入前stocks中成员若已经属于该板块,无异常. 相当于noop(pass)操作 ''' #print name catalog = Catalog.objects.get(name=name) #如果板块不存在,这里会抛出异常 #stockmap = dict([(stock.code,stock) for stock in list(StockCode.objects.all())]) stockmap = self.get_stockmap() #stockmap移出后速度加快1倍 [catalog.stocks.add(stockmap[code]) for code in stocks if code in stockmap] def add_mappings(self,mappings,source): '''添加源-标准的映射表(映射表不更新). 这块功能现在已经弱化,只为导入时source_code无法根据规则转化为standard的提供帮助 mappings为(source_code,StockCode对象)的列表 source为数据源 ''' for scode,sobj in mappings: mapping = Mapping.objects.create(source_code = scode,standard=sobj,source=source) def update_codes(self,codes): '''更新代码表, 实质上code是不能更新的,更新以后只能算新股票 codes: 元素为(exchange,code,name,stocktype)的列表 返回添加的代码列表 ''' code_query_set = StockCode.objects.all() code_set = set([ code[0] for code in code_query_set.values_list('code')]) new_codes = [ code for code in codes if code[1] not in code_set ] exist_codes = [ (code[1],code[2]) for code in codes if code[1] in code_set ] for exchange,code,name,stype in new_codes: new_corp = Corporation.objects.create(name=name) stock = StockCode.objects.create(corporation = new_corp,code = code,name = name, exchange=exchange,stype=stype) StockCodeHistory.objects.create(scode=stock,name=name) for code,name in exist_codes: exist_obj = StockCode.objects.get(code=code) if exist_obj.name != name: exist_obj.name = name exist_obj.save() StockCodeHistory.objects.create(scode=stock,name=name) return [ code[1] for code in new_codes ] def update_codes2(self,pairs,exchange,stype): '''更新代码表, 这个早先的接口性能较好,但操作太不自然,废弃 pairs: 元素为(code,name)的列表 exchage: 交易所对象 stype: 证券类型 返回添加的(代码,对象)列表 ''' codes = StockCode.objects.filter(exchange=exchange,stype=stype).values_list('code','name') codeset = {} codeset.update(codes) print codeset new_codes = [] for code,name in pairs: if code not in codeset: new_corp = Corporation.objects.create(name=name) codes = StockCode.objects.filter(exchange=exchange,stype=stype).values_list('code','name') new_obj = StockCode.objects.create(code = code,name = name,corporation = new_corp,exchange=exchange,stype=stype) new_codes.append((code,new_obj)) elif codeset[code] != name: exist_obj = StockCode.objects.get(code=code) exist_obj.name = name exist_obj.save() return new_codes def add_xinfos(self,xinfos): ''' 添加除权数据 xinfos为tcommon.XInfo类型的记录列表,其tstock为source_code ''' code2obj = self.get_stockmap() xinfos = [xinfo for xinfo in xinfos if xinfo.tstock in code2obj] for x in xinfos: pi = PowerInfo(tstock=code2obj[x.tstock],sgbl=x.tsgbl,pgbl=x.tpgbl,fhbl=x.tfhbl,zfs=x.tzfs, \ zfj=x.tzfj,jjs=x.tjjs,register_day=x.tregisterday,execute_day=x.texecuteday) pi.save() def add_reports(self,reports): ''' 添加report reports: 元素为tcommon.Report类型的列表 字段变换:tperiod = r.tdate ''' code2obj = self.get_stockmap() reports = [report for report in reports if report.tstock in code2obj] for r in reports: stock = code2obj[r.tstock] rt = Report(tstock=stock,announce_day=r.treleaseday, \ tperiod=r.tdate,zgb=r.tzgb,ag=r.tag,bg=r.tbg,hg=r.thg, \ mgwfplr=r.tmgwfplr,mggjj=r.tmggjj,mgjzc=r.tmgjzc,mgsy=r.tmgsy) rt.save() self.update_stock_size(stock,r.tzgb,r.tag) def update_stock_size(self,stock,zgb,ag,edate=0): if stock.total_size != zgb or stock.outstanding_size != ag: stock.total_size = zgb stock.outstanding_size = ag stock.save() StockCodeHistory.objects.create(scode=stock,name=stock.name,total_size=zgb,outstanding_size=ag) return True return False def get_xinfo_keys(self,begin,end): ''' 找出时间段内的除权纪录键, 返回(source_code,execute_day)组成的列表 ''' xinfos = PowerInfo.objects.filter(execute_day__range=(begin,end-1)).order_by('execute_day') \ .values_list('tstock__id','execute_day') smap = self.get_id2code() return [ (smap[xinfo[0]],xinfo[1]) for xinfo in xinfos ] def get_report_keys(self,begin,end): ''' 找出时间段内的报表纪录键 返回tcommon.XInfo列表,每个纪录的tstock以code表示 ''' reports = Report.objects.filter(announce_day__range=(begin,end-1)).order_by('tperiod') \ .values_list('tstock__id','tperiod') smap = self.get_id2code() return [ (smap[report[0]],report[1]) for report in reports ]
Python
from django.conf.urls.defaults import * urlpatterns = patterns('', # Example: # (r'^foxit/', include('foxit.foo.urls')), # Uncomment this for admin: (r'^admin/', include('django.contrib.admin.urls')), )
Python
# -*- coding:utf-8 -*- #本package用于技术和应用上的试验
Python
# -*- coding:utf-8 -*- from decorator import decorator
Python
# -*- coding: utf-8 -*- import unittest import os.path from wolfox.foxit.base.tutils import * class ModuleTest(unittest.TestCase): def testTempFile(self): #测试mktemp,removetemp fo = mktemp('test code') self.assertEquals('test code',open(fo['name']).read()) removetemp(fo) self.assertRaises(IOError,open,fo['name']) def testParseName(self): self.assertEquals("zzz",parseName("c:/xxx/yyy/zzz.txt")) self.assertEquals("zzz",parseName("c:/zzz.txt")) self.assertEquals("zzz",parseName("xxx/yyy/zzz.txt")) self.assertEquals("zzz",parseName("zzz.txt")) self.assertEquals("zzz",parseName("zzz")) def testLoggingConfig(self): #通路测试, import logging logging_config('a.log','b.log') logging_config('a.log','b.log',logging.ERROR,logging.INFO) logging_config('c.log') logging_config('at.log','s.log') logger = logging.getLogger('tuilts.test') logger.debug('debug msg') logger.info('info msg') logger.warning('warning msg') self.assertTrue(True) #logging.shutdown() #关闭日志系统之后才能删除文件,但不能这么暴力,会把外围测试驱动者的logging也关掉 logger = logging.getLogger() for handler in log_handlers: logger.removeHandler(handler) handler.close() os.remove('a.log') os.remove('b.log') os.remove('c.log') os.remove('at.log') os.remove('s.log') def testLinelog(self): linelog('test line log') self.assertTrue(True) def testWriteRecord(self): fo = mktemp('') fh = open(fo['name'],'w') writerecord(fh,(1,2,3,4,5)) fh.close() removetemp(fo) def testWriteRecords(self): fo = mktemp('') fh = open(fo['name'],'w') writerecords(fh,(1,2,3,4,5),(3,4,5,6,7),('8a','a1',2,3,4)) fh.close() removetemp(fo) if __name__ == "__main__": unittest.main()
Python
# -*-coding:utf-8 -*- VOLUME_BASE = 100L; #手 AMOUNT_BASE = 100000L; #百元 = 10000分 = 100000厘 class asdict(object): def __getitem__(self,key): #允许dict的调用方法 #print "getitem:" + key if(self.has_key(key)): return getattr(self,key) def has_key(self,key): return key in self.__slots__ #如果有继承容器父类,则也需要验证父类的 def __str__(self): """只有以cvs方式保存的时候(测试环境)才用到""" return ",".join((str(getattr(self,slot)) for slot in self.__slots__)) def asdict(self): ad = {} for slot in self.__slots__: ad[slot] = getattr(self,slot) return ad class DatedStock(asdict): __slots__ = "none" #必须设置slots,否则子类即便设置了slots属性,也会存在__dict__ def __cmp__(self,other): #print "in cmp" return self.tdate - other.tdate or self.tstock > other.tstock def __eq__(self,other): #以便用于Set或者用做dict的key #print "in eq" return self.tstock == other.tstock and self.tdate == other.tdate def __hash__(self): #print "in hash" return hash(str(self.tstock) + str(self.tdate)) def createQuoteFromSrc(tstock,tdate,topen,tclose,thigh,tlow,tvolume,tamount): #从数据源读取数据创建对象,传入的价格和量的数据都是float型的 quote = Quote() (quote.tstock,quote.tdate,quote.topen,quote.tclose,quote.thigh,quote.tlow,quote.tvolume,quote.tamount) = (tstock,tdate,f2_milli(topen),f2_milli(tclose),f2_milli(thigh),f2_milli(tlow),tvolume,f2_100(tamount)) quote.calcAvg() return quote def createQuoteFromDb(tstock,tdate,topen,tclose,thigh,tlow,tvolume,tamount,tavg): #从数据表读取数据创建对象,传入参数都已经是1/1000为单位的整数 quote = Quote() (quote.tstock,quote.tdate,quote.topen,quote.tclose,quote.thigh,quote.tlow,quote.tvolume,quote.tamount,quote.tavg) = (tstock,tdate,topen,tclose,thigh,tlow,tvolume,tamount,tavg) return quote xunitbase = 1000 class Quote(DatedStock): #在属性名字前加t的目的是在保证属性名和字段名同名的同时,避免与数据库的关键字冲突 """行情数据: 价格单位都是厘,成交量为手,成交金额为百元""" __slots__ = 'tstock','tdate','topen','tclose','thigh','tlow','tavg','tvolume','tamount' def __init__(self): #super(DatedStock,self).__init__(self) self.tstock = "AAAAAA" self.tdate = 99999999 self.topen = self.tclose = self.thigh = self.tlow = self.tavg = self.tvolume = self.tamount = 0 def calcAvg(self): if self.tvolume != 0: #先将成交金额单位调整为厘(*100000),然后去除以成交量,得到以厘为单位均价 self.tavg = int((self.tamount * AMOUNT_BASE + self.tvolume * VOLUME_BASE/2)/(self.tvolume*VOLUME_BASE)) else: self.tavg = self.tclose; def to_tuple(self): return self.tstock,self.tdate,self.topen,self.tclose,self.thigh,self.tlow,self.tavg,self.tvolume,self.tamount def createXInfoFromSrc(tstock,tregisterday,texecuteday,tpgbl,tsgbl,tfhbl,tpgj,tzfs=0,tzfj=0): #从数据源读取数据创建对象,传入的价格和量的数据都是float型的 xinfo = XInfo() (xinfo.tstock,xinfo.tregisterday,xinfo.texecuteday,xinfo.tpgbl,xinfo.tsgbl,xinfo.tfhbl,xinfo.tpgj,xinfo.tzfs,xinfo.tzfj) = (tstock,tregisterday,texecuteday,f2_milli(tpgbl),f2_milli(tsgbl),f2_milli(tfhbl),f2_milli(tpgj),f2_milli(tzfs),f2_milli(tzfj)) return xinfo def createXInfoFromDb(id,tstock,tregisterday,texecuteday,tpgbl,tsgbl,tfhbl,tpgj,tzfs,tzfj,tstate,tremark): #从数据表读取数据创建对象,传入参数都已经是1/1000为单位的整数 xinfo = XInfo() (xinfo.id,xinfo.tstock,xinfo.tregisterday,xinfo.texecuteday,xinfo.tpgbl,xinfo.tsgbl,xinfo.tfhbl,xinfo.tpgj,xinfo.tzfs,xinfo.tzfj,xinfo.tstate,xinfo.tremark) = (id,tstock,tregisterday,texecuteday,tpgbl,tsgbl,tfhbl,tpgj,tzfs,tzfj,tstate,tremark) return xinfo class XInfo(DatedStock): #除权信息 __slots__="id",'tstock','tsgbl','tpgbl','tfhbl','tpgj','tzfs','tzfj','tjjs','tregisterday','texecuteday','tstate','tremark' def __init__(self): self.id = 0 self.tstock = "AAAAAA" self.tregisterday = self.texecuteday = 99999999 self.tremark = "" self.tstate = 0; #未除权 self.tsgbl = self.tpgbl = self.tfhbl = self.tpgj = self.tzfs = self.tzfj = self.tjjs = 0 def __getattr__(self,name): #以便DateFilter if(name == "tdate"): return self.texecuteday def createReportFromSrc(tstock,ttype,treleaseday,tdate,tzgb,tbg,thg,tag,tmgwfplr,tmgsy,tmgjzc,tmggjj): #从数据源读取数据创建对象,传入的价格和量的数据都是float型的 report = Report() (report.tstock,report.ttype,report.treleaseday,report.tdate,report.tzgb,report.tbg,report.thg,report.tag,report.tmgwfplr,report.tmgsy,report.tmgjzc,report.tmggjj) = (tstock,ttype,treleaseday,tdate,int(tzgb),int(tbg),int(thg),int(tag),f2_milli(tmgwfplr),f2_milli(tmgsy),f2_milli(tmgjzc),f2_milli(tmggjj)) #assert report.zgb < 2000000000 return report def createReportFromDb(tstock,ttype,treleaseday,tdate,tzgb,tbg,thg,tag,tmgwfplr,tmgsy,tmgjzc,tmggjj,tremark): #从数据表读取数据创建对象,传入参数都已经调整完毕 report = Report() (report.tstock,report.ttype,report.treleaseday,report.tdate,report.tzgb,report.tbg,report.thg,report.tag,report.tmgwfplr,report.tmgsy,report.tmgjzc,report.tmggjj,report.tremark) = (tstock,ttype,treleaseday,tdate,tzgb,tbg,thg,tag,tmgwfplr,tmgsy,tmgjzc,tmggjj,tremark) return report class Report(DatedStock): #报表信息 __slots__= 'tstock','ttype','treleaseday','tzgb','tbg','thg','tag','tmgwfplr','tmgsy','tmgjzc','tmggjj','tremark' def __init__(self): self.tstock = "AAAAAA" self.ttype = 1 #1年2半年3季4月 0未知 self.tremark = "" self.treleaseday = 99999999 self.tdate = 9999 self.tzgb = self.tbg = self.thg = self.tag = self.tmgwfplr = self.tmgsy = self.tmgjzc = self.tmggjj = 0 def __getattr__(self,name): #以便DateFilter if(name == "tdate"): print self.treleaseday//100 return self.treleaseday//100 def f2_milli(fsrc): # float转换为0.001为单位的整数 return int(fsrc*1000 + 0.5) def f2_centi(fsrc): # float转换为0.01为单位的整数 return int(fsrc * 100 + 0.5) def f2_100(fsrc): # float转换为100为单位的整数 return int(fsrc/100.0 + 0.5) def f2_10000(fsrc): # float转换为100为单位的整数 return int(fsrc/10000.0 + 0.5) class DataObject(object):pass
Python
# -*- coding: utf-8 -*- #This project is licensed under the Apache License Version 2.0 #author: wycharon@gmail.com #一些工具类和函数 import os import sys,codecs import logging,logging.handlers LINELENGTH = 60 iseq = range(9999) #用于在list迭代中得到下标,如 [i for i,v in zip(iseq,sourcelist)] 将得到一个index列表 #两个临时文件的帮助函数. mktemp根据txt生成一个临时文件,removetemp删除这个临时文件 def mktemp(txt): from tempfile import mkstemp tpair = mkstemp() file(tpair[1],'w+').write(txt) return {'fd':tpair[0],'name':tpair[1]} def removetemp(temp): import os os.close(temp['fd']) os.remove(temp['name']) def parseName(filename):#去掉文件扩展名并获得不含路径的文件名,如c:\aaa\bbb.txt变为bbb,而bbb.txt也变为bbb return os.path.splitext(os.path.basename(filename))[0] log_handlers = [] def logging_config(mainfile,summaryfile=None,mainlevel = logging.DEBUG,summarylevel=logging.WARNING): ''' 配置logging mainfile为主要文件,用于记录mainlevel以上信息,采用轮换方式 summaryfile为概要文件,用于记录概要信息 ''' rootlogger = logging.getLogger() for handler in log_handlers: #移除之前的handlers rootlogger.removeHandler(handler) #print 'closing:',handler.baseFilename handler.close() #print 'closed:',handler.baseFilename log_handlers[:] = [] #清空,并避免global声明 rootlogger.setLevel(mainlevel) #最低级别 hmainfile = logging.handlers.RotatingFileHandler(mainfile,maxBytes=1024000,backupCount=3) hmainfile.setFormatter(logging.Formatter('%(name)s:%(funcName)s:%(lineno)d: %(asctime)s %(levelname)s %(message)s')) rootlogger.addHandler(hmainfile) log_handlers.append(hmainfile) if(summaryfile): hsummary = logging.FileHandler(summaryfile) hsummary.setLevel(summarylevel) hsummary.setFormatter(logging.Formatter('%(name)s:%(funcName)s:%(lineno)d: %(asctime)s %(levelname)s %(message)s')) rootlogger.addHandler(hsummary) log_handlers.append(hsummary) def linelog(msg): #在同一行覆盖显示日志输出 sys.stdout.write(unicode((u'\r%s%s' % (msg,' ' * (LINELENGTH - len(msg)))))) #.encode('gbk')) #适应输出编码为gbk def writerecord(filehandler,record): #用于循环的话比较浪费,基本不用于循环,只用于单行记录 format_string = (u'%s,' * len(record))[:-1] + '\n' filehandler.write(format_string % record) def writerecords(filehandler,*args): ''' 用于多个列表的同步输出,通常用于运算脚本的测试中 args必须都是列表 ''' length = len(args) assert length > 0 format_string = (u'%s,' * length)[:-1] + '\n' for record in zip(*args): filehandler.write(format_string % record)
Python
# -*- coding: utf-8 -*- """ 本文件用于验证fxj数据解码的正确性 """ import unittest from wolfox.foxit.base.common import Quote from wolfox.foxit.source import reader,filestore,fxj import os.path cur_dir = os.path.dirname(__file__) #test_dir = os.path.split(cur_dir)[0] #test_data_dir = os.path.join(test_dir,'data') test_data_dir = os.path.join(cur_dir,'test_data') class FxjTest(unittest.TestCase): def testDay(self): SRCNAME = os.path.join(test_data_dir,"quote_test2.dad") DESNAME = os.path.join(test_data_dir,"output/quote_day_test.txt") dayextractor = fxj.TradeExtractor() fxjreader = reader.Reader(dayextractor) records = fxjreader.read(SRCNAME) self.assertEquals(37,len(records)) #print len(records) fs = filestore.CSVStore() fs.open(DESNAME) try: fs.save(records) finally: fs.close() def testMin5(self): SRCNAME = os.path.join(test_data_dir,"m5_test.dad") DESNAME = os.path.join(test_data_dir,"output/m5_test.txt") m5extractor = fxj.TradeExtractor(fxj.min5_func) fxjreader = reader.Reader(m5extractor) records = fxjreader.read(SRCNAME) #print len(records) self.assertEquals(195,len(records)) fs = filestore.CSVStore() fs.open(DESNAME) try: fs.save(records) finally: fs.close() def testM5to60(self): SRCNAME = os.path.join(test_data_dir,"m5_test.dad") DESNAME = os.path.join(test_data_dir,"output/m5to60_test.txt") #SRCNAME = "../data/200908m.dad" #DESNAME = os.path.join(test_data_dir,"200908m.txt") m5extractor = fxj.M5to60Extractor() fxjreader = reader.Reader(m5extractor) records = fxjreader.read(SRCNAME) #self.assertEquals(17,len(records)) #print len(records) fs = filestore.CSVStore() fs.open(DESNAME) try: fs.save(records) finally: fs.close() def testXInfo(self): SRCNAME = os.path.join(test_data_dir,"xtest.pwr") DESNAME = os.path.join(test_data_dir,"output/xtest.pow") extractor = fxj.XExtractor() fxjreader = reader.Reader(extractor) records = fxjreader.read(SRCNAME) fs = filestore.CSVStore() fs.open(DESNAME) try: fs.save(records) finally: fs.close() def testReport(self): SRCNAME = os.path.join(test_data_dir,"report_test.fin") DESNAME = os.path.join(test_data_dir,"output/report_test.rpt") extractor = fxj.ReportExtractor() fxjreader = reader.Reader(extractor) records = fxjreader.read(SRCNAME) fs = filestore.CSVStore() fs.open(DESNAME) try: fs.save(records) finally: fs.close() def testCatalog(self): SRCNAME = os.path.join(test_data_dir,"xizang.BLK") DESNAME = os.path.join(test_data_dir,"output/xizang.txt") extractor = fxj.CatalogExtractor() fxjreader = reader.Reader(extractor) records = fxjreader.read(SRCNAME) fs = filestore.CSVStore() fs.open(DESNAME) try: fs.save(records) finally: fs.close() class CodeReaderTest(unittest.TestCase): def test_find_type(self): reader = fxj.CodeReader() self.assertEquals(None,reader.find_type('SHX00120')) self.assertEquals(u'股票',reader.find_type('SH600120')) self.assertEquals(u'基金',reader.find_type('SH500020')) def test_parse(self): reader = fxj.CodeReader() self.assertEquals(('SH','SH000001',u'上证指数',u'指数'),reader.parse(u'000001\t上证指数\n'.encode('gbk'),'SH')) def test_readlines(self): #通透测试 reader = fxj.CodeReader() src_name = os.path.join(test_data_dir,"SZ.SNT") reader.readlines(src_name) self.assertTrue(True) def test_read_codes(self): #通透测试 reader = fxj.CodeReader() src_name = os.path.join(test_data_dir,"SZ.SNT") results = reader.read_codes(src_name) self.assertEquals(6,len(results)) class CatalogReaderTest(unittest.TestCase): def test_read_catalogs(self): creader = fxj.CatalogReader() results = creader.read_catalogs(os.path.join(test_data_dir,'blk')) self.assertEquals(3,len(results)) names = [ name for name,members in results ] self.assertTrue(u'广西' in names) self.assertTrue(u'广东' in names) self.assertTrue(u'贵州' in names) if __name__ == "__main__": import logging logging.basicConfig(filename="test.log",level=logging.DEBUG,format='%(name)s:%(funcName)s:%(lineno)d:%(asctime)s %(levelname)s %(message)s') unittest.main()
Python
# -*- coding: utf-8 -*- import logging import time #from django.db import transaction import wolfox.foxit.source.reader as reader from wolfox.foxit.base.tutils import linelog from wolfox.foxit.dune.models import PowerInfo,Exchange,StockType,Catalog logger = logging.getLogger("source.transfer") class Transfer(object): ''' 常用功能的集成类,是一个基本没有自己逻辑的包装类 ''' def __init__(self,store,conn,begin=0,end=99999999): self.store = store self.conn = conn self.begin = begin self.end = end self.q_file_ranges=[] #元素应当为(filename,begin,end) self.h_file_ranges=[] #元素应当为(filename,begin,end) self.x_filenames=[] self.r_filenames=[] self.c_filenames=[] def set_quote_params(self,extractor,filenames): ''' 分析家数据存在问题,对数据的批处理导入有影响. 如20080701的日数据中,包含了20060x0x的某个已经退市股票的数据 虽然如此,对小范围文件(特别是单个文件)的导入,仍可以采用self中设置的begin,end 已经不用 ''' self.q_extractor = extractor self.q_file_ranges = [ (filename,self.begin,self.end) for filename in filenames] def set_quote_params2(self,extractor,file_ranges): ''' 分析家数据存在问题,对数据的批处理导入有影响. 如20080701的日数据中,包含了20060x0x的某个已经退市股票的数据 因此大规模批量导入时,每个文件都需要单独限定时间段,避免早先的历史数据影响导入 ''' self.q_extractor = extractor self.q_file_ranges = file_ranges def set_hour_quote_params2(self,extractor,file_ranges): ''' 分析家数据存在问题,对数据的批处理导入有影响. 如20080701的日数据中,包含了20060x0x的某个已经退市股票的数据 因此大规模批量导入时,每个文件都需要单独限定时间段,避免早先的历史数据影响导入 ''' self.h_extractor = extractor self.h_file_ranges = file_ranges def set_xinfo_params(self,extractor,filenames): self.x_extractor = extractor self.x_filenames = filenames def set_report_params(self,extractor,filenames): self.r_extractor = extractor self.r_filenames = filenames def set_code_params(self,creader,filenames): self.c_reader = creader self.c_filenames = filenames def init_catalog(self,code_reader,code_filenames,catalog_reader,catalog_targets): init_catalog(self.store,code_reader,code_filenames,catalog_reader,catalog_targets) def sync(self): bt = time.time() new_codes = sync_codes(self.store,self.c_reader,self.c_filenames) self.store.transfer_xquotes2(self.conn,new_codes) #对之前既有但没有code的行情数据的转换 self.store.transfer_hour_xquotes2(self.conn,new_codes) #对之前既有但没有code的行情数据的转换 #迟到的新代码对除权数据没有影响,因为之前代码没有,数据进不了PowerInfo表,有代码之后,老数据仍然能进 print u'代码同步耗时:%s' % (time.time() - bt) xbegin,xend = 99999999,0 ct = time.time() linelog('begin quotes transfer') for filename,fbegin,fend in self.q_file_ranges: print u'导入文件%s' % filename begin,end = sync_quotes(self.store,self.conn,filename,self.q_extractor,fbegin,fend) xbegin = begin if begin < xbegin else xbegin xend = end if end > xend else xend print u'行情数据导入耗时:%s' % (time.time() - ct) linelog('begin xinfos transfer') dt = time.time() for filename in self.x_filenames: sync_xinfos(self.store,filename,self.x_extractor,xbegin,xend) print u'除权数据导入耗时:%s' % (time.time() - dt) et = time.time() linelog('begin reports transfer') for filename in self.r_filenames: sync_reports(self.store,filename,self.r_extractor,xbegin,xend) print u'财务数据同步耗时:%s' % (time.time() - et) linelog('begin xit') ft = time.time() #xit_end = self.store.get_latest_xquote_day(self.conn) xit(self.store,self.conn,0) #除权所有到此未除权的项 #_xit2(self.store,self.conn,['SH600654'],0) #_xit2(self.store,self.conn,['SH600654'],19950526) print u'除权耗时:%s' % (time.time() - ft) self.sync60() return xbegin,xend def sync60(self): xbegin,xend = 2200000000,0 ct = time.time() for filename,fbegin,fend in self.h_file_ranges: print u'导入文件%s' % filename begin,end = sync_hour_quotes(self.store,self.conn,filename,self.h_extractor,fbegin,fend) xbegin = begin if begin < xbegin else xbegin xend = end if end > xend else xend print u'60分钟数据导入耗时:%s' % (time.time() - ct) ft = time.time() xit_hour(self.store,self.conn,0) #除权所有到此未除权的项 print u'60分钟除权耗时:%s' % (time.time() - ft) return xbegin,xend #公开的函数 def sync_quotes(store,conn,filename,extractor,begin,end): qreader = reader.Reader(extractor,_create_date_filter(begin,end)) quotes,xbegin,xend = _read_quotes(filename,qreader) print u'数据读入完毕,共%s条记录' % len(quotes) #print xbegin,store.get_latest_squote_day(conn),store.get_latest_xquote_day(conn) if xbegin <= store.get_latest_squote_day(conn) or xbegin <= store.get_latest_xquote_day(conn): from sqlite3 import IntegrityError raise IntegrityError,u'要导入数据的日期小于已有数据的日期' logger.debug(u'开始插入数据') #store.add_squotes(conn,quotes) store.add_quotes(conn,quotes) print u'文件%s倒入完毕.' % filename #print u'文件%s倒入完毕,开始转换....' % filename #store.transfer_xquotes(conn,xbegin,xend) return xbegin,xend def sync_hour_quotes(store,conn,filename,extractor,begin,end): print begin,end qreader = reader.Reader(extractor,_create_date_filter(begin*100,end*100)) quotes,xbegin,xend = _read_quotes(filename,qreader) print 'len(quotes)=%s,xbegin=%s,xend=%s'%(len(quotes),xbegin,xend) print u'数据读入完毕' #print store.get_latest_hour_squote_day(conn),store.get_latest_hour_xquote_day(conn) #print xbegin,store.get_latest_squote_day(conn),store.get_latest_xquote_day(conn) if xbegin <= store.get_latest_hour_squote_day(conn) or xbegin <= store.get_latest_hour_xquote_day(conn): from sqlite3 import IntegrityError raise IntegrityError,u'要导入数据的日期小于已有数据的日期' logger.debug(u'开始插入数据') #store.add_squotes(conn,quotes) store.add_hour_quotes(conn,quotes) print u'文件%s倒入完毕.' % filename #print u'文件%s倒入完毕,开始转换....' % filename #store.transfer_xquotes(conn,xbegin,xend) return xbegin,xend def sync_xinfos(store,filename,extractor,begin=0,end=99999999): ''' 同步除权信息''' return _sync_records(store.get_xinfo_keys,store.add_xinfos,filename,extractor,begin,end) def sync_reports(store,filename,extractor,begin=0,end=99999999): ''' 同步年报信息''' return _sync_records(store.get_report_keys,store.add_reports,filename,extractor,begin,end) def xit(store,conn,begin=0): ''' 时间段除权 begin/end:除权交易数据的起止日 ''' xit_end = store.get_latest_xquote_day(conn) xinfos = list(PowerInfo.objects.filter(execute_day__range = (begin,xit_end)).filter(day_state = 0).order_by('execute_day')) #必须先转换成list以读完记录,否则当记录数超过100(估计是缓存数量)时,后续处理(xinfo.save)时会因为表锁死而无法save print u'待除权项数量:%s' % len(xinfos) store.xit(conn,xinfos) def xit_hour(store,conn,begin=0): ''' 时间段除权 begin/end:除权交易数据的起止日 ''' xit_end = store.get_latest_hour_xquote_day(conn) xinfos = list(PowerInfo.objects.filter(execute_day__range = (begin,xit_end)).filter(hour_state = 0).order_by('execute_day')) #必须先转换成list以读完记录,否则当记录数超过100(估计是缓存数量)时,后续处理(xinfo.save)时会因为表锁死而无法save print u'待除权项数量:%s' % len(xinfos) store.xit_hour(conn,xinfos) def sync_codes(store,creader,filenames): ''' 同步代码 store: 底层数据服务对象 creader: 文件读取对象 filenames: [...] 代码文件 ''' ex_map = dict([ (exchange.abbr_code,exchange) for exchange in Exchange.objects.all()]) st_map = dict([ (stype.name,stype) for stype in StockType.objects.all()]) codes = [] for filename in filenames : codes.extend(creader.read_codes(filename)) codes = [ (ex_map[code[0]],code[1],code[2],st_map[code[3]]) for code in codes if code[0] in ex_map and code[-1] in st_map ] #过滤掉市场和种类之外的代码 new_codes = store.update_codes(codes) #print new_codes return new_codes def init_catalog(store,code_reader,code_filenames,catalog_reader,catalog_targets): ''' 连带脚本. 先执行sync_codes,然后执行init_catalog 这个脚本只能在初始化的时候执行一次。否则因为这里同步了code,但没有对那些行情数据进行补转换,会导致隐藏的错误 code_reader: 文件读取对象 code_filenames: [...] 代码文件 catalog:reader: CatalogReader的实例 catalog_targets: 板块文件所在目录或文件列表 ''' sync_codes(store,code_reader,code_filenames) return _init_catalog(store,catalog_reader,catalog_targets) ####以下为内务函数或普通情形下不建议使用的函数(如_xit2)####### def sync_quotes2(store,conn,filename,extractor,begin,end): #这里是先删除再导入. 容易误操作,废弃? qreader = reader.Reader(extractor,_create_date_filter(begin,end)) quotes,xbegin,xend = _read_quotes(filename,qreader) #for quote in quotes: print quote store.remove_squotes(conn,begin,end) store.remove_xquotes(conn,begin,end) store.add_squotes(conn,quotes) store.transfer_xquotes(conn,xbegin,xend) return xbegin,xend def _read_quotes(filename,qreader): #便捷函数,建议用包裹函数sync_quotes替代 return _read_records(filename,qreader) def _read_xinfos(filename,reader): #便捷函数. 但建议用sync_xinfos替代 return _read_records(filename,reader) def _read_reports(filename,reader): #便捷函数. 但建议用sync_reports替代 return _read_records(filename,reader) def _create_date_filter(begin,end): if(begin == 0 and end == 99999999): return reader.NullFilter() return reader.DateFilter(begin,end) def _create_filter(begin,end,stocks): datefilter = reader.DateFilter(begin,end) return reader.CodeFilter(stocks,datefilter) def _read_records(filename,reader): ''' 读取记录 filename:文件名 reader:读取对象 ''' records = set(reader.read(filename)) #去重. 这里有个前提条件是同一天的除权记录不会被数据来源刻意的分为两条. #因为这里的去重实际上判断标准是 股票名tstock+日期tdate,其它字段不论 logger.debug(u"文件 %s 包含 %s 条记录" % (filename,len(records))) if(not records): logger.debug(u'没有更新的记录') return [],0,0 #records = [ record for record in records if record.is_valid()] #去掉错误数据 #logger.debug(u"transfer:去除错误数据后文件 %s 中有 %s 条记录" % (filename,len(records))) begin,end = min(records).tdate,max(records).tdate+1 logger.debug(u"记录起止日期:%s -- %s" % (begin,end)) return records,begin,end def _xit2(store,conn,stocks,begin=0,end=99999999): ''' 时间段内对特定股票集合除权 begin/end:除权交易数据的起止日 stocks为标准code集合 ''' xit_end = store.get_latest_xquote_day(conn) xinfos = PowerInfo.objects.filter(execute_day__range = (begin,xit_end)) \ .filter(tstock__code__in=stocks).filter(day_state = 0).order_by('execute_day') store.xit(conn,xinfos) def _sync_records(key_func,add_func,filename,extractor,begin,end): rreader = reader.Reader(extractor,_create_date_filter(begin,end)) #print filename,rreader,begin,end src_records,rbegin,rend = _read_records(filename,rreader) exist_keys= set(key_func(rbegin,rend)) #print src_records[0].tstock,src_records[0].tdate,type(src_records[0]) new_records = [ record for record in src_records if (record.tstock,record.tdate) not in exist_keys] #print new_records #print new_records,add_func add_func(new_records) return len(new_records),rbegin,rend def _init_catalog(store,creader,targets): ''' 板块初始化 creader: CatalogReader的实例 targets: 板块文件所在目录或文件列表 只能执行一次。在第一次sync_codes之后,因为需要用到合法的StockCode信息 需要适当处理股票代码不存在的情况(由add_stock_to_catalog3处理) 没有处理板块不存在的情况. 因此调用者需要确保这个情况不存在 ''' c_map = dict([ (c.name,c) for c in Catalog.objects.all()]) catalogss = [] for target in targets: catalogss.extend(creader.read_catalogs(target)) catalogss = [ entry for entry in catalogss if entry[0] in c_map ] map(lambda entry:store.add_stock_to_catalog3(*entry),catalogss) return [name for name,catalogs in catalogss]
Python
# -*- coding: utf-8 -*- #检查上证指数和深证指数的一致性,输出不一致的日期 not_in_sh =''' select tdate from dune_xdayquote dx join dune_stockcode ds on ds.id = dx.tstock_id where code = 'SZ399001' and tdate > 19960101 and tdate not in (select tdate from dune_xdayquote dx join dune_stockcode ds on ds.id = dx.tstock_id where code = 'SH000001' and tdate > 19960101) ''' not_in_sz =''' select tdate from dune_xdayquote dx join dune_stockcode ds on ds.id = dx.tstock_id where code = 'SH000001' and tdate > 19960101 and tdate not in (select tdate from dune_xdayquote dx join dune_stockcode ds on ds.id = dx.tstock_id where code = 'SZ399001' and tdate > 19960101) ''' def check(conn): ''' 返回(上海市场缺失交易日,深圳市场缺失交易日)''' cursor = conn.cursor() cursor.execute(not_in_sh) rows = cursor.fetchall() dates1 = [row[0] for row in rows] cursor.execute(not_in_sz) rows = cursor.fetchall() dates2 = [row[0] for row in rows] return dates1,dates2 if __name__ == '__main__': from django.core.management import setup_environ import wolfox.foxit.settings as settings setup_environ(settings) from django.db import connection from pprint import pprint pprint(check(connection))
Python
# -*- coding: utf-8 -*- """ 本文件用于验证fxj数据解码的正确性 """ import unittest class CommonTest(unittest.TestCase): def testModule(self): from wolfox.foxit.source.common import patterns,pattern1,pattern2 self.assertTrue(True) if __name__ == "__main__": import logging logging.basicConfig(filename="test.log",level=logging.DEBUG,format='%(name)s:%(funcName)s:%(lineno)d:%(asctime)s %(levelname)s %(message)s') unittest.main()
Python
# -*- coding: utf-8 -*- from wolfox.source.fxj import DayExtractor,XExtractor,ReportExtractor from wolfox.source.transfer import createFilter import wolfox.source.reader as reader def get_day_info(filename,extractor,begin=0,end=99999999,stocks=None): ''' 获得指定文件在指定时间段内的记录数''' ri = reader.Reader(extractor,createFilter(begin,end,stocks)) quotes = ri.read(filename) if(not quotes): print >> output,'在%d - %d 之间没有指定的数据' %(begin,end) quotes.sort() stock_records = {} dispatch = lambda item: stock_records.setdefault(item.tstock,[]).append(item) map(dispatch,quotes) #temp的每个key都对应为排过序列表 from_date,to_date,nums = quotes[0].tdate,quotes[-1].tdate,len(quotes) return (from_date,to_date,nums),stock_records if __name__ == '__main__': import optparse import cStringIO parser = optparse.OptionParser() parser.add_option('--source','-s',help="需要显示信息的源记录文件") options,arguments = parser.parse_args() if options.source: output = cStringIO.StringIO() sum_info,stock_records = get_day_info(options.source,DayExtractor()) rlist = [] for key,records in stock_records.items(): rlist.append((key,records[0].tdate,records[-1].tdate,len(records))) #print >> output, '%s 共有从%s - %s 的 %d 条记录' % (key,records[0].tdate,records[-1].tdate,len(records)) rlist.sort(key=lambda x:x[0]) for item in rlist: #输出到output print >> output,item print output.getvalue(),sum_info else: print u'请输入目标文件名'
Python
# -*- coding: utf-8 -*- import logging from wolfox.foxit.base.tutils import parseName logger = logging.getLogger("foxit.source.reader") class NullFilter(object): def filter(self,record): return True nullFilter = NullFilter() class DateFilter(object): #只能做filter链条末端的filter,不设置innerFilter __slots__ = "begin","end" def __init__(self,begin=0,end=99999999): self.begin = begin self.end = end def filter(self,record): return self.begin <= record.tdate < self.end class CodeFilter(object): __slots__ = "codes","nextFilter" def __init__(self,codes,nextFilter=nullFilter): #codes为Set类型 self.codes = codes self.nextFilter = nextFilter def filter(self,record): return (record.tstock in self.codes) and self.nextFilter.filter(record) class Reader(object): __slots__ = "extractor","filter" def __init__(self,extractor,filter=nullFilter): self.extractor = extractor self.filter = filter def read(self,filename): fh = open(filename,"rb") #如果文件无法打开,则必须直接返回异常 records = self.read2(fh,parseName(filename)) fh.close() return records def read2(self,filehandle,name): records = [] try: self.extractor.handleHeader(filehandle,name) record = self.extractor.extract(filehandle) while(record): if(self.filter.filter(record)): records.append(record) record = self.extractor.extract(filehandle) except Exception, inst: #logger.warn(u"文件读取异常:" + str(inst).decode('gbk')) logger.exception(inst) return records
Python
# -*- coding: utf-8 -*- ''' 分析家数据格式相关类的聚集 这些类的数据读取方法,在返回值中存在股票代码时,必须已经转换为标准代码 ''' import logging import re import glob import os.path from datetime import datetime from struct import unpack from wolfox.foxit.base.common import Quote,createQuoteFromSrc,createXInfoFromSrc,createReportFromSrc import wolfox.foxit.source.reader as reader from wolfox.foxit.source.common import patterns,pattern1,pattern2 logger = logging.getLogger("foxit.source.fxj.extractor") #老版本的上证指数代码 ==> 6.0版本的代码的对照表 CODEMAP60 = {"SH1A0001":"SH000001","SH1A0002":"SH000002","SH1A0003":"SH000003","SH1B0001":"SH000004", "SH1B0002":"SH000005","SH1B0004":"SH000006","SH1B0005":"SH000007","SH1B0006":"SH000008", "SH1B0007":"SH000010","SH1B0008":"SH000011","SH1B0009":"SH000012","SH1B0010":"SH000013", "SH1C0003":"SH000016"} class CodeReader(object): ''' 代码读取器 用于获得特定来源的(交易所缩写编号,标准代码,名字,证券类型)元组列表 这个类的目的是归集相关函数,免予污染模块名字空间 ''' def read_codes(self,fname): ''' 主函数 返回(交易所缩写编号,标准代码,名字,股票类型)的列表. 其标准code根据特定的对应关系获得,这里是prefix + 源code ''' lines = self.readlines(fname) assert 'SuperStk Name Table',lines[0][:-1] #[:-1]是为了去掉回车 prefix = lines[1][:-1] #name_tuples = self.parse(lines[2:],prefix) results = [ self.parse(line,prefix) for line in lines[2:]] results = filter(lambda record: record[3],results) return results def readlines(self,fname): #已经废弃 fh = open(fname) lines = fh.readlines() fh.close() return lines def parse(self,line,prefix): #分析家的数据源中,代码文件传入的line是gbk的 #code,name = line.split('\t') code,name = line[:6],line[7:-1].decode('gbk') #源文件格式为gbk code = prefix + code if code in CODEMAP60: code = CODEMAP60[code] #映射 stype = self.find_type(code) return prefix,code,name,stype def find_type(self,code): ms = filter(lambda t: t[0].match(code) and t[1],patterns) #留下的是正确的pattern if(ms): return ms[0][1] #必然只有一个元素 return None class CatalogReader(object): ''' 板块读取器 这个类的目的是归集相关函数,免予污染模块名字空间 ''' def read_catalogs(self,directory): ''' 从指定目录中读取所有板块文件,并返回(板块名,板块成员)列表 ''' extractor = CatalogExtractor() creader = reader.Reader(extractor) filenames = glob.glob(os.path.join(directory,'*.BLK')) catalogs_list = [ creader.read(filename) for filename in filenames ] names = [ os.path.splitext(os.path.basename(filename))[0].decode('gbk') for filename in filenames ] #这里的decode原因是该板块文件格式本身是gbk的 return zip(names,catalogs_list) min5_list = [ '09%02d' % m for m in range(35,60,5)] \ + [ '10%02d' % m for m in range(0,60,5)] \ + [ '11%02d' % m for m in range(0,31,5)] \ + [ '13%02d' % m for m in range(5,60,5)] \ + [ '14%02d' % m for m in range(0,60,5)] \ + ['1500'] min5_map = dict(zip(min5_list,range(len(min5_list)))) day_func = lambda tid:int(datetime.fromtimestamp(tid).strftime("%Y%m%d")) #min5_func = lambda tid:int(datetime.utcfromtimestamp(tid).strftime("%y%m%d%H%M")) #必须utc,否则时区出错 min5_func = lambda tid:int(datetime.utcfromtimestamp(tid).strftime("%Y%m%d")) * 100 + min5_map[datetime.utcfromtimestamp(tid).strftime("%H%M")] #正好未溢出 class TradeExtractor(object): #交易数据解析 """ 分析家 DAD文件格式: 文件头 + M * (股票名记录 + N * 股票交易记录) + 结尾记录 文件头(16字节): unsigned int 1: 文件标记 0x33fc198c unsigned int 2: 未知 unsigned int 3: 股票个数 unsigned int 4: 文件标记 0x0 股票名记录(32字节): unsigned int date_id: 0xffffffff表示类型为股票名字 char[8] : 股票名字,其中上海以SH开头,深圳以SZ开头,后六位为标准编码 char[20] : 全零 交易记录(32字节): unsigned int date_id: !=0xffffffff 为1970-01-01起始的秒数,utc时间,对日判断无影响,但对分钟判断有影响,必须用对函数 float open_price:开盘价 float high_price:最高价 float low_price:最低价 float close_price:收盘价 float total_volume:成交量//单位为手 float total_value:成交金额//单位为元 unsigned short:未知 unsigned short:未知 结尾记录: unsigned int date_id: 0xffffffff char[28]:全零 """ def __init__(self,tfunc=day_func): self.tfunc = tfunc def handleHeader(self,filehandle,fname): #第三个参数为去掉扩展名和路径的文件名 header = filehandle.read(16) tag,nouse,snumber,nouse = unpack('iiii',header) if(tag != 0x33fc198c): raise IOError,u'文件类型错误,不是分析家日线文件' self.curstock = '000000' def extract_old(self,filehandle): #此处在60分钟处理月数据时递归溢出 ds = filehandle.read(4) (dateid,) = unpack('i',ds) record = None while(dateid == -1): #名字 self.curstock = filehandle.read(8) #print self.curstock if(unpack('ii',self.curstock) == (0,0)): #结束块 #print "结束块" return #返回None if(self.curstock in CODEMAP60): #分析家6.0升级后改动了上证指数的编码,需要将老版本的代码改到新版本 self.curstock = CODEMAP60[self.curstock] self.is_index = True if self.curstock[:5] == 'SH000' or self.curstock[:5] == 'SZ399' else False filehandle.read(20) ds = filehandle.read(4) (dateid,) = unpack('i',ds) else:#数据 #tdate = int(datetime.fromtimestamp(dateid).strftime("%Y%m%d")) #print 'dateid:%s' % dateid tdate = self.tfunc(dateid) #print tdate rs = filehandle.read(28) (open,high,low,close,volume,amount,nouse) = unpack('fffffff',rs) if self.is_index: volume //= 1000 record = createQuoteFromSrc(self.curstock,tdate,open,close,high,low,volume,amount) print 'record: %s:%s' % (record.tstock,record.tdate) if not pattern1.match(record.tstock): #非目标stockcode,如国债 return self.extract(filehandle) #递归调用 if pattern2.match(record.tstock) and record.tvolume <= 0: logger.info(u'问题数据,%s.volume=%s,record=%s' % (record.tstock,record.tvolume,record)) return self.extract(filehandle) #递归调用 if record.tavg == 0: record.tavg = (record.thigh + record.tlow +1) // 2 return record def extract(self,filehandle): while(True): ds = filehandle.read(4) (dateid,) = unpack('i',ds) if(dateid == -1): #名字 self.curstock = filehandle.read(8) #print self.curstock if(unpack('ii',self.curstock) == (0,0)): #结束块 #print "结束块" return #返回None if(self.curstock in CODEMAP60): #分析家6.0升级后改动了上证指数的编码,需要将老版本的代码改到新版本 self.curstock = CODEMAP60[self.curstock] self.is_index = True if self.curstock[:5] == 'SH000' or self.curstock[:5] == 'SZ399' else False filehandle.read(20) else:#数据 #tdate = int(datetime.fromtimestamp(dateid).strftime("%Y%m%d")) #print 'dateid:%s' % dateid tdate = self.tfunc(dateid) #print tdate rs = filehandle.read(28) (open,high,low,close,volume,amount,nouse) = unpack('fffffff',rs) if self.is_index: volume //= 1000 record = createQuoteFromSrc(self.curstock,tdate,open,close,high,low,volume,amount) #print 'record: %s:%s' % (record.tstock,record.tdate) if record.tavg == 0: record.tavg = (record.thigh + record.tlow +1) // 2 if pattern2.match(record.tstock) and record.tvolume <= 0: logger.warning(u'问题数据,%s.volume=%s,record=%s' % (record.tstock,record.tvolume,record)) elif pattern1.match(record.tstock): #排除非目标stockcode,如国债 return record # rday = lambda r:r.tdate/100 rhour = lambda r:r.tdate%100 /12 class M5to60Extractor(object): ''' 在extractor层面处理完5=>60的转换,否则需要的改动太大 不能继承自TradeExtractor, 否则在从TradeExtractor来的对extract的递归调用会使用子类的extract,导致重数太多,语义也不对 ''' def __init__(self): self.extractor = TradeExtractor(min5_func) def handleHeader(self,filehandle,fname): #第三个参数为去掉扩展名和路径的文件名 self.extractor.handleHeader(filehandle,fname) self.curday = -1 self.curhour = -1 self.curtrade = Quote() self.finished = False def extract(self,filehandle): if self.finished: return None record = self.extractor.extract(filehandle) #print "record: %s %s" % (record.tstock,record.tdate) while record and record.tstock == self.curtrade.tstock and self.curday == rday(record) and self.curhour == rhour(record): #继续累加 self.curtrade.tclose = record.tclose self.curtrade.tamount += record.tamount self.curtrade.tvolume += record.tvolume if self.curtrade.thigh < record.thigh: self.curtrade.thigh = record.thigh if self.curtrade.tlow > record.tlow: self.curtrade.tlow = record.tlow record = self.extractor.extract(filehandle) #缺乏do..while或until循环语句的不便 #if record: print "record: %s %s" % (record.tstock,record.tdate) else: self.curtrade.calcAvg() completed_trade = self.curtrade completed_trade.tdate = completed_trade.tdate / 100 * 100 + completed_trade.tdate % 100 / 12 #转换为小时计数 self.curtrade = record if not record: self.finished = True else: self.curday = rday(record) self.curhour = rhour(record) if completed_trade.tvolume == 0: #过滤掉第一个桩 return self.extract(filehandle) #print completed_trade.tstock,completed_trade.tdate return completed_trade class XExtractor(object): #除权数据解析 """ 分析家除权文件http://download.fxj.com.cn/base/SPLIT.PWR 文件格式 文件头 + M * (股票名记录 + N * 股票交易记录) 文件头(8字节): unsigned int 1: 文件标记 0xff43c832 unsigned int 2: 未知,总是0xffcc83dd 股票名记录(20字节): unsigned int date_id: 0xffffffff表示类型为股票名字 char[8] : 股票名字,其中上海以SH开头,深圳以SZ开头,后六位为标准编码 char[8] : 未知 通常这8个字节分为2个float,是上一个股票最后一条除权记录的配股价格和红利价格字段的拷贝。 估计是除权文件生成程序的bug,或者起到一个校验作用 交易记录(20字节): unsigned int date_id: !=0xffffffff 为1970-01-01起始的秒数 float stock_sggs; // 每股送股股数,如果是10送5,则为0.5 float stock_pggs; // 每股配股股数,方式同上 float stock_pgjg; // 配股每股价格 float stock_bonus; // 每股红利价格 """ __slots__ = "curstock" def handleHeader(self,filehandle,fname): #第三个参数为去掉扩展名和路径的文件名,貌似现在没用了 header = filehandle.read(8) tag,nouse = unpack('II',header) if(tag != 0xff43c832): raise IOError,u'文件类型错误,不是分析家除权文件,tag:%x' % tag self.curstock = '000000' def extract(self,filehandle): ds = filehandle.read(4) if(len(ds) == 0): return #文件结束,返回None (dateid,) = unpack('i',ds) while(dateid == -1): #名字 self.curstock = filehandle.read(8) #print "new stock:",self.curstock filehandle.read(8) ds = filehandle.read(4) (dateid,) = unpack('i',ds) else:#数据 #tdate = int(datetime.fromtimestamp(dateid).strftime("%Y%m%d")) tdate = day_func(dateid) rs = filehandle.read(16) (sgbl,pgbl,pgj,fhbl) = unpack('ffff',rs) record = createXInfoFromSrc(self.curstock,tdate,tdate,pgbl,sgbl,fhbl,pgj) return record class ReportExtractor(object): #财务报表数据解析 """ 分析家财务文件(FIN)解析 文件格式: 文件头 + N 记录 文件头(8字节): 标志(4字节):0x223FD90C 保留(4字节) 记录(166字节) 股名(10字节): 市场名(2字节,SH/SZ) + 保留(2字节 0000) + 代码(6字节) 起始日期 (4字节)Integer 从1970.1.1开始的秒数(未确认,目前是全零) 更新日期 (4字节)Integer 从1970.1.1开始的秒数 总股本 (4字节) Float 万股 国家股 (4字节) Float 万股 发起法人股 (4字节) Float 万股 法人股 (4字节) Float 万股 B股 (4字节) Float 万股 H股 (4字节) Float 万股 流通A股 (4字节) Float 万股 职工股 (4字节) Float 万股 A2转配股 (4字节) Float 万股 总资产 (4字节) Float 千元 流动资产 (4字节) Float 千元 固定资产 (4字节) Float 千元 无形资产 (4字节) Float 千元 长期投资 (4字节) Float 千元 流动负债 (4字节) Float 千元 长期负债 (4字节) Float 千元 资本公积金 (4字节) Float 千元 每股公积金 (4字节) Float 元/股 股东权益 (4字节) Float 千元 主营收入 (4字节) Float 千元 主营利润 (4字节) Float 千元 其它利润 (4字节) Float 千元 营业利润 (4字节) Float 千元(此项未确认) 投资收益 (4字节) Float 千元 补贴收入 (4字节) Float 千元 营业外收支 (4字节) Float 千元(此项未确认,可能错误) 上年损益调整 (4字节)Float 千元 利润总额 (4字节) Float 千元 税后利润 (4字节) Float 千元(此项未确认) 净利润 (4字节) Float 千元 未分配利润 (4字节) Float 千元 每股未分配 (4字节) Float 元 每股收益 (4字节) Float 元 每股净资产 (4字节) Float 元 调整每股净资产 (4字节)Float 千元 股东权益比 (4字节) Float 百分之一 净资产收益率 (4字节) Float 百分之一 """ __slots__ = "curstock" def handleHeader(self,filehandle,fname): #第三个参数为去掉扩展名和路径的文件名 header = filehandle.read(8) tag,nouse = unpack('II',header) if(tag != 0x223fd90c): raise IOError,u'文件类型错误,不是分析家财务文件,tag:%x' % tag self.curstock = '000000' def extract(self,filehandle): sname = filehandle.read(10) if(len(sname) == 0): return #文件结束,返回None self.curstock = sname[:2] + sname[4:] tmp = filehandle.read(16) (nouse,fdate,zgb,nouse) = unpack('iiff',tmp) releaseday = day_func(fdate) #int(date.fromtimestamp(fdate).strftime("%Y%m%d")) filehandle.read(8) tmp = filehandle.read(16) (bg,hg,ag,nouse) = unpack('ffff',tmp) filehandle.read(36) tmp = filehandle.read(4) (mggjj,) = unpack('f',tmp) filehandle.read(52) tmp = filehandle.read(24) (mgwfplr,mgsy,nouse,mgjzc,nouse,nouse) = unpack('ffffff',tmp) record = createReportFromSrc(self.curstock,1,releaseday,releaseday,zgb,bg,hg,ag,mgwfplr,mgsy,mgjzc,mggjj) #logger.debug(u"读取财务记录%s,%s" % (self.curstock,releaseday)) return record class CatalogExtractor(object): #分析家板块文件(*.blk)解析 """ 文件结构 文件头 + N * 股票名记录 文件头(4字节) unsigned int: 板块文件标记 0xff5100a5 股票名记录(12字节) char(8): 股票名 char(4): 全零 """ def handleHeader(self,filehandle,fname): #第三个参数为去掉扩展名和路径的文件名 header = filehandle.read(4) (tag,) = unpack('I',header) if(tag != 0xff5100a5): raise IOError,u'文件类型错误,不是分析家板块文件,tag:0x%x' % tag def extract(self,filehandle): sname = filehandle.read(8) if(len(sname) == 0): return #文件结束,返回None filehandle.read(4) #全零 return sname
Python
# -*- coding: utf-8 -*- import unittest from wolfox.foxit.source.filestore import CSVStore TEST_FILE = 'fstest.txt' class CSVStoreTest(unittest.TestCase): def tearDown(self): try: import os os.remove(TEST_FILE) except Exception: #init测试中这个文件未创建 pass def test_init(self): fs = CSVStore() self.assertTrue(True) def test_open_close(self): fs = CSVStore() fs.open(TEST_FILE) fs.close() def test_save(self): fs = CSVStore() fs.open(TEST_FILE) fs.save(['filestore save test','next line']) fs.close() if __name__ == "__main__": unittest.main()
Python
# -*- coding: utf-8 -*- import unittest from wolfox.foxit.source.check import check class CheckTest(unittest.TestCase): #只测试通路 def test_throught(self): from django.core.management import setup_environ import wolfox.foxit.settings as settings setup_environ(settings) from django.db import connection check(connection) self.assertTrue(True) if __name__ == "__main__": import logging logging.basicConfig(filename="test.log",level=logging.DEBUG,format='%(name)s:%(funcName)s:%(lineno)d:%(asctime)s %(levelname)s %(message)s') unittest.main()
Python
# -*- coding: utf-8 -*- ''' transfer模块的测试类 测试原则:逐步编织和完善测试网, 拒绝一步到位,也拒绝同样错误再次漏过. 验证主功能走通并正确 对于边界情况和异常流程,在发生错误时定位捕获. 初步时可只针对重要情况做事先测试,也可不做。 ''' from unittest import TestCase from wolfox.foxit.lib.mock import Mock,patch,sentinel from wolfox.foxit.dune.test_common import prepare,clean from wolfox.foxit.dune.store_test import prepare_xit from wolfox.foxit.base.common import XInfo from wolfox.foxit.source.transfer import * from wolfox.foxit.source.fxj import * from wolfox.foxit.source.reader import * from wolfox.foxit.dune.store import NormalStore from wolfox.foxit.dune.models import Catalog,StockCode,XDayQuote,SDayQuote import os.path cur_dir = os.path.dirname(__file__) test_data_dir = os.path.join(cur_dir,'test_data') class TransferTest(TestCase): def setUp(self): prepare() def tearDown(self): clean() def test_init_catalog(self): #包装方法,只测试通透性 from django.db import connection transfer = Transfer(NormalStore(),connection,0,99999999) test_blk_dir = os.path.join(test_data_dir,'blk') test_code_file = os.path.join(test_data_dir,'SZ.SNT') creader = CatalogReader() store = NormalStore() new_catalogs = transfer.init_catalog(CodeReader(),[test_code_file],creader,[test_blk_dir]) self.assertTrue(True) def test_sync(self): #包装方法,只测试通透性和xbegin,xend. 测试self.transfer.set_quote_params,不设时间段 from django.db import connection transfer = Transfer(NormalStore(),connection,20070101,99999999) test_c_files = (os.path.join(test_data_dir,'SZ.SNT'),os.path.join(test_data_dir,'SH.SNT')) test_q_files = (os.path.join(test_data_dir,'quote_test.dad'),os.path.join(test_data_dir,'quote_test2.dad')) test_h_files_range = [[os.path.join(test_data_dir,'m5_test.dad'),0,22000000]] test_x_files = (os.path.join(test_data_dir,'xtest.pwr'),) test_r_files = (os.path.join(test_data_dir,'report_test.fin'),) transfer.set_code_params(CodeReader(),test_c_files) transfer.set_quote_params(TradeExtractor(),test_q_files) transfer.set_xinfo_params(XExtractor(),test_x_files) transfer.set_report_params(ReportExtractor(),test_r_files) transfer.set_hour_quote_params2(M5to60Extractor(),test_h_files_range) cursor = transfer.conn.cursor() cursor.execute('delete from dune_xdayquote') cursor.execute('delete from dune_sdayquote') xbegin,xend = transfer.sync() self.assertTrue(xbegin <= xend) def test_sync60(self): #包装方法,只测试通透性和xbegin,xend. 测试self.transfer.set_quote_params,不设时间段 from django.db import connection transfer = Transfer(NormalStore(),connection,20070101,99999999) test_h_files_range = [[os.path.join(test_data_dir,'m5_test.dad'),0,22000000]] transfer.set_hour_quote_params2(M5to60Extractor(),test_h_files_range) cursor = transfer.conn.cursor() cursor.execute('delete from dune_xhourquote') cursor.execute('delete from dune_shourquote') xbegin,xend = transfer.sync60() self.assertTrue(xbegin <= xend) def test_sync2(self): #包装方法,只测试通透性和xbegin,xend,测试self.transfer.set_quote_params2,每个行情文件都单设时间段 from django.db import connection transfer = Transfer(NormalStore(),connection,0,99999999) test_c_files = (os.path.join(test_data_dir,'SZ.SNT'),os.path.join(test_data_dir,'SH.SNT')) test_q_files = (os.path.join(test_data_dir,'quote_test.dad'),os.path.join(test_data_dir,'quote_test2.dad')) test_x_files = (os.path.join(test_data_dir,'xtest.pwr'),) test_r_files = (os.path.join(test_data_dir,'report_test.fin'),) test_q_file_ranges = (test_q_files[0],20070101,20070801),(test_q_files[1],20080701,20080801) transfer.set_code_params(CodeReader(),test_c_files) transfer.set_quote_params2(TradeExtractor(),test_q_file_ranges) transfer.set_xinfo_params(XExtractor(),test_x_files) transfer.set_report_params(ReportExtractor(),test_r_files) cursor = transfer.conn.cursor() cursor.execute('delete from dune_xdayquote') cursor.execute('delete from dune_sdayquote') xbegin,xend = transfer.sync() self.assertTrue(xbegin <= xend) class ModuleTest(TestCase): def test_create_date_filter(self): from wolfox.foxit.source.transfer import _create_date_filter filter1 = _create_date_filter(0,99999999) filter2 = _create_date_filter(20010101,20060101) self.assertEquals(NullFilter,type(filter1)) self.assertEquals(DateFilter,type(filter2)) def test_create_filter(self): from wolfox.foxit.source.transfer import _create_filter filter1 = _create_filter(0,99999999,['SH01','SH02']) filter2 = _create_filter(20010101,20080101,['SH01','SH02']) self.assertEquals(CodeFilter,type(filter1)) self.assertEquals(CodeFilter,type(filter2)) def test_read_quotes(self): from wolfox.foxit.source.transfer import _read_quotes extractor = TradeExtractor() reader = Reader(extractor,NullFilter()) quotes,begin,end = _read_quotes(os.path.join(test_data_dir,'quote_test.dad'),reader) self.assertEquals(71,len(quotes)) self.assertEquals(20070702,begin) self.assertEquals(20070802,end) def test_read_records(self): #以xinfo为例验证records from wolfox.foxit.source.transfer import _read_records extractor = XExtractor() reader = Reader(extractor,NullFilter()) records,begin,end = _read_records(os.path.join(test_data_dir,'xtest.pwr'),reader) self.assertEquals(87,len(records)) self.assertEquals(19981203,begin) self.assertEquals(20061114,end) def test_read_records(self): #以xinfo为例验证records在数据为空时的情况 from wolfox.foxit.source.transfer import _read_records,_create_date_filter extractor = XExtractor() reader = Reader(extractor,_create_date_filter(0,0)) records,begin,end = _read_records(os.path.join(test_data_dir,'xtest.pwr'),reader) self.assertEquals(0,len(records)) self.assertEquals(0,begin) self.assertEquals(0,end) def test_read_xinfos(self): #通路测试 from wolfox.foxit.source.transfer import _read_xinfos extractor = XExtractor() reader = Reader(extractor,NullFilter()) records,begin,end = _read_xinfos(os.path.join(test_data_dir,'xtest.pwr'),reader) self.assertTrue(True) def test_read_reports(self): #通路测试 from wolfox.foxit.source.transfer import _read_reports extractor = ReportExtractor() reader = Reader(extractor,NullFilter()) reports,begin,end = _read_reports(os.path.join(test_data_dir,'report_test.fin'),reader) self.assertTrue(True) @patch('wolfox.foxit.source.transfer','PowerInfo') def test_xit(self,pm): #prepare store = Mock() conn = Mock() store.get_latest_xquote_day.return_value=20090100 filter_rev1 =Mock() filter_rev2 = Mock() record1,record2 = XInfo(),XInfo() pm.objects.filter.return_value = filter_rev1 filter_rev1.filter.return_value = filter_rev2 filter_rev2.order_by.return_value = (record1,record2) #action xit(store,conn,20010101) #assertion. 不过这个太侵入性了.渗入到实现的细节,未必是好. 一旦实现变化,这里也要变化.不若针对接口I/O得好 self.assertEquals(True,pm.objects.filter.called) self.assertEquals(True,store.xit.called) self.assertEquals({'execute_day__range': (20010101, 20090100)},pm.objects.filter.call_args[1]) self.assertEquals(conn,store.xit.call_args[0][0]) self.assertEquals([record1,record2],store.xit.call_args[0][1]) def test_xit_passthrough(self): #测试实际的通过性 from django.db import connection prepare() prepare_xit(connection) xit(NormalStore(),connection,20010101) clean() def test_xit_hour_passthrough(self): #测试实际的通过性 from django.db import connection prepare() prepare_xit(connection) xit_hour(NormalStore(),connection,20010101) clean() @patch('wolfox.foxit.source.transfer','PowerInfo') def test_xit2(self,pm): from wolfox.foxit.source.transfer import _xit2 #prepare store = Mock() conn = Mock() store.get_latest_xquote_day.return_value=20090100 filter1 = Mock() filter2 = Mock() filter3 = Mock() record1,record2 = XInfo(),XInfo() pm.objects.filter.return_value = filter1 filter1.filter.return_value = filter2 filter2.filter.return_value = filter3 filter3.order_by.return_value = (record1,record2) #action _xit2(store,conn,['SH00000X','SH00000Y'],20010101,20090101) #assertion. 不过这个太侵入性了.渗入到实现的细节,未必是好. 一旦实现变化,这里也要变化.不若针对接口I/O得好 self.assertEquals(True,pm.objects.filter.called) self.assertEquals(True,store.xit.called) self.assertEquals({'execute_day__range': (20010101, 20090100)},pm.objects.filter.call_args[1]) self.assertEquals({'tstock__code__in': ['SH00000X', 'SH00000Y']},filter1.filter.call_args[1]) self.assertEquals(conn,store.xit.call_args[0][0]) self.assertEquals((record1,record2),store.xit.call_args[0][1]) def test_xit2_passthrough(self): #测试实际的通过性 from wolfox.foxit.source.transfer import _xit2 from django.db import connection prepare() prepare_xit(connection) _xit2(NormalStore(),connection,['SH00000X','SH00000Y'],20010101) clean() def test_sync_xinfos(self): #只检测实际通过性,间接测试sync_records extractor = XExtractor() store = NormalStore() length,begin,end = sync_xinfos(store,os.path.join(test_data_dir,'xtest.pwr'),extractor,0,99999999) self.assertTrue(length>0) def test_sync_reports(self): #只检测实际通过性,间接测试sync_records extractor = ReportExtractor() store = NormalStore() length,begin,end = sync_reports(store,os.path.join(test_data_dir,'report_test.fin'),extractor,0,99999999) self.assertTrue(length>0) def test_sync_codes(self): import os.path names = ['SZ.SNT','SH.SNT'] test_data_files = map(lambda n: os.path.join(test_data_dir,n),names) creader = CodeReader() store = NormalStore() try: prepare() new_codes = sync_codes(store,creader,test_data_files) new_codes2 = sync_codes(store,creader,test_data_files) wka = StockCode.objects.get(code='SZ000002') #验证确实保存了,否则会抛出异常 finally: clean() self.assertEquals(9,len(new_codes)) #SH000001已经在初始化时存在了 self.assertEquals(0,len(new_codes2)) #第二次为没更新 def test_init_catalog_local(self): #测试_init_catalog,即本地版本 from wolfox.foxit.source.transfer import _init_catalog test_blk_dir = os.path.join(test_data_dir,'blk') test_code_file = os.path.join(test_data_dir,'SZ.SNT') creader = CatalogReader() store = NormalStore() try: prepare() sync_codes(store,CodeReader(),[test_code_file]) new_catalogs = _init_catalog(store,creader,[test_blk_dir]) catalog_gd = Catalog.objects.get(name=u'广东') members = catalog_gd.stocks.values_list('code') self.assertEquals(2,len(members)) self.assertTrue(('SZ000429',) in members) self.assertTrue(('SZ000507',) in members) finally: clean() self.assertEquals(2,len(new_catalogs)) self.assertTrue(u'广东' in new_catalogs) self.assertTrue(u'广西' in new_catalogs) def test_init_catalog(self): #测试init_catalog,即对外版本 test_data_dir = os.path.join(os.path.dirname(__file__),'test_data') test_blk_dir = os.path.join(test_data_dir,'blk') test_code_file = os.path.join(test_data_dir,'SZ.SNT') creader = CatalogReader() store = NormalStore() try: prepare() new_catalogs = init_catalog(store,CodeReader(),[test_code_file],creader,[test_blk_dir]) catalog_gd = Catalog.objects.get(name=u'广东') members = catalog_gd.stocks.values_list('code') self.assertEquals(2,len(members)) self.assertTrue(('SZ000429',) in members) self.assertTrue(('SZ000507',) in members) finally: clean() self.assertEquals(2,len(new_catalogs)) self.assertTrue(u'广东' in new_catalogs) self.assertTrue(u'广西' in new_catalogs) def test_sync_quotes(self): #通透性测试 from django.db import connection store = NormalStore() test_quote_file = os.path.join(test_data_dir,'quote_test.dad') try: prepare() from sqlite3 import IntegrityError self.assertRaises(IntegrityError,sync_quotes,store,connection,test_quote_file,TradeExtractor(),0,99999999) #重复将导致异常 cursor = connection.cursor() cursor.execute('delete from dune_xdayquote') cursor.execute('delete from dune_sdayquote') xbegin,xend = sync_quotes(store,connection,test_quote_file,TradeExtractor(),0,99999999) xcount = XDayQuote.objects.filter(tdate__range=(xbegin,xend)).count() scount = SDayQuote.objects.filter(tdate__range=(xbegin,xend)).count() self.assertRaises(IntegrityError,sync_quotes,store,connection,test_quote_file,TradeExtractor(),0,99999999) #重复将导致异常 finally: clean() self.assertEquals(20070702,xbegin) self.assertEquals(20070802,xend) print 'xcount:%s,scount:%s' % (xcount,scount) self.assertEquals(23,xcount) self.assertEquals(48,scount) def test_sync_quotes2(self): #通透性测试 from django.db import connection store = NormalStore() test_quote_file = os.path.join(test_data_dir,'quote_test.dad') try: prepare() xbegin,xend = sync_quotes2(store,connection,test_quote_file,TradeExtractor(),0,99999999) xcount = XDayQuote.objects.filter(tdate__range=(xbegin,xend)).count() scount = SDayQuote.objects.filter(tdate__range=(xbegin,xend)).count() xbegin,xend = sync_quotes2(store,connection,test_quote_file,TradeExtractor(),0,99999999) #再次倒入也不会出错 finally: clean() self.assertEquals(20070702,xbegin) self.assertEquals(20070802,xend) self.assertEquals(23,xcount) self.assertEquals(71,scount)
Python
# -*- coding: utf-8 -*- ''' 格式的公共部分 ''' import re patterns = [(re.compile('SH000...|SZ399...'),u'指数'), (re.compile('SH18....|SH5000..|SH500180|SH510...|SH000300|SZ18....|SZ159...'),u'基金'), (re.compile('SH600...|SH601...|SZ000...|SZ002...|SZ300'),u'股票'), (re.compile('SH0310...|SZ5800...'),u'权证'), ] #patterns的紧凑模式 pattern1 = re.compile('SH000...|SZ399...|SH18....|SH5000..|SH500180|SH510...|SH000300|SZ18....|SZ159...|SH600...|SH601...|SZ000...|SZ300|SZ002...|SH0310...|SZ5800...') #不允许其tvolume为0的代码集合 pattern2 = re.compile('SH18....|SH5000..|SH500180|SH000300|SH600...|SH601...|SZ000...|SZ002...|SH0310...|SZ5800...')
Python
# -*- coding: utf-8 -*- from django.db import models class Normal(models.Model): name = models.CharField(max_length=16) i1 = models.IntegerField() i2 = models.IntegerField() i3 = models.IntegerField() i4 = models.IntegerField() i5 = models.IntegerField() i6 = models.IntegerField() class Normal2(models.Model): name = models.CharField(max_length=16) i1 = models.IntegerField() i2 = models.IntegerField() i3 = models.IntegerField() i4 = models.IntegerField() i5 = models.IntegerField() i6 = models.IntegerField() class Admin: list_display = ('name',)
Python
# -*- coding: utf-8 -*- #测试一维序和二维序的寻址速度 #基本持平(包括transpose的),相差大概最多只有5% #但是如果是针对特殊的行/列作运算,速度下降极快,至少有2个数量级 # 发现问题主要出在 sum(a)与a.sum()的差距上,这个有数量级的差别。估计类似的差别在别的函数上也会有体现 # 这个是我的原因,居然直接用了python的sum,而不是np.sum,倒!!!!!!! # 去除这个因素,则性能损失大概在50%左右 #因此,在计算之前将数据整理好还是有效果的 import numpy as np from time import time x=np.arange(20000) x.shape=4000,5 y=np.arange(20000) y.shape=5,4000 z=x.transpose() def r1(): for i in xrange(5): m=np.sum(x[:,i]) #居然这个操作比x.sum(0)要慢2个数量级,而实际上处理的数据是x.sum(0)多很多 #m=x.sum(0) #m=x[:,i].sum() #正解 return m def r2(): for i in xrange(5): m=np.sum(y[i]) #居然这个操作比y.sum(1)要慢2个数量级,而实际上处理的数据是y.sum(1)多很多 #m=y.sum(1) #m=y[i].sum() return m if __name__ == '__main__': times = 10000 b=time() for i in xrange(times): m=x.sum(0) e=time() print e-b print m b=time() for i in xrange(times): m=y.sum(1) e=time() print e-b print m b=time() for i in xrange(times): m=np.sum(x,0) #这个极其耗费时间 e=time() print e-b print m b=time() for i in xrange(times): m=z.sum(1) e=time() print e-b print m b=time() for i in xrange(times): m=r1() e=time() print e-b print m b=time() for i in xrange(times): m=r2() e=time() print e-b print m
Python
# -*- coding: utf-8 -*- #比较两种方式在读取数据上的效率 #方式1:普通成批读取,然后用sync同步成等长序列 #方式2:逐个读取,获得的直接就是等长序列. 发现onebyone比成批速度快1.5倍 #经过分析,发现性能瓶颈主要在于organize_tuples2quotes这个函数,因为数据没有按照stock,date排序,所以分派非常耗时 #优化之后,效率相差不多,但还是onebyone快%15左右 from time import time from django.core.management import setup_environ import wolfox.foxit.settings as target setup_environ(target) from django.db import connection from wolfox.foxit.dune.store import NormalStore as s def onebyone(s,ref,stocks,begin,end): rev = [] #i=0 for stock in stocks: #print i,'execute:',stock #i+=1 rev.append(s.get_refbased_xquotes(connection,ref,stock,begin,end)) return rev from wolfox.core.task import Task my_sync = Task.sync step=30 def batch(s,ref,stocks,begin,end): b=time() rev = [] base = s.get_xquotes2(connection,[ref],begin,end)[ref] #date_base = [ t.tdate for t in base] date_base = [ t[1] for t in base] #print date_base qs = {} for x in xrange(step,len(stocks),step): #一次性导致长时间僵死,所以分批处理 print 'batch:',x qs.update(s.get_xquotes2(connection,stocks[x-step:x],begin,end)) if x < len(stocks): print 'batch end:',x qs.update(s.get_xquotes2(connection,stocks[x:],begin,end)) #print type(qs) m=time() print 'batch read:',m-b #i=0 for v in qs.values(): #print 'execute:',i #i+=1 #vdate = [ t.tdate for t in v] vdate = [ t[1] for t in v] rev.append(my_sync(date_base,vdate,v)) #print base return rev if __name__ == '__main__': ns = s() id2code = ns.get_id2code() code2id = ns.get_code2id() print len(code2id) #print code2id['SZ000900'] b1=time() #r1=onebyone(ns,1,id2code.keys(),20000000,20030001) e1=time() print e1-b1 b2=time() r2=batch(ns,u'SH000001',code2id.keys(),20000000,20030101) e2=time() print e2-b2 #print len(r1) print len(r2) from pprint import pprint #pprint(r2[100]) #pprint(r1[-1]) print e1-b1 print e2-b2
Python
# -*- coding: utf-8 -*- '''比较三种方式的插入效率 方式1: 纯粹django 方式2a: django中直接使用sql,使用占位符号 方法2b: 直接使用填完后的字符串 方式3: 纯粹sql 都插入100000条记录 测试结果: 1. 82.5789999962 81.625 2. 27.0780000687 27.2649998665 3. 29.7339999676 29.6880002022 4. 6.59400010109 6.31200003624 500000: 1. 408.516 2. 146.14 3. 154.703 4. 32.407 在另一台机器上 1. 39.3280000687 39.6719999313 2. 12.375 12.8129999638 3. 11.3439998627 11.4690001011 4. 4.125 4.1400001049 基本结论:纯django和纯sql的性能相差一个数量级,混合型的在中间 决定对于大批量导入数据,采用纯sql的方式 日常导入数据,采用django 风格的混合型方式 方法3的数据库 CREATE TABLE "benchmark_normal3" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(16) NOT NULL, "i1" integer NOT NULL, "i2" integer NOT NULL, "i3" integer NOT NULL, "i4" integer NOT NULL, "i5" integer NOT NULL, "i6" integer NOT NULL ) ''' from django.core.management import setup_environ import wolfox.foxit.other_settings.settings_benchmark as target setup_environ(target) from django.db import transaction from wolfox.foxit.benchmark.models import Normal,Normal2 TIMES =100000 STEP = 1000 @transaction.commit_manually def pure_django(): for i in xrange(TIMES): cur = Normal(name='test',i1=i,i2=i,i3=i,i4=i,i5=i,i6=i) cur.save() if(i%STEP == 0): print 'save %d' % i transaction.commit() @transaction.commit_manually def django_sql(connection): cursor = connection.cursor() for i in xrange(TIMES): cursor.execute('insert into benchmark_normal2(name,i1,i2,i3,i4,i5,i6) values(%s,%s,%s,%s,%s,%s,%s)',(u'test',i,i,i,i,i,i)) if(i%STEP == 0): print 'save %d' % i transaction.commit() @transaction.commit_manually def django_sql2(connection): cursor = connection.cursor() for i in xrange(TIMES): cursor.execute("insert into benchmark_normal2(name,i1,i2,i3,i4,i5,i6) values('%s',%s,%s,%s,%s,%s,%s)" % (u'test',i,i,i,i,i,i)) if(i%STEP == 0): print 'save %d' % i transaction.commit() def pure_sql(connection): cursor = connection.cursor() for i in xrange(TIMES): cursor.execute('insert into benchmark_normal3(name,i1,i2,i3,i4,i5,i6) values(?,?,?,?,?,?,?)',(u'test',i,i,i,i,i,i)) if(i%STEP == 0): print 'save %d' % i connection.commit() if __name__ == '__main__': from time import time f = time() pure_django() t = time() print t-f from django.db import connection as conn_django f = time() django_sql(conn_django) t = time() print t-f f = time() django_sql2(conn_django) t = time() print t-f import sqlite3 import os.path par_path = os.path.join(os.path.dirname(__file__),os.pardir) #print par_path conn_sql = sqlite3.connect(os.path.join(par_path,'benchmark\\benchmark.db')) f = time() pure_sql(conn_sql) t = time() print t-f
Python
# -*- coding: utf-8 -*- '''比较两种方式的select效率 首先需要执行insert.py,插入大约200000条记录 然后比较django objects.filter()和sql同时选出2000条记录的效率 mixed: 使用django的connection来完成纯粹的sql工作,函数与sselect基本相同, 但传入的connection不同,同时参数的传递风格(paramstyle)不同,django用%s, sqlite用?方式 mixed2: 使用sql connection,但返回的数据转化为django的对象 2000条: django: 0.141000032425 0.125 sql: 0.0149998664856 0.0309998989105 10000条: django: 0.483999967575 0.483999967575 0.5 sql: 0.18799996376 0.171999931335 0.172 100000条: django: 4.76599979401 4.75 sql: 2.93700003624 2.93700003624 mixed: 3.03099989891 这个计算和内存耗用有关,如果屏蔽掉django方式,则: sql: 1.70300006866 mixed: 1.547 对于检索数量较多时,性能差异在1:2左右,少量时估计差异在3-8倍 对于少量数据(2000条左右), 多次访问(2000次左右)的比较 2000条,1000次: django: 91.125 sql: 23.391 23.5780000687 mixed: 25.625 2000条,2000次: django: 182.95299983 sql: 47.64 46.7349998951 mixed: 48.8900001049 典型情况 750条,2000次: django: 69.9689998627 sql: 17.187 16.969 16.7030000687 16.796 mixed: 17.1400001049 17.672 mixed2: 98.734 99.4219999313 典型情况下,mixed2的效能最差,这个可能和创建新对象时django的内务操作有关. mixed的性能可以接受. 而且受到django transaction的保护 ''' from django.core.management import setup_environ import wolfox.foxit.other_settings.settings_benchmark as target setup_environ(target) from django.db import transaction from wolfox.foxit.benchmark.models import Normal TIMES = 200000 STEP = 10000 id_from = 11000 id_to = 111000 def prepare(connection): cursor = connection.cursor() for i in xrange(TIMES): cursor.execute('insert into benchmark_normal(name,i1,i2,i3,i4,i5,i6) values(?,?,?,?,?,?,?)',(u'test',i,i,i,i,i,i)) if(i%STEP == 0): print 'save %d' % i connection.commit() def dselect(): q1 = Normal.objects.filter(id__gte = id_from).filter(id__lte = id_to) lq = list(q1) return lq class dummy(object): def __init__(self,id,name,i1,i2,i3,i4,i5,i6): self.id, self.name,self.i1,self.i2,self.i3,self.i4,self.i5,self.i6 = id,name,i1,i2,i3,i4,i5,i6 def sselect(connection): cursor = connection.cursor() cursor.execute('select id,name,i1,i2,i3,i4,i5,i6 from benchmark_normal where id>=? and id<=?',(id_from,id_to)) rows = cursor.fetchall() records = [dummy(id,name,i1,i2,i3,i4,i5,i6) for id,name,i1,i2,i3,i4,i5,i6 in rows] return records def mixed(connection): cursor = connection.cursor() cursor.execute('select id,name,i1,i2,i3,i4,i5,i6 from benchmark_normal where id>=%s and id<=%s',(id_from,id_to)) rows = cursor.fetchall() records = [dummy(id,name,i1,i2,i3,i4,i5,i6) for id,name,i1,i2,i3,i4,i5,i6 in rows] return records def mixed2(connection): cursor = connection.cursor() cursor.execute('select id,name,i1,i2,i3,i4,i5,i6 from benchmark_normal where id>=? and id<=?',(id_from,id_to)) rows = cursor.fetchall() records = [Normal(id=id,name=name,i1=i1,i2=i2,i3=i3,i4=i4,i5=i5,i6=i6) for id,name,i1,i2,i3,i4,i5,i6 in rows] return records if __name__ == '__main__': from time import time import sqlite3 import os.path par_path = os.path.join(os.path.dirname(__file__),os.pardir) #print par_path #准备 conn_sql = sqlite3.connect(os.path.join(par_path,'benchmark\\benchmark.db')) prepare(conn_sql) conn_sql.commit() conn_sql.close() ttimes = 1 #django方式 f = time() for x in xrange(ttimes): dselect() if(x%50 == 0): print 'now : %d' % x t = time() print t-f #mixed方式 django_conn + sql from django.db import connection as conn_django #mixed方式 f = time() for x in xrange(ttimes): mixed(conn_django) if(x%50 == 0): print 'mixed now : %d' % x t = time() print t-f conn_sql = sqlite3.connect(os.path.join(par_path,'benchmark\\benchmark.db')) #mixed2方式 f = time() for x in xrange(ttimes): mixed2(conn_sql) if(x%50 == 0): print 'mixed2 now : %d' % x t = time() print t-f #sql方式 f = time() for x in xrange(ttimes): sselect(conn_sql) t = time() print t-f conn_sql.close()
Python
# Create your views here.
Python
# -*- coding:utf-8 -*- class vdict(dict): ''' 键值属性化的dict ''' def __getattribute__(self,att_name): if att_name in self: return self[att_name] return dict.__getattribute__(self,att_name)
Python
# mock.py # Test tools for mocking and patching. # Copyright (C) 2007 Michael Foord # E-mail: fuzzyman AT voidspace DOT org DOT uk # mock 0.3.1 # http://www.voidspace.org.uk/python/mock.html # Released subject to the BSD License # Please see http://www.voidspace.org.uk/python/license.shtml # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml # Comments, suggestions and bug reports welcome. __all__ = ( 'Mock', 'patch', 'sentinel', '__version__' ) __version__ = '0.3.1' class Mock(object): def __init__(self, methods=None, spec=None, name=None, parent=None): self._parent = parent self._name = name if spec is not None and methods is None: methods = [member for member in dir(spec) if not (member.startswith('__') and member.endswith('__'))] self._methods = methods self.reset() def reset(self): self.called = False self.return_value = None self.call_args = None self.call_count = 0 self.call_args_list = [] self.method_calls = [] self._children = {} def __call__(self, *args, **keywargs): self.called = True self.call_count += 1 self.call_args = (args, keywargs) self.call_args_list.append((args, keywargs)) parent = self._parent name = self._name while parent is not None: parent.method_calls.append((name, args, keywargs)) if parent._parent is None: break name = parent._name + '.' + name parent = parent._parent return self.return_value def __getattr__(self, name): if self._methods is not None and name not in self._methods: raise AttributeError("object has no attribute '%s'" % name) if name not in self._children: self._children[name] = Mock(parent=self, name=name) return self._children[name] def _importer(name): mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod def patch(target, attribute, new=None): if isinstance(target, basestring): target = _importer(target) def patcher(func): original = getattr(target, attribute) if hasattr(func, 'restore_list'): func.restore_list.append((target, attribute, original)) func.patch_list.append((target, attribute, new)) return func func.restore_list = [(target, attribute, original)] func.patch_list = [(target, attribute, new)] def patched(*args, **keywargs): for target, attribute, new in func.patch_list: if new is None: new = Mock() args += (new,) setattr(target, attribute, new) try: return func(*args, **keywargs) finally: for target, attribute, original in func.restore_list: setattr(target, attribute, original) patched.__name__ = func.__name__ return patched return patcher class SentinelObject(object): def __init__(self, name): self.name = name def __repr__(self): return '<SentinelObject "%s">' % self.name class Sentinel(object): def __init__(self): self._sentinels = {} def __getattr__(self, name): return self._sentinels.setdefault(name, SentinelObject(name)) sentinel = Sentinel()
Python
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": execute_manager(settings)
Python
# The default ``config.py`` def set_prefs(prefs): """This function is called before opening the project""" # Specify which files and folders to ignore in the project. # Changes to ignored resources are not added to the history and # VCSs. Also they are not returned in `Project.get_files()`. # Note that ``?`` and ``*`` match all characters but slashes. # '*.pyc': matches 'test.pyc' and 'pkg/test.pyc' # 'mod*.pyc': matches 'test/mod1.pyc' but not 'mod/1.pyc' # '.svn': matches 'pkg/.svn' and all of its children # 'build/*.o': matches 'build/lib.o' but not 'build/sub/lib.o' # 'build//*.o': matches 'build/lib.o' and 'build/sub/lib.o' prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg', '.svn', '_svn', '.git'] # Specifies which files should be considered python files. It is # useful when you have scripts inside your project. Only files # ending with ``.py`` are considered to be python files by # default. #prefs['python_files'] = ['*.py'] # Custom source folders: By default rope searches the project # for finding source folders (folders that should be searched # for finding modules). You can add paths to that list. Note # that rope guesses project source folders correctly most of the # time; use this if you have any problems. # The folders should be relative to project root and use '/' for # separating folders regardless of the platform rope is running on. # 'src/my_source_folder' for instance. #prefs.add('source_folders', 'src') # You can extend python path for looking up modules #prefs.add('python_path', '~/python/') # Should rope save object information or not. prefs['save_objectdb'] = True prefs['compress_objectdb'] = False # If `True`, rope analyzes each module when it is being saved. prefs['automatic_soa'] = True # The depth of calls to follow in static object analysis prefs['soa_followed_calls'] = 0 # If `False` when running modules or unit tests "dynamic object # analysis" is turned off. This makes them much faster. prefs['perform_doa'] = True # Rope can check the validity of its object DB when running. prefs['validate_objectdb'] = True # How many undos to hold? prefs['max_history_items'] = 32 # Shows whether to save history across sessions. prefs['save_history'] = True prefs['compress_history'] = False # Set the number spaces used for indenting. According to # :PEP:`8`, it is best to use 4 spaces. Since most of rope's # unit-tests use 4 spaces it is more reliable, too. prefs['indent_size'] = 4 # Builtin and c-extension modules that are allowed to be imported # and inspected by rope. prefs['extension_modules'] = [] # Add all standard c-extensions to extension_modules list. prefs['import_dynload_stdmods'] = True # If `True` modules with syntax errors are considered to be empty. # The default value is `False`; When `False` syntax errors raise # `rope.base.exceptions.ModuleSyntaxError` exception. prefs['ignore_syntax_errors'] = False # If `True`, rope ignores unresolvable imports. Otherwise, they # appear in the importing namespace. prefs['ignore_bad_imports'] = False def project_opened(project): """This function is called after opening the project""" # Do whatever you like here!
Python
import deck import 14utils import 14 numPlayers = 0 numDecks = '' players = [] cardDeck = deck.Deck() def main(): try: numPlayers = int(input("Number of Players (2-4): ")) if not 14utils.restrictInput(numPlayers, 2, 4): raise ValueError elif numPlayers == 4: numDecks = input("Number of Decks to use (default 1, max 2): ") if numDecks == '': numDecks = 1 else: numDecks = int(numDecks) if not 14utils.restrictInput(numDecks, 1, 2): raise ValueError elif numDecks == 2: cardDeck.generateDeck() except ValueError: print("Invalid Input") else: for i in range(numPlayers): player = 14.Player() cardDeck.dealTo(player.faceDownCards,3) cardDeck.dealTo(player.faceUpCards,3) cardDeck.dealTo(player.hand,5) players.append(player) # Main Program main()
Python
import random class Deck: def __init__(self): self.cards = [] self.generateDeck() def generateDeck(self, decks=1): for iii in range(decks): for i in range(4): for ii in range(9): self.cards.append( (self.cardSuit(i), str(2+ii)) ) self.cards.append( (self.cardSuit(i), 'J') ) self.cards.append( (self.cardSuit(i), 'Q') ) self.cards.append( (self.cardSuit(i), 'K') ) self.cards.append( (self.cardSuit(i), 'A') ) def cardSuit(self, suit): if suit == 0: return 'S' elif suit == 1: return 'H' elif suit == 2: return 'C' elif suit == 3: return 'D' else: raise ValueError def shuffle(self): random.shuffle(self.cards) def dealTo(self, _list, _amount): for i in range(_amount): _list.append(self.cards.pop()) def length(self): return len(self.cards) def discard(self): self.cards = []
Python
def restrictInput(_input, _low, _high): if(_input<_low or _input >_high): # print("Invalid Input") return False return True
Python
import kohutils class Player(): def __init__(self): self.faceDownCards = [] self.faceUpCards = [] self.hand = [] def playCard(self, pileCards, indexHand, indexCard): # Plays a card. # indexHand: 0 = hand, 1 = cards on field # indexCard = which card if indexHand == 0: if not self.hand: return False else: if len(self.hand) >= indexCard: card = self.hand[indexCard] if card < pileCards[len(pileCards) - 1]: return False self.hand.pop(indexCard) pileCards.append(card) return pileCards else: return False elif indexHand == 1: if self.hand: return False else: if self.faceUpCards[indexCard] == None: if self.faceDownCards == None: return False else: card = self.faceDownCards[indexCard] if card < pileCards[len(pileCards) - 1]: return False self.faceDownCards[indexCard] = None pileCards.append(card) return pileCards else: card = self.faceUpCards[indexCard] if card < pileCards[len(pileCards) - 1]: return False self.faceUpCards[indexCard] = None pileCards.append(card) return pileCards def switchFaceUpCard(self, indexCard, card): if not kohutils.restrictInput(indexCard, 0, 2): return False tmpCard = self.faceUpCards[indexCard] self.faceUpCards = card return tmpCard
Python
#!/usr/bin/env python import string """ Define functions that serve to decode strings in a sample of backdoor.android.obad.a (F7BE25E4F19A3A82D2E206DE8AC979C8) """ main_service_tab = [ 27, -9, 11, -41, -10, -2, 2, -7, 23, -19, -49, 73, 1, -9, 5, -60, 32, 37, -10, 0, 13, -5, 26, -21, 6, -28, 10, -18, 2, 15, -8, 16, -1, -4, -3, -52, 55, 14, 1, 8, -13, 11, 8, -68, 23, 46, 1, 8, -13, 21, -2, 15, -8, 16, -1, -4, -3, -52, 55, 14, 1, 8, -13, 11, 8, -68, 39, 23, -5, 19, -11, 1, -18, 36, -11, 3, 1, 15, -11, 11, -9, 4, 16, 0, 17, -31, 35, 0, -7, 7, -5, -38, 42, 30, -18, -46, 63, -48, 3, 6, -31, 35, 0, -7, 7, -5, 15, -8, 16, -1, -4, -3, -52, 67, 6, -67, 22, 53, -10, 5, -6, 15, -8, 16, -1, -4, -3, -52, 55, 14, 1, 8, -13, 11, 8, -68, 29, 39, 8, -13, 11, 8, -21, 0, 41, -23, 42, -56, 2, -50, 56, -27, 1, -21, 59, -48, 18, -3, -18, 30, -1, 10, 6, 30, -12, 24, -46, 50, -39, 10, 26, -54, 46, -10, -16, 5, 27, -28, 34, -48, 50, -28, 41, 5, -10, 14, 3, 4, -37, 11, -7, -6, 10, 16, -4, 24, -13, 18, -3, 19, -18, -27, -14, 60, -8, 5, -1, 20, -16, 8, -52, -7, 35, 31, -22, -31, 33, 32, -8, 9, -28, 13, 27, -7, -1, 24, -42, -21, 23, 13, 27, 5, -23, 21, -38, 41, -9, -8, 31, -9, -1, 21, -19, -55, 39, -27, 29, -26, 32, 9, 0, 39, -43, -24, 16, 49, -30, -27, 36, -32, 49, -46, 4, 69, -19, -29, 20, -33, 29, 12, 18, -49, 50, -10, 3, 20, -31, 47, 2, -2, -45, 15, 7, 13, -27, 39, -38, 42, -4, -46, 21, 44, -23, -34, 20, 2, 8, 10, -29, 57, -28, -7, 49, 2, -37, -23, 58, 3, -57, 52, 8, -35, 39, -51, 0, 4, -1, 51, -24, 11, -24, 4, 12, -18, 6, 30, 11, 2, 32, -64, 21, 0, 37, -45, 1, 56, -7, 11, -8, -47, 57, -5, -22, -3, -14, 5, 62, -60, 52, -5, -41, 33, -31, 1, 25, -23, 58, -6, -41, 33, 31, -46, 5, 52, -70, 28, -4, 33, -43, 26, 21, -22, 28, -19, 26, -14, 19, 10, -38, 3, -21, 42, -19, 50, -11, -22, 28, -32, 47, -14, -18, 36, -64, 68, -69, 31, -16, 53, 14, -37, 41, -15, -15, -11, -20, 33, 33, -27, 39, -59, 67, -4, -65, 8, 18, -4, 52, -61, 48, 21, -67, 33, -23, 20, -16, 36, -36, 17, -10, 1, 47, -40, -5, -3, 44, 22, -54, 54, 14, -43, 39, -30, -21, 71, -68, 51, 10, -23, -24, 68, -51, 19, 32, -61, 29, -24, -2, -4, 77, -28, -37, 42, -12, -1, 34, 15, -72, 25, -13, 3, 22, 20, 12, 18, 3, -59, 51, -30, 5, 12, -31, 1, 25, -20, 55, -6, -7, 21, -57, 51, -29, 1, 52, -36, 7, 38, -14, -46, -6, 43, -31, 47, 0, 21, -12, 10, -38, 3, -21, 42, -15, 30, 5, -22, 10, -13, 35, -3, -18, 32, -60, 6, 37, -13, -18, 55, 9, -56, 35, 36, -12, -28, -1, 49, -37, 34, -39, 51, -31, -14, 2, -1, 13, 33, -10, -15, -8, -21, 50, -8, -16, -13, 46, -25, 43, -46, 58, -8, -8, -23, -26, -3, 61, -17, 34, -24, 15, 15, -63, -5, 6, 42, 30, -56, 32, -33, 53, -28, 5, 11, 33, -42, 11, 35, -38, -21, 53, -13, -28, 34, -8, 44, -15, 15, -14, -34, -8, 58, -41, 42, -6, 23, -1, -32, 40, -20, -23, -30, 63, 14, -66, 68, -6, -6, -12, 3, 21, -24, -4, 14, -34, 30, 10, 17, -42, 63, -13, -46, 52, -25, 9, -10, -15, 26, -8, 40, 0, -59, 9, 30, -21, 36, -3, 8, -13, -16, 25, 31, -59, 6, 37, -13, -15, 25, 42, 1, -66, 5, 38, 0, 31, -40, 0, -13, 20, 6, 46, -16, -53, 8, 48, -34, 54, -5, -11, -27, 52, -64, 48, 16, -7, -1, -55, 25, -15, 42, 14, 1, -50, -3, 65, -21, 36, -42, 31, 15, -38, -21, 0, 4, -1, 26, 31, -18, -32, 54, -31, -9, -3, 30, -30, 43, 30, -62, 21, 0, 37, 15, 0, -10, 3, 15, -10, -37, -13, 40, -19, 42, -2, 12, -2, -24, -28, 31, -5, 12, -31, 1, 25, -26, 61, -6, 18, -27, 24, -48, 13, 49, -65, 44, -12, 26, -50, 70, -17, -25, 35, -12, 10, -24, -17, 7, 17, 15, 21, -59, 13, 25, -27, 27, 17, 23, -32, 32, -22, -10, 9, 29, 19, 1, -40, -25, 64, -56, 28, -8, -16, 55, -18, 38, -15, 20, -21, -26, 38, -62, 32, -4, 51, 5, -44, 11, 5, -27, 44, 9, -30, -28, 39, 27, 0, -52, 52, 13, 3, 5, -38, -6, 40, -52, 51, -13, -9, -15, 48, 22, -38, 32, -13, 26, -38, 24, -35, 23, -29, 53, -15, -4, -33, 1, 53, 25, -50, 45, -32, 33, -30, -28, 34, 28, -30, 47, -37, -11, 0, 45, -27, 32, -33, 31, -22, -5, 20, 27, -34, -9, 53, -7, -6, -12, -29, 58, -12, -30, 0, -16, 45, -1, -15, 43, -10, -46, 29, 35, -10, -26, 30, 24, -39, 31, 0, -53, 50, 24, -51, -24, 36, 47, -55, 45, -5, -32, 9, -29, 47, 33, 3, -17, -12, 34, -44, 32, 0, 17, -34, 19, 4, 10, -8, 8, 0, -21, 21, 14, -6, 5, 2, -28, 40, -9, 8, 14, 15, -8, 16, -1, -4, -3, -52, 55, 14, 1, 8, -13, 11, 8, -68, 68, -1, -61, 36, 19, 4, 10, -8, 8, 0, -22, 22, 15, -11, 8, 0, 15, -12, 17, -47, 46, 0, 5, 1, 1, -7, 11, 8, -45, 43, -11, 3, 12, -5, 1, -15, 20, 17, 2, -9, 7, -5, 15, -8, 16, -1, -4, -3, -52, 55, 14, 1, 8, -13, 11, 8, -68, 23, 46, 0, 5, 1, 1, -7, 11, 8, -36, 21, 14, -6, -4, 11, 33, -10, -45, 0, 6, 16, 4, 8, 35, -16, 0, 18, 5, -27, 13, -5, -18, -5, 20, 12, 9, -64, 49, 14, -38, -6, 7, 1, -41, 39, 8, 14, 0, 2, -2, 13, 19, -23, 25, -24, -11, -2, 2, 25, -34, 30, 5, -9, -55, 62, 11, -2, 1, -62, 30, 11, -2, 1, -11, 51, 2, -15, 26, -38, 29, -14, 4, -9, 3, 9, 3, 6, -40, 11, -2, 1, -11, 51, 2, -15, 26, -12, -29, 56, -16, -6, -18, 2, -45, 1, 62, -18, 32, -56, 2, -12, -7, -6, 25, -16, 0, -13, 45, -10, 6, 35, -21, 9, -48, 54, -16, -7, -18, 2, 0, 17, -38, 23, 15, -5, 16, -18, 8, 0, 7, 1, -31, 35, 0, -7, 7, -5, 0, 17, -46, 35, 3, -3, 22, -7, 10, 12, -7, -44, 47, 6, -40, 2, 1, 7, 13, 15, -8, 16, -1, -4, -3, -52, 55, 14, 1, 8, -13, 11, 8, -68, 39, 23, -5, 19, -11, 1, -18, 36, -11, 3, 1, 15, -11, 11, -9, 4, 16, -77, 35, 33, 7, 13, -3, 5, 0, 17, -34, 19, 4, 10, -8, 8, 0, -22, 22, 15, -11, 8, 0, 15, 5, -9, -55, 62, 11, -2, 1, -62, 30, 11, -2, 1, 3, 21, 10, -3, 0, 19 ] def main_service_cOIcOOo(p0, p1, p2): """ p6, p7 and p8 are integers """ v4 = main_service_tab v3 = 0 v2 = 0 p2c = p2 + 0x5f v0 = "" v5 = 0 p0c = p0 + 0x2fc p1c = p1 # Tableau qui devrait avoir une taille p0 count = 0 v1 = [] while count < p0c : v1.insert(0, 0) count += 1 cond = -1 while True: if (cond == -1) : if not (v4 is None): cond = 0 else : v2 = p0c v3 = p1c cond =2 elif (cond == 0): v2 = chr(p2c) v1[v5] = v2 v5 += 1 if (v5 < p0c): cond = 1 else: v2 = 0 for c in v1 : v0 = v0 + c return v0 elif (cond == 1): v2 = p2c v3 = v4[p1c] cond = 2 elif (cond == 2): p1c += 0x1 p2c = v2 + v3 -2 cond = 0 program = "" for line in open("MainService.java"): program += line program = string.replace(program, "\n", "") program = string.replace(program, "\t", "") program = string.replace(program, ", ", ",") program = string.replace(program, " ,", ",") prg2 = string.split(program) res = [] new_prg = "" for s in prg2: index = string.find(s, "com.android.system.admin.MainService.cOIcOOo") new_s = "" if index >= 0: left_b = string.find(s, "(", index) right_b = string.find(s, ")", left_b + 1) if (left_b == -1 or right_b == -1): new_s = s else: param = "" i = left_b + 1 while i < right_b: param += s[i] i += 1 param = string.split(param,",") class_name = "\"" + main_service_cOIcOOo(int(param[0]), int(param[1]), int(param[2])) + "\"" if index > 0: new_s += s[:index] new_s += class_name new_s += s[right_b:] else: new_s = s new_prg += new_s + " " new_prg = string.replace(new_prg, "{", "{\n") new_prg = string.replace(new_prg, "}", "}\n") new_prg = string.replace(new_prg, ";", ";\n") print main_service_cOIcOOo(-760,1167,6)
Python
#!/usr/bin/env python """ Personal notes Goal : cluster Android apk that are similar according to the similarity features introduced in Androguard """
Python
# logging mixin for use by DeVIDE interfaces import logging import sys class LoggingMixin: def __init__(self): # this sets things up for logging to stderr logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', stream=sys.stdout) file_handler = logging.FileHandler('devide.log', 'w') file_handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') file_handler.setFormatter(formatter) # add file handler to root logger logging.getLogger('').addHandler(file_handler) def log_error_list(self, msgs): """Log a list of strings as error. This method must be supplied by all interfaces. """ for msg in msgs: logging.error(msg) def log_error(self, message): """Log a single string as error. This method must be supplied by all interfaces. """ logging.error(message) def log_info(self, message, timeStamp=True): """Log information. This will simply go into the log window. """ # we'll always follow the format set by the logger setup in the ctor logging.info(message) def log_message(self, message, timeStamp=True): """Use this to log a message that has to be shown to the user in for example a message box. """ logging.info('MESSAGE: %s' % (message,)) def log_warning(self, message, timeStamp=True): logging.warning(message) def set_progress(self, progress, message, noTime=False): # we also output an informative message to standard out # in cases where DeVIDE is very busy, this is quite # handy. logging.info( "PROGRESS: %s: %.2f" % (message, progress) )
Python
from logging_mixin import LoggingMixin from SimpleXMLRPCServer import SimpleXMLRPCServer import time class ServerProxy: def test_function(self): return "Hello World!" class XMLRPCInterface(LoggingMixin): def __init__(self, devide_app): self._devide_app = devide_app # initialise logging mixin LoggingMixin.__init__(self) print "Initialising XMLRPC..." # without real IP number, this is only available via localhost self.server = SimpleXMLRPCServer(('localhost', 8000)) self.server.register_instance(ServerProxy()) #server.register_function() def handler_post_app_init(self): """DeVIDE-required method for interfaces.""" pass def quit(self): self.server.server_close() def start_main_loop(self): self.log_message('DeVIDE available at %s' % ('localhost:8000',)) self.log_message('Starting XMLRPC request loop.') try: self.server.serve_forever() except KeyboardInterrupt: self.log_message('Got keyboard interrupt.') self.log_message('Shutting down.') self.quit()
Python
# simple api mixin to be used by RPC and command line interfaces # of DeVIDE that require simple methods for speaking to a running # instance class SimpleAPIMixin: def __init__(self, devide_app): self.devide_app = devide_app def close(self): del self.devide_app def load_and_realise_network(self, filename): """Load and instantiate a network from a given dvn filename. e.g. module_dict, conn = load_and_realise_network('test.dvn') @param filename: name of .dvn network file. @returns: dictionary mapping from serialised instance name to meta_module. dict.values() returns the the list of MetaModule instances in the instantiated network. Also list of connections. """ ln = self.devide_app.network_manager.load_network pms_dict, connection_list, glyph_pos_dict = ln(filename) rn = self.devide_app.network_manager.realise_network new_modules_dict, new_connections = rn(pms_dict, connection_list) mm = self.devide_app.get_module_manager() new_modules_dict2 = {} for k in new_modules_dict: instance = new_modules_dict[k] meta_module = mm.get_meta_module(instance) new_modules_dict2[k] = meta_module return new_modules_dict2, new_connections def execute_network(self, meta_modules): """Given a list of MetaModule instances, execute the network represented by those modules. List of metamodules can be found for example in the values() of the """ self.devide_app.network_manager.execute_network(meta_modules) def clear_network(self): # graphEditor.clear_all_glyphs_from_canvas() - delete network func # has to be moved to NetworkManager self.devide_app.network_manager.clear_network() def get_module_instance(self, module_name): mm = self.devide_app.get_module_manager() return mm.get_instance(module_name) def get_module_config(self, module_name): mi = self.get_module_instance(module_name) return mi.get_config() def set_module_config(self, module_name, config): mi = self.get_module_instance(module_name) mi.set_config(config)
Python
# required for this dir to be recognised as package.
Python
import copy from logging_mixin import LoggingMixin import os from simple_api_mixin import SimpleAPIMixin class ScriptInterface(SimpleAPIMixin, LoggingMixin): def __init__(self, devide_app): self.devide_app = devide_app # initialise logging mixin LoggingMixin.__init__(self) print "Initialising script interface..." def handler_post_app_init(self): """DeVIDE-required method for interfaces.""" pass def quit(self): pass def start_main_loop(self): self.log_message('Starting to execute script.') sv = self.devide_app.main_config.script script_params = self.devide_app.main_config.script_params if sv is None: self.log_error('No script name specified with --script.') self.log_error('Nothing to run, will exit.') else: g2 = {} g2.update(globals()) g2['interface'] = self g2['script_params'] = script_params execfile(sv, g2) self.log_message('Shutting down.') self.quit()
Python
import Pyro.core import time # client example: # import Pyro.core # Pyro.core.initClient() # URI = 'PYROLOC://localhost:7766/DeVIDE' # p = Pyro.core.getProxyForURI(URI) # p.test_func() class ServerProxy(Pyro.core.ObjBase): def test_function(self): return "Hello world!" class PyroInterface: def __init__(self, devide_app): self._devide_app = devide_app print "Initialising Pyro..." Pyro.core.initServer() self.daemon = Pyro.core.Daemon() self.server_proxy = ServerProxy() self.server_proxy_name = 'DeVIDE' self.uri = self.daemon.connect( self.server_proxy, self.server_proxy_name) self.easy_uri = 'PYROLOC://%s:%d/%s' % \ (self.daemon.hostname, self.daemon.port, self.server_proxy_name) def handler_post_app_init(self): """DeVIDE-required method for interfaces.""" pass def quit(self): self.daemon.disconnect(self.server_proxy) self.daemon.shutdown() def log_error_list(self, msgs): """Log a list of strings as error. This method must be supplied by all interfaces. """ for msg in msgs: print 'ERROR: %s' % (msg,) def log_error(self, message): """Log a single string as error. This method must be supplied by all interfaces. """ self.log_error_list([message]) def log_info(self, message, timeStamp=True): """Log information. This will simply go into the log window. """ if timeStamp: msg = "%s: %s" % ( time.strftime("%X", time.localtime(time.time())), message) else: msg = message print 'INFO: %s' % (msg,) def log_message(self, message, timeStamp=True): """Use this to log a message that has to be shown to the user in for example a message box. """ print 'MESSAGE: %s' % (message,) def log_warning(self, message, timeStamp=True): print 'WARNING: %s' % (message,) def set_progress(self, progress, message, noTime=False): # we also output an informative message to standard out # in cases where DeVIDE is very busy, this is quite # handy. print "PROGRESS: %s: %.2f" % (message, progress) def start_main_loop(self): self.log_message('DeVIDE available at %s' % (self.easy_uri,)) self.log_message('Starting Pyro request loop.') try: self.daemon.requestLoop() except KeyboardInterrupt: self.log_message('Got keyboard interrupt.') self.log_message('Shutting down.') self.quit()
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. # we use psutil for keeping an eye on memory (and crashes) # if you don't have this yet, install with: # dre shell # pip install psutil import psutil import string import sys import time import webbrowser import wx import wx.html #import resources.python.mainFrame import resources.graphics.images import main_frame class WXInterface(wx.App): """WX-based graphical user interface for DeVIDE. This contains all functionality that used to be in the main devide WX interface. I'm still working on the division between this class and the graph editor. For now: we keep this class as small as possible; it only handles WX-app central events. The GraphEditor does everything else. An alternative view would be that the GraphEditor is only concerned with the actual network editor canvas. As I said, I'm still working on this. NOTE: I'm leaning towards the latter approach. A third approach would be to factor out a third class responsible for the rest of the main UI. Then we'd have: WXInterface, GraphEditor, MysteryClass. """ def __init__(self, devide_app): self._devide_app = devide_app self._main_frame = None wx.App.__init__(self, 0) self._graph_editor = None self._python_shell = None def OnInit(self): """Standard WX OnInit() method, called during construction. """ # set the wx.GetApp() application name self.SetAppName('DeVIDE') #self._main_frame = resources.python.mainFrame.mainFrame( # None, -1, "dummy", name="DeVIDE") self._title = 'DeVIDE v%s' % (self._devide_app.get_devide_version(),) self._main_frame = main_frame.MainWXFrame(None, -1, self._title, (-1,-1), (800,600)) wx.InitAllImageHandlers() self._main_frame.SetIcon(self.getApplicationIcon()) wx.EVT_MENU(self._main_frame, self._main_frame.fileExitId, self.exitCallback) #wx.EVT_MENU(self._main_frame, self._main_frame.windowGraphEditorId, # self._handlerMenuGraphEditor) wx.EVT_MENU(self._main_frame, self._main_frame.window_python_shell_id, self._handler_menu_python_shell) #wx.EVT_MENU(self._main_frame, self._main_frame.windowMinimiseChildrenId, # lambda e: self._windowIconizeAllChildren()) #wx.EVT_MENU(self._main_frame, self._main_frame.windowRestoreChildrenId, # lambda e: self._windowRestoreAllChildren()) #wx.EVT_MENU(self._main_frame, self._main_frame.testingAllTestsId, # self._handlerTestingAllTests) wx.EVT_MENU(self._main_frame, self._main_frame.helpShowHelpId, self._handlerHelpContents) wx.EVT_MENU(self._main_frame, self._main_frame.helpAboutId, self.aboutCallback) # timer to update memory monitor every FIVE seconds self.timer = wx.PyTimer(self._handler_update_memory_display) self.timer.Start(5000) self._handler_update_memory_display() self._main_frame.Show(1) # here we also show twice: in wxPython 2.4.2.4 the TextCtrls sometimes # have difficulty completely drawing themselves at startup self._main_frame.Show(1) # with these calls, we force an immediate draw of the full window # if we don't do this, some of the controls are only drawn when # startup progress is 100% (this is on wxPython 2.6.0.1) self._main_frame.Refresh() self._main_frame.Update() self.SetTopWindow(self._main_frame) return True def OnExit(self): pass def getApplicationIcon(self): icon = wx.EmptyIcon() icon.CopyFromBitmap( resources.graphics.images.getdevidelogo32x32Bitmap()) return icon def getMainWindow(self): return self._main_frame def get_main_window(self): return self.getMainWindow() def _handlerHelpContents(self, event): self.showHelp() def _handler_load_network_at_startup(self, event): ge = self._graph_editor fn = self._devide_app.main_config.load_network ge._load_and_realise_network(fn) ge.canvas.reset_view() ge.set_current_filename(fn) def _handler_test_all(self, event): import testing reload(testing) dt = testing.DeVIDETesting(self._devide_app) dt.runAllTests() # after testing, we have to quit... self.quit() def handler_post_app_init(self): """AFTER we've started the GUI and performed all pre-imports, this method makes sure that all other dependencies are imported into the module namespace. We want these imports here, else the pre-imports can't do their thing. """ global GraphEditor, PythonShell from graph_editor import GraphEditor import module_kits from module_kits.wx_kit.python_shell import PythonShell self.start_graph_editor() # setup wx-based testing if necessary if self._devide_app.main_config.test: wx.EVT_TIMER(self, 999999, self._handler_test_all) self.timer = wx.Timer(self, 999999) self.timer.Start(150, True) if self._devide_app.main_config.load_network: # you have to keep a binding to the timer like this, or it # doesn't work at all. self.timer_ln = wx.Timer(self, -1) # now bind the timer event self.Bind( wx.EVT_TIMER, self._handler_load_network_at_startup, self.timer_ln) # then tell the timer to trigger it in 150ms self.timer_ln.Start(150, True) def _handler_update_memory_display(self): vmu = psutil.virtmem_usage() # SWAP / pagefile memory pmu = psutil.phymem_usage() # physical RAM # we show the user how much physical+swap they're using out of the total available total_used = (vmu[1]+pmu[1]) / 1024 / 1024 / 1024.0 total_avail = (vmu[0]+vmu[0]) / 1024 / 1024 / 1024.0 mem_msg = "%.1f / %.1f GB" % (total_used , total_avail) # write into the second section of the statusbar self._main_frame.GetStatusBar().SetStatusText(mem_msg, 1) # and log a warning to the message window if total_used / total_avail > 0.95: self.log_info("You have almost exhausted all available memory. Free up memory to prevent crashing.") def quit(self): """Event handler for quit request. Calls close on the app class, which will in turn call our close() handler. """ self._devide_app.close() def close(self): # python shell and all its sub-windows need to be closed as well if self._python_shell: self._python_shell.close() # take care of the graphEditor if it exists if self._graph_editor: self._graph_editor.close() # take care of main window self._main_frame.Close() def showHelp(self): webbrowser.open('http://code.google.com/p/devide/wiki/HelpIndex', new=1, autoraise=1) def start_python_shell(self): if self._python_shell == None: self._python_shell = PythonShell(self.getMainWindow(), 'Main DeVIDE Python Introspection', self.getApplicationIcon(), self._devide_app) self._python_shell.inject_locals({'devide_app' : self._devide_app, 'obj' : self._python_shell}) self._python_shell.set_statusbar_message( "'devide_app' is bound to the main app class, " "'obj' to the shell.") else: self._python_shell.show() def start_graph_editor(self): if self._graph_editor == None: self._graph_editor = GraphEditor(self, self._devide_app) else: self._graph_editor.show() def log_error_list(self, msgs): """Log a list of strings as error. This method must be supplied by all interfaces. """ for msg in msgs: wx.LogError(msg) wx.Log_FlushActive() def log_error(self, message): """Log a single string as error. This method must be supplied by all interfaces. """ self.log_error_list([message]) def log_info(self, message, timeStamp=True): """Log information. This will simply go into the log window. """ if timeStamp: msg = "%s: %s" % ( time.strftime("%X", time.localtime(time.time())), message) else: msg = message self._main_frame.message_log_text_ctrl.AppendText( msg + '\n') def log_message(self, message, timeStamp=True): """Use this to log a message that has to be shown to the user in for example a message box. """ wx.LogMessage(message) wx.Log_FlushActive() def log_warning(self, message, timeStamp=True): wx.LogWarning(message) wx.Log_FlushActive() def set_progress(self, progress, message, noTime=False): self._main_frame.set_progress(int(round(progress)), message) # we also output an informative message to standard out # in cases where DeVIDE is very busy, this is quite # handy. print "%s: %.2f" % (message, progress) # activate the busy cursor (we're a bit more lenient # on its epsilon) if abs(progress - 100.0) > 1: if not wx.IsBusy(): wx.BeginBusyCursor() # or switch it off else: if wx.IsBusy(): wx.EndBusyCursor() # let's also show the completion message in the # message log... self.log_info(message) # bring this window to the top if the user wants it #if self._main_frame.progressRaiseCheckBox.GetValue(): # self._main_frame.Raise() # we want wx to update its UI, but it shouldn't accept any # user input, else things can get really crazy. - # we do keep interaction for the main window enabled, # but we disable all menus. menuCount = self._main_frame.GetMenuBar().GetMenuCount() for menuPos in range(menuCount): self._main_frame.GetMenuBar().EnableTop(menuPos, False) wx.SafeYield(win=self._main_frame) for menuPos in range(menuCount): self._main_frame.GetMenuBar().EnableTop(menuPos, True) def set_status_message(self, msg): self._main_frame.GetStatusBar().SetStatusText(msg) def start_main_loop(self): self.MainLoop() def aboutCallback(self, event): from resources.python.aboutDialog import aboutDialog about = aboutDialog(self._main_frame, -1, 'dummy') about.icon_bitmap.SetBitmap( resources.graphics.images.getdevidelogo64x64Bitmap()) # set the main name and version about.name_version_text.SetLabel( 'DeVIDE v%s' % (self._devide_app.get_devide_version(),)) # now get all other versions we require pyver = string.split(sys.version)[0] about.versions_listbox.Append('Python %s' % (pyver,)) # get versions of all included kits; by this time ModuleManager # has been imported kits_and_versions = [] import module_kits for module_kit in module_kits.module_kit_list: v = getattr(module_kits, module_kit).VERSION about.versions_listbox.Append('%s: %s' % (module_kit, v)) about.GetSizer().Fit(about) about.Layout() about.CentreOnParent(wx.BOTH) about.ShowModal() about.Destroy() def exitCallback(self, event): self.quit() def _handlerMenuGraphEditor(self, event): self.start_graph_editor() def _handler_menu_python_shell(self, event): self.start_python_shell() def set_current_filename(self, filename): """Change the window title to reflect the current network filename. This is purely for display purposes and is used by the Graph Editor. """ self._main_frame.SetTitle('%s - %s' % (self._title, filename)) def _windowIconizeAllChildren(self): children = self._main_frame.GetChildren() for w in children: try: if w.IsShown() and not w.IsIconized(): try: w.Iconize() except wx.PyAssertionError: # we get this if it's not created yet pass except AttributeError: # it's a panel for instance pass def _windowRestoreAllChildren(self): children = self._main_frame.GetChildren() for w in children: try: # we don't want to attempt to restore things that are # hidden... only iconized if w.IsShown() and w.IsIconized(): try: w.Restore() # after a restore, we have to do a show, # or windows go crazy under Weendows. w.Show() except wx.PyAssertionError: # this is usually "not implemented" on gtk, so we # do an ugly work-around: store the window # position, hide it, show it, reposition it - # this even works under KDE p = w.GetPosition() w.Hide() w.Show() w.SetPosition(p) except AttributeError: # panels and stuff simply don't have this method pass
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. # FIXME: def show() should really be moved a level up!! # left click on glyph: select and drag # left click on canvas: rubberband select # right click on glyph: glyph context menu # right click on canvas: canvas context menu # middle click: pan # shift-middle click up and down: zoom out and in # mouse wheel: zoom # if you want to handle right-clicks on the ModulesListBox, seems EVT_CONTEXT_MENU # is the only way to go. See this discussion: # http://groups.google.com/group/wxpython-users/browse_thread/thread/0346be5e6d99a981 # (there's a python sample a little ways down) # for opening stuff with the default application, see here: # http://stackoverflow.com/questions/434597/open-document-with-default-application-in-python ALLCATS_STRING = "ALL categories" import copy from internal.devide_canvas.devide_canvas import DeVIDECanvas from internal.devide_canvas.devide_canvas_object import \ DeVIDECanvasGlyph, DeVIDECanvasLine, DeVIDECanvasSimpleLine, \ DeVIDECanvasRBBox import gen_utils from module_manager import ModuleManagerException import module_utils # for get_module_icon import os import re import string import sys import time import weakref import wx # so we're using VTK here for doing the graph layout. import vtk from module_kits.misc_kit import dprint # ---------------------------------------------------------------------------- class geCanvasDropTarget(wx.PyDropTarget): def __init__(self, graphEditor): wx.PyDropTarget.__init__(self) self._graphEditor = graphEditor do = wx.DataObjectComposite() tdo = wx.TextDataObject() fdo = wx.FileDataObject() do.Add(tdo) do.Add(fdo) self._tdo = tdo self._fdo = fdo self.SetDataObject(do) self._dataObject = do def OnDrop(self, x, y): return True def OnData(self, x, y, d): # when we are a drag source, we get blocked throughout the # drag, which means that our picked_cobject doesn't get # updated, which means that drops on glyphs don't get handled. # so here we make sure that the correct picked_cobject is # selected right before we actually handle the drop: self._graphEditor.canvas.update_picked_cobject_at_drop(x, y) if self.GetData(): # single line starting with 'module:' OR # single line starting with 'segment:' OR # multiple lines (with newlines), each specifying a # filename (URI) text = self._tdo.GetText() # array of unicode filenames filenames = self._fdo.GetFilenames() if len(text) > 0: # text gets precedence over filenames filenames = [] # we have to zero this, else filenames never get a # chance (fdo and tdo are persistent) self._tdo.SetText('') tlines = self._graphEditor.canvasDropText(x,y,text) # if text is NOT a segment or module spec, # canvasDropText will return an array of text lines # we assume that these could be filenames if tlines: filenames = tlines if len(filenames) > 0: # handle the list of filenames dropFilenameErrors = self._graphEditor.canvasDropFilenames( x,y,filenames) if len(dropFilenameErrors) > 0: em = ['The following dropped files could not ' 'be handled:'] for i in dropFilenameErrors: em.append( '%s: %s' % (i)) self._graphEditor._interface.log_warning( '\n'.join(em)) # d is the recommended drag result. we could also return # wx.DragNone if we don't want whatever's been dropped. return d # ---------------------------------------------------------------------------- class GlyphSelection: """Abstraction for any selection of glyphs. This is used for the default selection and for the blocked glyph selection currently. """ def __init__(self, canvas, glyph_flag): """ @param glyph_flag: string name of glyph attribute that will be set to true or false depending on the selection that it belongs to. """ self._canvas = canvas self._glyph_flag = glyph_flag self._selectedGlyphs = [] def close(self): # take care of all references self.removeAllGlyphs() def addGlyph(self, glyph): """Add a glyph to the selection. """ if glyph in self._selectedGlyphs: # it's already selected, ignore return # add it to our structures self._selectedGlyphs.append(glyph) # tell it that it's the chosen one (ha ha) setattr(glyph, self._glyph_flag, True) #glyph.selected = True # redraw it glyph.update_geometry() def getSelectedGlyphs(self): """Returns a list with the selected glyphs. Do not modify externally. """ return self._selectedGlyphs def removeGlyph(self, glyph): """Remove a glyph from the selection. """ if not glyph in self._selectedGlyphs: # it's not in the selection, do nothing. return del self._selectedGlyphs[self._selectedGlyphs.index(glyph)] setattr(glyph, self._glyph_flag, False) #glyph.selected = False glyph.update_geometry() def removeAllGlyphs(self): """Remove all glyphs from selection. """ for glyph in self._selectedGlyphs: glyph.selected = False glyph.update_geometry() self._selectedGlyphs = [] def selectGlyph(self, glyph): """Set the selection on one single glyph. All others must be unselected. """ self.removeAllGlyphs() self.addGlyph(glyph) # ---------------------------------------------------------------------------- class GraphEditor: def __init__(self, interface, devideApp): # initialise vars self._interface = interface self._devide_app = devideApp mf = self._interface._main_frame em = mf.edit_menu self._append_edit_commands(em, mf, None, False) self._append_network_commands(mf.network_menu, mf, False) wx.EVT_MENU(mf, mf.id_modules_search, self._handler_modules_search) wx.EVT_MENU(mf, mf.id_rescan_modules, lambda e, s=self: s.fill_module_lists()) wx.EVT_MENU(mf, mf.id_refresh_module_kits, self._handler_refresh_module_kits) wx.EVT_MENU(mf, mf.fileNewId, self._fileNewCallback) wx.EVT_MENU(mf, mf.fileExitId, self._fileExitCallback) wx.EVT_MENU(mf, mf.fileOpenId, self._fileOpenCallback) wx.EVT_MENU(mf, mf.fileOpenSegmentId, self._handlerFileOpenSegment) wx.EVT_MENU(mf, mf.fileSaveId, self._fileSaveCallback) wx.EVT_MENU(mf, mf.id_file_save_as, self._handler_file_save_as) wx.EVT_MENU(mf, mf.id_file_export, self._handler_file_export) wx.EVT_MENU(mf, mf.fileSaveSelectedId, self._handlerFileSaveSelected) wx.EVT_MENU(mf, mf.fileExportAsDOTId, self._handlerFileExportAsDOT) wx.EVT_MENU(mf, mf.fileExportSelectedAsDOTId, self._handlerFileExportSelectedAsDOT) wx.EVT_MENU(mf, mf.helpShowHelpId, self._handlerHelpShowHelp) # every time a normal character is typed mf.search.Bind(wx.EVT_TEXT, self._handler_search) # we do this to capture enter, escape and up and down # we need this nasty work-around on win and gtk: the # SearchCtrl doesn't trigger the necessary events itself. if wx.Platform in ['__WXMSW__', '__WXGTK__']: for child in mf.search.GetChildren(): if isinstance(child, wx.TextCtrl): child.Bind(wx.EVT_CHAR, self._handler_search_char) break else: mf.search.Bind(wx.EVT_CHAR, self._handler_search_char) # user clicks on x, search box is emptied. mf.search.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN, self._handler_search_x_button) # when the user changes category, update the search results mf.module_cats_choice.Bind(wx.EVT_CHOICE, self._update_search_results) wx.EVT_LISTBOX(mf, mf.module_list_box.GetId(), self._handlerModulesListBoxSelected) # this will be filled in by self.fill_module_tree; it's here for # completeness self._available_modules = None # this is usually shortly after initialisation, so a module scan # should be available. Actually, the user could be very naughty, # but let's not think about that. self.fill_module_lists(scan_modules=False) wx.EVT_MOUSE_EVENTS(mf.module_list_box, self._handlerModulesListBoxMouseEvents) # instantiate the canvas. self.canvas = DeVIDECanvas(mf._rwi, mf._ren) # the canvas is a drop target self._canvasDropTarget = geCanvasDropTarget(self) # the vtkRenderWindowInteractor is also a WX construct. mf._rwi.SetDropTarget(self._canvasDropTarget) # bind events on the canvas self.canvas.add_observer('left_button_down', self._observer_canvas_left_down) self.canvas.add_observer('right_button_down', self._observer_canvas_right_down) self.canvas.add_observer('left_button_up', self._observer_canvas_left_up) self.canvas.add_observer('dragging', self._observer_canvas_drag) # bind some global hotkeys on the RWI (not on the whole main # frame... we want to delete to keep working in the rest of # the interface) mf._rwi.SetAcceleratorTable( wx.AcceleratorTable( [(wx.ACCEL_NORMAL, wx.WXK_DELETE, self.ID_DELETE_GLYPHS)])) # initialise selection self._selected_glyphs = GlyphSelection(self.canvas, 'selected') self._blocked_glyphs = GlyphSelection(self.canvas, 'blocked') # we'll use this to keep track of the rubber-band box self._rbb_box = None # line used for previewing possible connections self._preview_line = None # initialise cut/copy/paste buffer self._copyBuffer = None # initialise current filename self.set_current_filename(None) # On Windows, file open/save dialogs remember where you last # used them. On Linux, we have to do this ourselves. If we # don't, every new selection dialog starts on the current # directory. self._last_fileselector_dir = '' # instrument network_manager with handler so we can autosave # before a network gets executed self._devide_app.network_manager.add_observer( 'execute_network_start', self._observer_network_manager_ens) # now display the shebang # (GraphEditor controls the GraphEditor bits...) self.show() def _handler_modules_search(self, event): self._interface._main_frame.search.SetFocus() def _handler_refresh_module_kits(self, event): mm = self._devide_app.get_module_manager() mm.refresh_module_kits() def _handler_search(self, event): """Handler for when the user types into the search box. """ self._update_search_results() def _place_current_module_at_convenient_pos(self): """Place currently selected module (in the Module List subwindow) at an open position on the canvas. This method is called when the user double clicks on a module in the module list or when she presses <enter> during module searching. """ # place currently selected module below the bottom-most module # on the canvas mlb = self._interface._main_frame.module_list_box # _update_search_results() makes sure the first selectable # item is selected sel = mlb.GetSelection() shortName, module_name = (mlb.GetString(sel), mlb.GetClientData(sel)) if module_name: canvas = self.canvas # find all glyphs that are visible at the moment all_glyphs = self._get_all_glyphs() tl = self.canvas.get_top_left_world() br = self.canvas.get_bottom_right_world() bl = tl[0], br[1] w,h = canvas.get_wh_world() # determine all visible glyphs visible_glyphs = [] for g in all_glyphs: if g.is_inside_rect(bl, w, h): visible_glyphs.append(g) # determine minx and miny of all glyphs last_height = 0 if visible_glyphs: minx,miny = visible_glyphs[0].get_position() last_height = visible_glyphs[0].get_bounds()[1] for g in visible_glyphs: x,y = g.get_position() if y < miny: miny = y last_height = g.get_bounds()[1] if x < minx: minx = x ph = DeVIDECanvasGlyph._pHeight x = minx y = miny - last_height - 2.0*ph - 10 else: # default position is in the centre; but below all other # glyphs if there are any y = tl[1] - h / 2.0 # default position is the centre; but lined up with the # left of all other glyphs if there are any x = tl[0] + w / 2.0 if y < bl[1]: # glyph would end up below the visible viewport canvas.pan_canvas_world(0, - h / 4.0) modp = 'module:' segp = 'segment:' if module_name.startswith(modp): # the coordinates are canvas-absolute already self.create_module_and_glyph(x, y, module_name[len(modp):]) elif module_name.startswith(segp): self._load_and_realise_network(module_name[len(segp):], (x,y), reposition=True) else: # this could happen, I've no idea how though. return False # module or segment successfully created return True # no module or segment was created return False def _handler_search_char(self, event): key_code = event.GetKeyCode() if key_code == wx.WXK_ESCAPE: self._interface._main_frame.search.SetValue('') elif key_code == wx.WXK_RETURN: self._place_current_module_at_convenient_pos() self._interface._main_frame.search.SetFocus() elif key_code in [wx.WXK_UP, wx.WXK_DOWN]: mlb = self._interface._main_frame.module_list_box sel = mlb.GetSelection() if sel >= 0: if key_code == wx.WXK_UP: sel -= 1 else: sel += 1 if sel >= 0 and sel < mlb.GetCount(): # this SetSelection doesn't seem to call the # event handlers for the mlb (thus updating the help) mlb.SetSelection(sel) # so we call it manually self._handlerModulesListBoxSelected(None) else: event.Skip() def _handler_search_x_button(self, event): self._interface._main_frame.search.SetValue('') def _handlerModulesListBoxMouseEvents(self, event): if event.ButtonDClick(): self._place_current_module_at_convenient_pos() # user has dragged and dropped module, if a viewer module # has taken focus with Raise(), we have to take it back. self.canvas._rwi.SetFocus() wx.SafeYield() return if not event.Dragging(): # if no dragging is taking place, let somebody else # handle this event... event.Skip() return mlb = self._interface._main_frame.module_list_box sel = mlb.GetSelection() if sel >= 0: shortName, module_name = mlb.GetString(sel), mlb.GetClientData(sel) if type(module_name) != str: return dataObject = wx.TextDataObject(module_name) dropSource = wx.DropSource(self._interface._main_frame.module_list_box) dropSource.SetData(dataObject) # we don't need the result of the DoDragDrop call (phew) # the param is supposedly the copy vs. move flag; True is move. # on windows, setting it to false disables the drop on the canvas. dropSource.DoDragDrop(True) # event processing has to continue, else the listbox keeps listening # to mouse movements after the glyph has been dropped #event.Skip() def _blockmodule(self, glyph): """Block the module represented by glyph. This does does not invoke a canvas redraw, as these methods can be called in batches. Invoking code should call redraw. """ # first get the module manager to block this mm = self._devide_app.get_module_manager() mm.blockmodule(mm.get_meta_module(glyph.module_instance)) # then tell the glyph about it self._blocked_glyphs.addGlyph(glyph) # finally tell the glyph to update its geometry glyph.update_geometry() def _unblockmodule(self, glyph): """Unblock the module represented by glyph. This does does not invoke a canvas redraw, as these methods can be called in batches. Invoking code should call redraw. """ # first get the module manager to unblock this mm = self._devide_app.get_module_manager() mm.unblockmodule(mm.get_meta_module(glyph.module_instance)) # then tell the glyph about it self._blocked_glyphs.removeGlyph(glyph) # finally tell the glyph to update its geometry glyph.update_geometry() def _execute_modules(self, glyphs): """Given a list of glyphs, request the scheduler to execute only those modules. Of course, producers of selected modules will also be asked to resend their output, even although they are perhaps not part of the selection. This method is called by event handlers in the GraphEditor. """ instances = [g.module_instance for g in glyphs] mm = self._devide_app.get_module_manager() allMetaModules = [mm._module_dict[instance] for instance in instances] try: self._devide_app.network_manager.execute_network(allMetaModules) except Exception, e: # if an error occurred, but progress is not at 100% yet, # we have to put it there, else app remains in visually # busy state. if self._devide_app.get_progress() < 100.0: self._devide_app.set_progress( 100.0, 'Error during network execution.') # finally report the exception. self._devide_app.log_error_with_exception(str(e)) def _handler_blockmodules(self, event): """Block all selected glyphs and their modules. """ for glyph in self._selected_glyphs.getSelectedGlyphs(): self._blockmodule(glyph) # then update the display self.canvas.redraw() def _handler_unblockmodules(self, event): """Unblock all selected glyphs and their modules. """ for glyph in self._selected_glyphs.getSelectedGlyphs(): self._unblockmodule(glyph) # then update the display self.canvas.redraw() def _handler_execute_network(self, event): """Event handler for 'network|execute' menu call. Gets list of all instances in current network, converts these to scheduler modules and requests the scheduler to execute them. """ allGlyphs = self.canvas.getObjectsOfClass(DeVIDECanvasGlyph) self._execute_modules(allGlyphs) def _handler_execute_selected(self, event): self._execute_modules(self._selected_glyphs.getSelectedGlyphs()) def canvasDropText(self, x, y, itemText): """itemText is a complete module or segment spec, e.g. module:modules.Readers.dicomRDR or segment:/home/cpbotha/work/code/devide/networkSegments/blaat.dvn x,y are in wx coordinates. @returns: empty list, or list with unhandled lines in itemText. """ modp = 'module:' segp = 'segment:' w_x,w_y,w_z = self.canvas.display_to_world((x,self.canvas.flip_y(y))) if itemText.startswith(modp): self.create_module_and_glyph(w_x, w_y, itemText[len(modp):]) # if the user has dropped a module on the canvas, we want # the focus to return to the canvas, as the user probably # wants to connect the thing up. if we don't do this, # some viewer modules takes focus. Thanks Peter Krekel. self.canvas._rwi.SetFocus() wx.SafeYield() return [] elif itemText.startswith(segp): self._load_and_realise_network(itemText[len(segp):], (w_x,w_y), reposition=True) # see explanation above for the SetFocus self.canvas._rwi.SetFocus() wx.SafeYield() return [] else: # not a module or segment spec, might be a list of URIs, # including filenames; we return an array # text/uri-list (RFC 2483) return itemText.split('\r\n') def canvasDropFilenames(self, x, y, filenames): """Event handler for when the user drops a list of filenames on the canavs. @param x,y: coordinates in the wx system. """ # before we do anything, convert to world coordinates w_x,w_y,w_z = \ self.canvas.display_to_world((x,self.canvas.flip_y(y))) def create_module_one_var(module_name, configVarName, configVarValue, newModuleName=None): """This method creates a module_name (e.g. modules.Readers.vtiRDR) at position x,y. It then sets the 'configVarName' attribute to value configVarValue. """ (mod, glyph) = self.create_module_and_glyph(w_x, w_y, module_name) if mod: cfg = mod.get_config() setattr(cfg, configVarName, filename) mod.set_config(cfg) if newModuleName: r = self._rename_module(mod, glyph, newModuleName) #i = 0 #while not r: # i += 1 # r = self._rename_module(mod, glyph, '%s (%d)' % # (newModuleName, i)) def handle_drop_on_glyph(glyph, filename): """Adds whole list of filenames to dicomRDR list, or adds first filename in list if its any other module with a filename attribute in its config struct. """ mi = g.module_instance c = mi.get_config() mm = self._devide_app.get_module_manager() if mi.__class__.__name__ == 'dicomRDR': c = mi.get_config() del c.dicomFilenames[:] c.dicomFilenames.extend(filenames) # this will do the whole config -> logic -> view dance # view is only done if view_initialised is True mi.set_config(c) return True elif mi.__class__.__name__ == 'DICOMReader': c = mi.get_config() del c.dicom_filenames[:] c.dicom_filenames.extend(filenames) mi.set_config(c) return True elif hasattr(c, 'filename'): c = mi.get_config() c.filename = filenames[0] mi.set_config(c) return True else: return False actionDict = {'vti' : ('modules.readers.vtiRDR', 'filename'), 'vtp' : ('modules.readers.vtpRDR', 'filename'), 'mha' : ('modules.readers.metaImageRDR', 'filename'), 'mhd' : ('modules.readers.metaImageRDR', 'filename'), 'stl' : ('modules.readers.stlRDR', 'filename')} # list of tuples: (filename, errormessage) dropFilenameErrors = [] # shortcut for later canvas = self.canvas # filename mod code ========================================= # dropping a filename on an existing module will try to change # that module's config.filename (if it exists) to the dropped # filename. if not successful, the normal logic for dropped # filenames applies. #g = canvas.get_glyph_on_coords(rx,ry) g = canvas.event.picked_cobject dprint("canvasDropFilename:: picked_cobject", g) if g: # returns True if glyph did something with drop... ret = handle_drop_on_glyph(g, filenames) if ret: return dropFilenameErrors # end filename mod code dcmFilenames = [] for filename in filenames: if filename.lower().endswith('.dvn'): # we have to convert the event coords to real coords self._load_and_realise_network(filename, (w_x,w_y), reposition=True) # some DVNs contain viewer modules that take the focus # (due to Raise). Here we take it back to the canvas, # most logical thing we can do. self.canvas._rwi.SetFocus() wx.SafeYield() elif filename.lower().endswith('.vtk'): # for this type we have to do some special handling. # it could be a structuredpoints or a polydata, so we # have to read the first few lines to determine try: # read first four lines of file, fourth is what we want f = file(filename) for i in range(4): fline = f.readline() fline = fline.strip().lower() except Exception, e: dropFilenameErrors.append( (filename, 'Could not parse VTK file to distinguish type.')) else: # this only executes if there was no exception if fline.endswith('structured_points'): create_module_one_var( 'modules.readers.vtkStructPtsRDR', 'filename', filename, os.path.basename(filename)) elif fline.lower().endswith('polydata'): create_module_one_var( 'modules.readers.vtkPolyDataRDR', 'filename', filename, os.path.basename(filename)) else: dropFilenameErrors.append( (filename, 'Could not distinguish type of VTK file.')) elif filename.lower().endswith('.dcm'): dcmFilenames.append(filename) else: ext = filename.split('.')[-1].lower() if ext in actionDict: create_module_one_var(actionDict[ext][0], actionDict[ext][1], filename, os.path.basename(filename)) else: dropFilenameErrors.append( (filename, 'File extension not known.')) # ends for filename in filenames if len(dcmFilenames) > 0: (mod,glyph) = self.create_module_and_glyph( w_x, w_y, 'modules.readers.DICOMReader') if mod: try: cfg = mod.get_config() cfg.dicom_filenames.extend(dcmFilenames) mod.set_config(cfg) except Exception, e: dropFilenameErrors.append( ('DCM files', 'Error loading DICOM files: %s.' % (str(e),))) return dropFilenameErrors def close(self): """This gracefull takes care of all graphEditor shutdown and is mostly called at application shutdown. """ # remove the observer we have placed on the network manager self._devide_app.network_manager.remove_observer( 'execute_network_start', self._observer_network_manager_ens) # make sure no refs are stuck in the selection self._selected_glyphs.close() # this should take care of just about everything! self.clear_all_glyphs_from_canvas() # this will take care of all cleanup (including the VTK stuff) # and then Destroy() the main WX window. self._interface._main_frame.close() def _append_edit_commands(self, pmenu, eventWidget, origin, disable=True): """Append copy/cut/paste/delete commands and the default handlers to a given menu. Origin is used by the paste command, and should be the REAL canvas coordinates, i.e. with scroll position taken into account. """ copyId = wx.NewId() ni = wx.MenuItem(pmenu, copyId, '&Copy Selected\tCtrl-C', 'Copy the selected glyphs into the copy buffer.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, copyId, self._handlerCopySelected) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) cutId = wx.NewId() ni = wx.MenuItem(pmenu, cutId, 'Cu&t Selected\tCtrl-X', 'Cut the selected glyphs into the copy buffer.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, cutId, self._handlerCutSelected) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) pasteId = wx.NewId() ni = wx.MenuItem( pmenu, pasteId, '&Paste\tCtrl-V', 'Paste the contents of the copy buffer onto the canvas.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, pasteId, lambda e: self._handlerPaste(e, origin)) if disable: if not self._copyBuffer: ni.Enable(False) deleteId = wx.NewId() ni = wx.MenuItem(pmenu, deleteId, '&Delete Selected\tCtrl-D', 'Delete all selected glyphs.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, deleteId, lambda e: self._delete_selected_glyphs()) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) self.ID_DELETE_GLYPHS = deleteId testId = wx.NewId() ni = wx.MenuItem(pmenu, testId, 'Test Selected', 'Test all selected glyphs.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, testId, lambda e: self._testSelectedGlyphs()) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) def _append_network_commands(self, pmenu, eventWidget, disable=True): """Append copy/cut/paste/delete commands and the default handlers to a given menu. """ ############################################################# execute_id = wx.NewId() ni = wx.MenuItem(pmenu, execute_id, 'E&xecute network\tF5', 'Execute the complete network.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, execute_id, self._handler_execute_network) ############################################################# execute_selected_id = wx.NewId() ni = wx.MenuItem(pmenu, execute_selected_id, 'E&xecute selected modules', 'Execute only the selected modules.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, execute_selected_id, self._handler_execute_selected) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) ############################################################# block_id = wx.NewId() ni = wx.MenuItem(pmenu, block_id, '&Block Selected\tCtrl-B', 'Block selected modules from executing.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, block_id, self._handler_blockmodules) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) ############################################################# unblock_id = wx.NewId() ni = wx.MenuItem(pmenu, unblock_id, '&Unblock Selected\tCtrl-U', 'Unblock selected modules so that they can execute.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, unblock_id, self._handler_unblockmodules) if disable: if not self._selected_glyphs.getSelectedGlyphs(): ni.Enable(False) ############################################################# if False: layout_sucky_id = wx.NewId() ni = wx.MenuItem(pmenu, layout_sucky_id, 'Sucky graph layout\tF7', 'Perform SUCKY(tm) graph layout.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, layout_sucky_id, lambda e: self._layout_network_sucky()) reset_graph_view_id = wx.NewId() ni = wx.MenuItem(pmenu, reset_graph_view_id, 'Reset Graph Canvas view\tCtrl-R', 'Reset Graph Canvas view so that whole network is visible.') pmenu.AppendItem(ni) wx.EVT_MENU(eventWidget, reset_graph_view_id, lambda e: self.canvas.reset_view()) def _testSelectedGlyphs(self): si = [i.module_instance for i in self._selected_glyphs.getSelectedGlyphs()] def create_glyph(self, rx, ry, labelList, module_instance): """Create only a glyph on the canvas given an already created module_instance. labelList is a list of strings that will be printed inside the glyph representation. The glyph instance is returned. @param rx,ry: world coordinates of new glyph. """ co = DeVIDECanvasGlyph(self.canvas, (rx, ry), len(module_instance.get_input_descriptions()), len(module_instance.get_output_descriptions()), labelList, module_instance) self.canvas.add_object(co) co.add_observer('motion', self._observer_glyph_motion) co.add_observer('left_button_down', self._observer_glyph_left_button_down) co.add_observer('right_button_down', self._observer_glyph_right_button_down) co.add_observer('left_button_up', self._observer_glyph_left_button_up) co.add_observer('dragging', self._observer_glyph_dragging) co.add_observer('left_button_dclick', self._observer_glyph_left_button_dclick) # make sure we are redrawn. self.canvas.redraw() # the network loading needs this return co def create_module_and_glyph(self, x, y, module_name): """Create a DeVIDE and a corresponding glyph at world coordinates x,y. @return: a tuple with (module_instance, glyph) if successful, (None, None) if not. """ # check that it's a valid module name if module_name in self._available_modules: # we have a valid module, we should try and instantiate mm = self._devide_app.get_module_manager() try: temp_module = mm.create_module(module_name) except ModuleManagerException, e: self._devide_app.log_error_with_exception( 'Could not create module %s: %s' % (module_name, str(e))) return (None, None) # if the module_manager did its trick, we can make a glyph if temp_module: # the modulemanager generates a random module name, # which we query with get_instance_name gLabel = [module_name.split('.')[-1], mm.get_instance_name(temp_module)] glyph = self.create_glyph(x,y,gLabel,temp_module) # route all lines self._route_all_lines() return (temp_module, glyph) def _execute_module(self, module_instance): """Ask the ModuleManager to execute the devide module represented by the parameter module_instance. """ mm = self._devide_app.get_module_manager() mm.execute_module(module_instance) def _module_doc_to_html(self, full_module_name, doc): # do rudimentary __doc__ -> html conversion docLines = string.split(doc.strip(), '\n') for idx in range(len(docLines)): docLine = docLines[idx].strip() if docLine == '': docLines[idx] = '<br><br>' # add pretty heading htmlDoc = '<center><b>%s</b></center><br><br>' % \ (full_module_name,) + string.join(docLines, '\n') # finally change the contents of the new/existing module help window return '<html><body>%s</body></html>' % (htmlDoc,) def fill_module_lists(self, scan_modules=True): """Build up the module tree from the list of available modules supplied by the ModuleManager. At the moment, things will look a bit strange if the module tree goes deeper than one level, but everything will still work. """ mm = self._devide_app.get_module_manager() if scan_modules: mm.scan_modules() self._available_modules = mm.get_available_modules() self._moduleCats = {} # let's build up new dictionary with categoryName as key and # list of complete module_names as value - check for 'Segments', # that's reserved for mn,module_metadata in self._available_modules.items(): # we add an ALL category implicitly to all modules for cat in module_metadata.cats + [ALLCATS_STRING]: if cat in self._moduleCats: self._moduleCats[cat].append('module:%s' % (mn,)) else: self._moduleCats[cat] = ['module:%s' % (mn,)] # list of DVN filenames if len(mm.availableSegmentsList) > 0: self._moduleCats['Segments'] = ['segment:%s' % (i,) for i in mm.availableSegmentsList] # this should add all segments to the ALLCATS_STRING category self._moduleCats[ALLCATS_STRING] += self._moduleCats['Segments'] # setup all categories self._interface._main_frame.module_cats_choice.Clear() idx = 0 cats = self._moduleCats.keys() cats.sort() # but make sure that ALL is up front, no matter what del cats[cats.index(ALLCATS_STRING)] cats = [ALLCATS_STRING] + cats for cat in cats: self._interface._main_frame.module_cats_choice.Append(cat) self._interface._main_frame.module_cats_choice.Select(0) self._update_search_results() def find_glyph(self, meta_module): """Given a meta_module, return the glyph that contains it. @return: glyph if found, None otherwise. """ all_glyphs = self.canvas.getObjectsOfClass(DeVIDECanvasGlyph) found = False for glyph in all_glyphs: if glyph.module_instance == meta_module.instance: found = True break # get out of this for if found: return glyph else: return None def _handlerGraphFrameClose(self, event): self.hide() def show(self): # this is BAD. why is the graph editor doing all of this and # not the interface? self._interface._main_frame.Show(True) self._interface._main_frame.Iconize(False) self._interface._main_frame.Raise() self.canvas.redraw() # we have to call into wx to get everything to actually # display. wx.SafeYield() def _handlerFileExportAsDOT(self, event): # make a list of all glyphs allGlyphs = self.canvas.getObjectsOfClass(DeVIDECanvasGlyph) if allGlyphs: filename = wx.FileSelector( "Choose filename for GraphViz DOT file", self._last_fileselector_dir, "", "dot", "GraphViz DOT files (*.dot)|*.dot|All files (*.*)|*.*", wx.SAVE) if filename: # save directory for future use self._last_fileselector_dir = \ os.path.dirname(filename) # if the user has NOT specified any fileextension, we # add .dot. (on Win this gets added by the # FileSelector automatically, on Linux it doesn't) if os.path.splitext(filename)[1] == '': filename = '%s.dot' % (filename,) self._exportNetworkAsDOT(allGlyphs, filename) def _handlerFileExportSelectedAsDOT(self, event): glyphs = self._selected_glyphs.getSelectedGlyphs() if glyphs: filename = wx.FileSelector( "Choose filename for GraphViz DOT file", self._last_fileselector_dir, "", "dot", "GraphViz DOT files (*.dot)|*.dot|All files (*.*)|*.*", wx.SAVE) if filename: # save directory for future use self._last_fileselector_dir = \ os.path.dirname(filename) # if the user has NOT specified any fileextension, we # add .dot. (on Win this gets added by the # FileSelector automatically, on Linux it doesn't) if os.path.splitext(filename)[1] == '': filename = '%s.dot' % (filename,) self._exportNetworkAsDOT(glyphs, filename) def _handlerFileOpenSegment(self, event): filename = wx.FileSelector( "Choose DeVIDE network to load into copy buffer", self._last_fileselector_dir, "", "dvn", "DeVIDE networks (*.dvn)|*.dvn|All files (*.*)|*.*", wx.OPEN) if filename: # save directory for future use self._last_fileselector_dir = \ os.path.dirname(filename) self._load_network_into_copy_buffer(filename) def _handlerFileSaveSelected(self, event): glyphs = self._selected_glyphs.getSelectedGlyphs() if glyphs: filename = wx.FileSelector( "Choose filename for DeVIDE network", self._last_fileselector_dir, "", "dvn", "DeVIDE networks (*.dvn)|*.dvn|All files (*.*)|*.*", wx.SAVE) if filename: # save directory for future use self._last_fileselector_dir = \ os.path.dirname(filename) # if the user has NOT specified any fileextension, we # add .dvn. (on Win this gets added by the # FileSelector automatically, on Linux it doesn't) if os.path.splitext(filename)[1] == '': filename = '%s.dvn' % (filename,) self._save_network(glyphs, filename) def _update_search_results(self, event=None): """Each time the user modifies the module search string or the category selection, this method is called to update the list of modules that can be selected. """ mf = self._interface._main_frame # get complete search results for this search string t = mf.search.GetValue() if t: mm = self._devide_app.get_module_manager() search_results = mm.module_search.find_matches(t) # search_results is dictionary {'name' : {'module.name' : 1, # 'other.module.name' : 1}, 'keywords' : ... else: # None is different from an empty dictionary search_results = None mcc = mf.module_cats_choice selected_cat = mcc.GetStringSelection() results_disp = {'misc' : [], 'name' : [], 'keywords' : [], 'help' : []} # now go through search results adding all modules that have # the correct categories if search_results is not None: for srkey in search_results: # srkey is a full module name and is guaranteed to be unique cat_found = False if selected_cat == ALLCATS_STRING: # we don't have to check categories cat_found = True else: if srkey.startswith('segment:'): if selected_cat == 'Segments': cat_found = True else: # srkey starts with module: or segment:, we have to # remove this module_name = srkey.split(':')[1] for c in mm._available_modules[module_name].cats: if c == selected_cat: cat_found = True # stop with for iteration break if cat_found: # now go through the different where-founds # wfs is a dict {'wf1' : 1, 'wf2' : 1} wfs = search_results[srkey] for wf in wfs: results_disp[wf].append('%s' % (srkey,)) else: # no search string, only selected categories results_disp['misc'] = self._moduleCats[selected_cat] # make sure separate results are sorted for where_found in results_disp: results_disp[where_found].sort() # now populate the mlb mlb = mf.module_list_box mlb.Clear() for section in ['misc', 'name', 'keywords', 'help']: if section != 'misc' and len(results_disp[section]) > 0: mlb.Append('<b><center>- %s match -</center></b>' % (section.upper(),), data=None, refresh=False) for mn in results_disp[section]: if mn.startswith('segment'): shortname = os.path.splitext(os.path.basename(mn))[0] else: # changes module:blaat.boo into boo and also # module:bar into bar. shortname = mn.split(':')[-1].split('.')[-1] mlb.Append(shortname, mn, refresh=False) # make sure the list is actually updated (we've appended a bunch # of things with refresh=False mlb.DoRefresh() # and select the first selectable item in the mlb # only the actual modules and segments have module_names sel = -1 module_name = None while module_name is None and sel < mlb.GetCount(): module_name = mlb.GetClientData(sel) sel += 1 if module_name: # this setselection does not fire the listbox event mlb.SetSelection(sel-1) # so we call the handler manually (so help is updated) self._handlerModulesListBoxSelected(None) def _handler_inject_module(self, module_instance): pyshell = self._devide_app.get_interface()._python_shell if not pyshell: self._devide_app.get_interface().log_message( 'Please activate Python Shell first.') return mm = self._devide_app.get_module_manager() bname = wx.GetTextFromUser( 'Enter a name to which the instance should be bound.', 'Input text', mm.get_instance_name(module_instance)) # we inject a weakref to the module, so that it can still be # destroyed when the user wishes to do that. if bname: pyshell.inject_locals( {bname : weakref.proxy(module_instance)}) def _reload_module(self, module_instance, glyph): """Reload a module by storing all configuration information, deleting the module, and then recreating and reconnecting it. @param module_instance: the instance that's to be reloaded. @param glyph: the glyph that represents the module. """ mm = self._devide_app.get_module_manager() meta_module = mm.get_meta_module(module_instance) # prod_tuple contains a list of (prod_meta_module, output_idx, # input_idx) tuples prod_tuples = mm.get_producers(meta_module) # cons_tuples contains a list of (output_index, consumer_meta_module, # consumer input index) cons_tuples = mm.get_consumers(meta_module) # store the instance name instance_name = meta_module.instance_name # and the full module spec name full_name = meta_module.module_name # and get the module state (we make a deep copy just in case) module_config = copy.deepcopy(meta_module.instance.get_config()) # and even the glyph position gp_x, gp_y = glyph.get_position() # now disconnect and nuke the old module self._delete_module(glyph) # FIXME: error checking # create a new one (don't convert my coordinates) new_instance, new_glyph = self.create_module_and_glyph( gp_x, gp_y, full_name) if new_instance and new_glyph: # give it its name back self._rename_module(new_instance, new_glyph, instance_name) try: # and its config (FIXME: we should honour pre- and # post-connect config!) new_instance.set_config(module_config) except Exception, e: self._devide_app.log_error_with_exception( 'Could not restore state/config to module %s: %s' % (new_instance.__class__.__name__, e) ) # connect it back up for producer_meta_module, output_idx, input_idx in prod_tuples: producer_glyph = self.find_glyph(producer_meta_module) # connect reports the error internally, so we'll just # continue trying to connect up things self._connect(producer_glyph, output_idx, new_glyph, input_idx) for output_idx, consumer_meta_module, input_idx in cons_tuples: consumer_glyph = self.find_glyph(consumer_meta_module) self._connect(new_glyph, output_idx, consumer_glyph, input_idx) self.canvas.redraw() wx.SafeYield() def _rename_module(self, module, glyph, newModuleName): if newModuleName: # try to rename the module... new_name = self._devide_app.get_module_manager().rename_module( module,newModuleName) if new_name: # if no conflict, set label and redraw ll = [module.__class__.__name__] ll.append(new_name) # change the list of labels glyph.setLabelList(ll) # which means we have to update the geometry (so they # are actually rendered) glyph.update_geometry() # which means we probably have to reroute lines as the # module might have changed size self._route_all_lines() self.canvas.redraw() return True else: # there was a conflict, return false return False else: # the user has given us a blank or None modulename... we'll rename # the module with an internal random name and remove its label uin = self._devide_app.get_module_manager()._make_unique_instance_name() rr = self._devide_app.get_module_manager().rename_module(module, uin) if rr: glyph.setLabelList([module.__class__.__name__, rr]) self.canvas.redraw() return True else: return False def _handler_reload_module(self, module_instance, glyph): self._reload_module(module_instance, glyph) def _handlerRenameModule(self, module, glyph): newModuleName = wx.GetTextFromUser( 'Enter a new name for this module.', 'Rename Module', self._devide_app.get_module_manager().get_instance_name(module)) if newModuleName: self._rename_module(module, glyph, newModuleName) def _handlerModulesListBoxSelected(self, event): """Handler called when user selects a single item from the Module List at the bottom left. """ mlb = self._interface._main_frame.module_list_box idx = mlb.GetSelection() if idx >= 0: cdata = mlb.GetClientData(idx) if cdata is not None: self._interface._main_frame.GetStatusBar().SetStatusText(cdata) self.show_module_help(cdata) def _determine_paste_pos(self): """Determine position to paste a network in the copy buffer. This is used if the user triggers the paste via hotkey and there's no event position. Network will be pasted to the right of all visible modules. """ canvas = self.canvas # find all glyphs that are visible at the moment all_glyphs = self._get_all_glyphs() tl = self.canvas.get_top_left_world() br = self.canvas.get_bottom_right_world() bl = tl[0], br[1] w,h = canvas.get_wh_world() # determine all visible glyphs visible_glyphs = [] for g in all_glyphs: if g.is_origin_inside_rect(bl, w, h): visible_glyphs.append(g) # determine maxx last_width = 0 if visible_glyphs: last_width = visible_glyphs[0].get_bounds()[0] maxx = visible_glyphs[0].get_position()[0] + last_width for g in visible_glyphs: x = g.get_position()[0] + g.get_bounds()[0] if x > maxx: maxx = x pw = DeVIDECanvasGlyph._pWidth x = maxx + 2.0 * pw else: # default position is the centre x = tl[0] + w / 2.0 # default y is 10% from the bottom y = br[1] + 0.1 * h if x > br[0]- 0.1 * w: # glyph would end up to the right of the visible viewport canvas.pan_canvas_world(w / 4.0, 0) return x,y def _handlerPaste(self, event, position): """If position is None, a paste position will be automatically determined. """ if self._copyBuffer: if position is None: position = self._determine_paste_pos() self._realise_network( # when we paste, we want the thing to reposition! self._copyBuffer[0], self._copyBuffer[1], self._copyBuffer[2], position, True) def _handlerHelpShowHelp(self, event): self._interface.showHelp() def _handlerCopySelected(self, event): if self._selected_glyphs.getSelectedGlyphs(): self._copyBuffer = self._serialise_network( self._selected_glyphs.getSelectedGlyphs()) def _handlerCutSelected(self, event): if self._selected_glyphs.getSelectedGlyphs(): self._copyBuffer = self._serialise_network( self._selected_glyphs.getSelectedGlyphs()) self._delete_selected_glyphs() def hide(self): self._interface._main_frame.Show(False) def _draw_preview_line(self, src, dst): """Draw / update a preview line from 3-D world position src to dst. """ if self._preview_line is None: self._preview_line = DeVIDECanvasSimpleLine(self.canvas, src, dst) self.canvas.add_object(self._preview_line) else: self._preview_line.src = src self._preview_line.dst = dst self._preview_line.update_geometry() self.canvas.redraw() # this shouldn't be here... def _kill_preview_line(self): if not self._preview_line is None: self.canvas.remove_object(self._preview_line) self._preview_line.close() self._preview_line = None def _draw_rubberband(self, cur_pos): if self._rbb_box is None: self._rbb_box = DeVIDECanvasRBBox(self.canvas, cur_pos, (0.1,0.1)) self.canvas.add_object(self._rbb_box) else: # just update the width and the height! # (these can be negative) w = cur_pos[0] - self._rbb_box.corner_bl[0] h = cur_pos[1] - self._rbb_box.corner_bl[1] self._rbb_box.width, self._rbb_box.height = w,h self._rbb_box.update_geometry() def _end_rubberbanding(self): """See stopRubberBanding: we need some more data! actually we don't: we have self.canvas too (with an event.wx_event) """ if not self._rbb_box is None: # store coords of rubber-band box c_bl = self._rbb_box.corner_bl w = self._rbb_box.width h = self._rbb_box.height # remove it from the canvas self.canvas.remove_object(self._rbb_box) self._rbb_box.close() self._rbb_box = None # now determine which glyphs were inside all_glyphs = self._get_all_glyphs() glyphs_in_rb = [] for g in all_glyphs: if g.is_inside_rect(c_bl, w, h): glyphs_in_rb.append(g) wxe = self.canvas.event.wx_event if not wxe.ControlDown() and not wxe.ShiftDown(): self._selected_glyphs.removeAllGlyphs() for g in glyphs_in_rb: self._selected_glyphs.addGlyph(g) def _disconnect(self, glyph, input_idx): """Disconnect input_idx'th input of glyph, also remove line from canvas. """ try: # first disconnect the actual modules mm = self._devide_app.get_module_manager() mm.disconnect_modules(glyph.module_instance, input_idx) except Exception, e: self._devide_app.log_error_with_exception( 'Could not disconnect modules (removing link ' 'from canvas anyway): %s' \ % (str(e))) # we did our best, the module didn't want to comply # we're going to nuke it anyway deadLine = glyph.inputLines[input_idx] if deadLine: # remove the line from the destination module input lines glyph.inputLines[input_idx] = None # and for the source module output lines outlines = deadLine.fromGlyph.outputLines[ deadLine.fromOutputIdx] del outlines[outlines.index(deadLine)] # also update geometry on both glyphs glyph.update_geometry() deadLine.fromGlyph.update_geometry() # and from the canvas self.canvas.remove_object(deadLine) deadLine.close() def _observer_canvas_left_down(self, canvas): """If user left-clicks on canvas and there's a selection, the selection should be canceled. However, if control or shift is being pressed, it could mean the user is planning to extend a selection with for example a rubber-band drag. """ wxe = canvas.event.wx_event if not wxe.ControlDown() and not wxe.ShiftDown() and \ len(self._selected_glyphs.getSelectedGlyphs()) > 0: self._selected_glyphs.removeAllGlyphs() self.canvas.update_all_geometry() self.canvas.redraw() def _observer_canvas_right_down(self, canvas): pmenu = wx.Menu('Canvas Menu') # fill it out with edit (copy, cut, paste, delete) commands self._append_edit_commands(pmenu, canvas._rwi, (canvas.event.world_pos[0:2])) pmenu.AppendSeparator() self._append_network_commands(pmenu, canvas._rwi) self.canvas._rwi.PopupMenu(pmenu, wx.Point(canvas.event.pos[0], canvas.event.pos[1])) def _observer_canvas_left_up(self, canvas): dprint("_observer_canvas_left_up::") # whatever the case may be, stop rubber banding. if self._rbb_box: self._end_rubberbanding() # this might mean double redraws, cache it? self.canvas.redraw() # any dragged objects? if canvas.getDraggedObject() and \ canvas.getDraggedObject().draggedPort and \ canvas.getDraggedObject().draggedPort != (-1,-1): if canvas.getDraggedObject().draggedPort[0] == 0: # the user was dragging an input port and dropped it # on the canvas, so she probably wants us to disconnect input_idx = canvas.getDraggedObject().draggedPort[1] self._disconnect(canvas.getDraggedObject(), input_idx) # we were dragging a port, so there was a preview line, # which we now can discard self._kill_preview_line() self.canvas.redraw() def _observer_canvas_drag(self, canvas): if canvas.event.left_button: self._draw_rubberband(canvas.event.world_pos) canvas.redraw() def _checkAndConnect(self, draggedObject, draggedPort, droppedObject, droppedInputPort): """Check whether the proposed connection can be made and make it. Also takes care of putting a new connection line on the canvas, and redrawing. """ if droppedObject.inputLines[droppedInputPort]: # the user dropped us on a connected input, we can just bail return if draggedPort[0] == 1: # this is a good old "I'm connecting an output to an input" self._connect(draggedObject, draggedPort[1], droppedObject, droppedInputPort) self.canvas.redraw() elif draggedObject.inputLines[draggedPort[1]]: # this means the user was dragging a connected input port and has # now dropped it on another input port... (we've already eliminated # the case of a drop on an occupied input port, and thus also # a drop on the dragged port) oldLine = draggedObject.inputLines[draggedPort[1]] fromGlyph = oldLine.fromGlyph fromOutputIdx = oldLine.fromOutputIdx toGlyph = oldLine.toGlyph toInputIdx = oldLine.toInputIdx # delete the old one self._disconnect(toGlyph, toInputIdx) # connect up the new one self._connect(fromGlyph, fromOutputIdx, droppedObject, droppedInputPort) self.canvas.redraw() def _observer_network_manager_ens(self, network_manager): """Autosave file, only if we have a _current_filename """ if self._current_filename is None: return all_glyphs = self.canvas.getObjectsOfClass( DeVIDECanvasGlyph) if all_glyphs: # create new filename fn = self._current_filename f, e = os.path.splitext(fn) new_fn = '%s_autosave%s' % (f, e) # auto-save the network to that file self._save_network(all_glyphs, new_fn) msg1 = 'Auto-saved %s' % (new_fn,) # set message on statusbar self._interface.set_status_message( '%s - %s' % (msg1,time.ctime(time.time()))) # and also in log window self._interface.log_info(msg1) def clear_all_glyphs_from_canvas(self): allGlyphs = self.canvas.getObjectsOfClass(DeVIDECanvasGlyph) mm = self._devide_app.get_module_manager() # we take care of the "difficult" modules first, so sort module # types from high to low maxConsumerType = max(mm.consumerTypeTable.values()) # go through consumerTypes from high to low, building up a list # with glyph in the order that we should destroy them # we should probably move this logic to the ModuleManager as a # method getModuleDeletionOrder() or somesuch glyphDeletionSchedule = [] for consumerType in range(maxConsumerType, -1, -1): for glyph in allGlyphs: moduleClassName = glyph.module_instance.__class__.__name__ if moduleClassName in mm.consumerTypeTable: currentConsumerType = mm.consumerTypeTable[ moduleClassName] else: # default filter currentConsumerType = 1 if currentConsumerType == consumerType: glyphDeletionSchedule.append(glyph) # now actually delete the glyphs in the correct order for glyph in glyphDeletionSchedule: self._delete_module(glyph) # only here! self.canvas.redraw() def _create_line(self, fromObject, fromOutputIdx, toObject, toInputIdx): l1 = DeVIDECanvasLine(self.canvas, fromObject, fromOutputIdx, toObject, toInputIdx) dprint("_create_line:: calling canvas.add_object") self.canvas.add_object(l1) # also record the line in the glyphs toObject.inputLines[toInputIdx] = l1 fromObject.outputLines[fromOutputIdx].append(l1) # REROUTE THIS LINE self._route_line(l1) def _connect(self, fromObject, fromOutputIdx, toObject, toInputIdx): success = True try: # connect the actual modules mm = self._devide_app.get_module_manager() mm.connect_modules(fromObject.module_instance, fromOutputIdx, toObject.module_instance, toInputIdx) # if that worked, we can make a linypoo self._create_line(fromObject, fromOutputIdx, toObject, toInputIdx) # have to call update_geometry (the glyphs have new # colours!) fromObject.update_geometry() toObject.update_geometry() except Exception, e: success = False self._devide_app.log_error_with_exception( 'Could not connect modules: %s' % (str(e))) return success def _delete_selected_glyphs(self): """Delete all currently selected glyphs. """ # we have to make a deep copy, as we're going to be deleting stuff # from this list deadGlyphs = [glyph for glyph in \ self._selected_glyphs.getSelectedGlyphs()] for glyph in deadGlyphs: # delete the glyph, do not refresh the canvas self._delete_module(glyph, False) # finally we can let the canvas redraw self.canvas.redraw() def _realise_network(self, pmsDict, connectionList, glyphPosDict, origin=(0,0), reposition=False): """Given a pmsDict, connectionList and glyphPosDict, recreate the network described by those structures. The origin of the glyphs will be set. If reposition is True, the uppermost and leftmost coordinates of all glyphs in glyphPosDict is subtracted from all stored glyph positions before adding the origin. """ # get the network_manager to realise the network nm = self._devide_app.network_manager newModulesDict, newConnections = nm.realise_network( pmsDict, connectionList) # newModulesDict and newConnections contain the modules and # connections which were _actually_ realised... let's draw # glyphs! if reposition: coords = glyphPosDict.values() minX = min([coord[0] for coord in coords]) minY = min([coord[1] for coord in coords]) reposCoords = [minX, minY] else: reposCoords = [0, 0] # store the new glyphs in a dictionary keyed on OLD pickled # instance_name so that we can connect them up in the next step mm = self._devide_app.get_module_manager() newGlyphDict = {} for newModulePickledName in newModulesDict.keys(): position = glyphPosDict[newModulePickledName] module_instance = newModulesDict[newModulePickledName] gLabel = [module_instance.__class__.__name__] instname = mm.get_instance_name(module_instance) if not instname.startswith('dvm'): gLabel.append(instname) newGlyph = self.create_glyph( position[0] - reposCoords[0] + origin[0], position[1] - reposCoords[1] + origin[1], gLabel, module_instance) newGlyphDict[newModulePickledName] = newGlyph # now make lines for all the existing connections # note that we use "newConnections" and not connectionList for connection in newConnections: sGlyph = newGlyphDict[connection.source_instance_name] tGlyph = newGlyphDict[connection.target_instance_name] self._create_line(sGlyph, connection.output_idx, tGlyph, connection.input_idx) # finally we can let the canvas redraw self.canvas.update_all_geometry() self.canvas.redraw() def _layout_network_sucky(self): # I've done it this way so that I can easily paste this method # into the main DeVIDE introspection window. #from internal.wxPyCanvas import wxpc iface = self._interface #iface = devide_app.get_interface() canvas = self.canvas ge = iface._graph_editor mm = self._devide_app.get_module_manager() #mm = devide_app.get_module_manager() all_glyphs = self.canvas.getObjectsOfClass( DeVIDECanvasGlyph) num_glyphs = len(all_glyphs) # we can only do this if we have more than one glyph to # move around. if num_glyphs <= 1: return (pmsDict, connection_list, glyphPosDict) = \ ge._serialise_network(all_glyphs) # first convert all glyph positions to points and connections # to polylines. polynet = vtk.vtkPolyData() points = vtk.vtkPoints() points.Allocate(num_glyphs, 10) lines = vtk.vtkCellArray() lines.Allocate(len(connection_list), 10) # for each glyph, we store in a dict its pointid in the # polydata name2ptid = {} ptid2glyph = {} for glyph in all_glyphs: pos = glyph.get_position() new_pos = pos + (0.0,) ptid = points.InsertNextPoint(new_pos) instance_name = mm.get_instance_name(glyph.module_instance) name2ptid[instance_name] = ptid ptid2glyph[ptid] = glyph condone = {} # we use this dict to add each connection once for connection in connection_list: prod_ptid = name2ptid[connection.source_instance_name] cons_ptid = name2ptid[connection.target_instance_name] # we keep this for now, we want the number of connections # between two modules to play a role in the layout. #if (prod_ptid, cons_ptid) in condone: # continue #else: # condone[(prod_ptid, cons_ptid)] = 1 v = vtk.vtkIdList() v.InsertNextId(prod_ptid) v.InsertNextId(cons_ptid) lines.InsertNextCell(v) # we can also add an extra connection from each glyph to EVERY # other glyph to keep things more balanced... (SIGH) for iglyph in all_glyphs: iptid = name2ptid[mm.get_instance_name(iglyph.module_instance)] for jglyph in all_glyphs: if iglyph is not jglyph: jptid = name2ptid[mm.get_instance_name(jglyph.module_instance)] v = vtk.vtkIdList() v.InsertNextId(iptid) v.InsertNextId(jptid) lines.InsertNextCell(v) polynet.SetPoints(points) polynet.SetLines(lines) lf = vtk.vtkGraphLayoutFilter() lf.SetThreeDimensionalLayout(0) lf.SetAutomaticBoundsComputation(0) minx, miny = canvas.GetViewStart()[0] + 50, canvas.GetViewStart()[1] + 50 maxx, maxy = canvas.GetClientSize()[0] + minx - 100, canvas.GetClientSize()[1] + miny - 100 lf.SetGraphBounds(minx, maxx, miny, maxy, 0.0, 0.0) # i've tried a number of things, they all suck. lf.SetCoolDownRate(1000) # default 10 lf.SetMaxNumberOfIterations(10) # default 50 lf.SetInput(polynet) lf.Update() new_pts = lf.GetOutput() for ptid, glyph in ptid2glyph.items(): new_pos = new_pts.GetPoint(ptid) glyph.setPosition(new_pos[0:2]) ge._route_all_lines() def _load_and_realise_network(self, filename, position=(0,0), reposition=False): """Attempt to load (i.e. unpickle) a DVN network file and recreate this network on the canvas. @param position: start position of new network in world coordinates. """ try: ln = self._devide_app.network_manager.load_network pmsDict, connectionList, glyphPosDict = ln(filename) self._realise_network(pmsDict, connectionList, glyphPosDict, position, reposition) except Exception, e: self._devide_app.log_error_with_exception(str(e)) def _load_network_into_copy_buffer(self, filename): """Attempt to load (i.e. unpickle) a DVN network and bind the tuple to self._copyBuffer. When the user pastes, the network will be recreated. DANG! """ try: ln = self._devide_app.network_manager.load_network pmsDict, connectionList, glyphPosDict = ln(filename) self._copyBuffer = (pmsDict, connectionList, glyphPosDict) except Exception, e: self._devide_app.log_error_with_exception(str(e)) def _save_network_DEPRECATED(self, glyphs, filename): (pmsDict, connectionList, glyphPosDict) = \ self._serialise_network(glyphs) # change the serialised module_instances to a pickled stream headerAndData = (('DVN', 1, 0, 0), \ (pmsDict, connectionList, glyphPosDict)) stream = cPickle.dumps(headerAndData, True) f = None try: f = open(filename, 'wb') f.write(stream) except Exception, e: self._devide_app.log_error_with_exception( 'Could not write network to %s: %s' % (filename, str(e))) if f: f.close() def _save_network(self, glyphs, filename, export=False): (pms_dict, connection_list, glyph_pos_dict) = \ self._serialise_network(glyphs) nm = self._devide_app.network_manager try: nm.save_network(pms_dict, connection_list, glyph_pos_dict, filename, export) except Exception, e: self._devide_app.log_error_with_exception( 'Could not write network to %s: %s' % (filename, str(e))) def _exportNetworkAsDOT(self, glyphs, filename): (pmsDict, connectionList, glyphPosDict) = \ self._serialise_network(glyphs) # first work through the module instances dotModuleDefLines = [] for instance_name, pickledModule in pmsDict.items(): configKeys = [i for i in dir(pickledModule.module_config) if not i.startswith('__')] configList = [] for configKey in configKeys: cValStr = str(getattr(pickledModule.module_config, configKey)) if len(cValStr) > 80: cValStr = 'Compacted' # just replace all \'s with /'s... else we have to futz # with raw strings all the way through! configList.append('%s : %s' % (configKey, cValStr.replace('\\', '/'))) configString = '\\n'.join(configList) dotModuleDefLines.append( '%s [shape=box, label="%s %s\\n%s"];\n' % \ (instance_name, pickledModule.module_name, instance_name, configString)) # then the connections # connectionList is a list of pickledConnections connectionLines = [] mm = self._devide_app.get_module_manager() for connection in connectionList: mi = mm.get_instance(connection.source_instance_name) outputName = '' if mi: outputName = mi.get_output_descriptions()[connection.output_idx] connectionLines.append('%s -> %s [label="%s"];\n' % \ (connection.source_instance_name, connection.target_instance_name, outputName )) f = None try: f = open(filename, 'w') f.write('/* GraphViz DOT file generated by DeVIDE */\n') f.write('/* Example: dot -Tps filename.dot -o filename.ps */\n') f.write('digraph DeVIDE_Network {\n') f.write('ratio=auto;\n'); # a4 is 8.something by 11.something f.write('size="7,10";\n'); f.writelines(dotModuleDefLines) f.writelines(connectionLines) f.write('}') except Exception, e: self._devide_app.log_error_with_exception( 'Could not write network to %s: %s' % (filename, str(e))) if f: f.close() def _serialise_network(self, glyphs): """Given a list of glyphs, return a tuple containing pmsDict, connectionList and glyphPosDict. This can be used to reconstruct the whole network from scratch and is used for saving and cutting/copying. glyphPosDict is a dictionary mapping from instance_name to glyph position. pmsDict maps from instance_name to PickledModuleState, an object with attributes (module_config, module_name, instance_name) connectionList is a list of pickledConnection, each containing (producer_instance_name, output_idx, consumer_instance_name, input_idx) """ module_instances = [glyph.module_instance for glyph in glyphs] mm = self._devide_app.get_module_manager() # let the ModuleManager serialise what it can pmsDict, connectionList = mm.serialise_module_instances( module_instances) savedInstanceNames = [pms.instance_name for pms in pmsDict.values()] # now we also get to store the coordinates of the glyphs which # have been saved (keyed on instance_name) savedGlyphs = [glyph for glyph in glyphs if mm.get_instance_name(glyph.module_instance)\ in savedInstanceNames] glyphPosDict = {} for savedGlyph in savedGlyphs: instance_name = mm.get_instance_name(savedGlyph.module_instance) glyphPosDict[instance_name] = savedGlyph.get_position() return (pmsDict, connectionList, glyphPosDict) def update_port_info_statusbar(self, glyph, port_inout, port_idx): """This is only called if port_inout is >= 0, i.e. there is valid information concerning a glyph, port side and port index under the mouse at the moment. Called by _observer_glyph_motion(). """ msg = '' canvas = self.canvas from_port = False draggedObject = canvas.getDraggedObject() if draggedObject and draggedObject.draggedPort and \ draggedObject.draggedPort != (-1, -1): if draggedObject.draggedPort[0] == 0: pstr = draggedObject.module_instance.get_input_descriptions()[ draggedObject.draggedPort[1]] else: pstr = draggedObject.module_instance.get_output_descriptions()[ draggedObject.draggedPort[1]] from_descr = '|%s|-[%s]' % (draggedObject.getLabel(), pstr) from_port = True # see if dragged port is the same as the port currently # under the mouse same_port = draggedObject == glyph and \ draggedObject.draggedPort[0] == port_inout and \ draggedObject.draggedPort[1] == port_idx if port_inout == 0: pstr = glyph.module_instance.get_input_descriptions()[ port_idx] else: pstr = glyph.module_instance.get_output_descriptions()[ port_idx] to_descr = '|%s|-[%s]' % (glyph.getLabel(), pstr) # if we have a dragged port (i.e. a source) and a port # currently under the mouse which is NOT the same port, show # the connection that the user would make if the mouse would # now be released. if from_port and not same_port: msg = '%s ===>> %s' % (from_descr, to_descr) # otherwise, just show the port under the mouse at the moment. else: msg = to_descr self._interface._main_frame.GetStatusBar().SetStatusText(msg) def _fileExitCallback(self, event): # call the interface quit handler (we're its child) self._interface.quit() def _fileNewCallback(self, event): self.clear_all_glyphs_from_canvas() self.set_current_filename(None) def _fileOpenCallback(self, event): filename = wx.FileSelector( "Choose DeVIDE network to load", self._last_fileselector_dir, "", "dvn", "DeVIDE networks (*.dvn)|*.dvn|All files (*.*)|*.*", wx.OPEN) if filename: # save the directory part of whatever was selected for # future use. self._last_fileselector_dir = \ os.path.dirname(filename) self.clear_all_glyphs_from_canvas() self._load_and_realise_network(filename) # make sure that the newly realised network is nicely in # view self.canvas.reset_view() self.set_current_filename(filename) def _helper_file_save(self, always_ask=True, export=False): """Save current network to file. If always_ask is True, will popup a file selector dialogue. If always_ask is False, will only popup a file selector dialogue if there is no current filename set. If export is True, it will invoke the relative path substitution mode during saving, i.e. all filename paths that are below the network directory will be stored in relative form. This will not change the current filename, and will always ask where to export to. """ # make a list of all glyphs allGlyphs = self.canvas.getObjectsOfClass( DeVIDECanvasGlyph) if allGlyphs: if always_ask or export or self._current_filename is None: if export: msg = "Choose filename for EXPORTED DeVIDE network" else: msg = "Choose filename for DeVIDE network" filename = wx.FileSelector(msg, self._last_fileselector_dir, "", "dvn", "DeVIDE networks (*.dvn)|*.dvn|All files (*.*)|*.*", wx.SAVE) else: filename = self._current_filename if filename: # save directory for future use self._last_fileselector_dir = \ os.path.dirname(filename) # if the user has NOT specified any fileextension, we # add .dvn. (on Win this gets added by the # FileSelector automatically, on Linux it doesn't) if os.path.splitext(filename)[1] == '': filename = '%s.dvn' % (filename,) if export: self._save_network( allGlyphs, filename, export=True) msg1 = 'EXPORTED to %s' % (filename,) else: self.set_current_filename(filename) self._save_network(allGlyphs, filename) msg1 = 'Saved %s' % (filename,) # set message on statusbar self._interface.set_status_message( '%s - %s' % (msg1,time.ctime(time.time()))) # and also in log window self._interface.log_info(msg1) def _fileSaveCallback(self, event): self._helper_file_save(always_ask=False) def _handler_file_save_as(self, event): self._helper_file_save(always_ask=True) def _handler_file_export(self, event): self._helper_file_save(always_ask=True, export=True) def _get_all_glyphs(self): """Return list with all glyphs on canvas. """ ag = self.canvas.getObjectsOfClass( DeVIDECanvasGlyph) return ag def _observer_glyph_dragging(self, glyph): canvas = self.canvas # this clause will execute once at the beginning of a drag... if not glyph.draggedPort: # we're dragging, but we don't know if we're dragging a port yet port = glyph.get_port_containing_mouse() dprint("_observer_glyph_dragging:: port", port) if port: # glyph.draggedPort = port else: # this indicates that the glyph is being dragged, but that # we don't have to check for a port during this drag glyph.draggedPort = (-1, -1) # when we get here, glyph.draggedPort CAN't BE None if glyph.draggedPort == (-1, -1): # this means that there's no port involved, so the glyph itself, # or the current selection of glyphs, gets dragged if glyph in self._selected_glyphs.getSelectedGlyphs(): # move the whole selection (MAN THIS IS CLEAN) # err, kick yerself in the nads: you CAN'T use glyph # as iteration variable, it'll overwrite the current glyph for sglyph in self._selected_glyphs.getSelectedGlyphs(): canvas.drag_object(sglyph, canvas.get_motion_vector_world(0.0)) # we're busy dragging glyphs, do a QUICK reroute # of all lines connected to this glyph. quick # rerouting ignores all other glyphs self._route_all_glyph_lines_fast(sglyph) else: # or just the glyph under the mouse # this clause should never happen, as the dragged glyph # always has the selection. canvas.drag_object(glyph, canvas.get_motion_vector_world(0.0)) self._route_all_glyph_lines_fast(glyph) # finished glyph drag event handling, have to redraw. canvas.redraw() else: if glyph.draggedPort[0] == 1: # the user is attempting a new connection starting with # an output port cop = glyph.get_centre_of_port(glyph.draggedPort[0], glyph.draggedPort[1]) self._draw_preview_line(cop, canvas.event.world_pos) elif glyph.inputLines and glyph.inputLines[glyph.draggedPort[1]]: # the user is attempting to relocate or disconnect an input inputLine = glyph.inputLines[glyph.draggedPort[1]] cop = inputLine.fromGlyph.get_centre_of_port( 1, inputLine.fromOutputIdx) self._draw_preview_line(cop, canvas.event.world_pos) # if not canvas.getDraggedObject(): # # this means that this drag has JUST been cancelled # if glyph.draggedPort == (-1, -1): # # and we were busy dragging a glyph around, so we probably # # want to reroute all lines! # # # reroute all lines # allLines = self._interface._main_frame.canvas.\ # getObjectsOfClass(wxpc.coLine) # # for line in allLines: # self._route_line(line) # # # # switch off the draggedPort # glyph.draggedPort = None # # redraw everything # canvas.redraw() def _observer_glyph_motion(self, glyph): inout, port_idx = glyph.get_port_containing_mouse() if inout >= 0: self.update_port_info_statusbar(glyph, inout, port_idx) def _observer_glyph_right_button_down(self, glyph): module = glyph.module_instance pmenu = wx.Menu(glyph.getLabel()) vc_id = wx.NewId() pmenu.AppendItem(wx.MenuItem(pmenu, vc_id, "View-Configure")) wx.EVT_MENU(self.canvas._rwi, vc_id, lambda e: self._view_conf_module(module)) help_id = wx.NewId() pmenu.AppendItem(wx.MenuItem( pmenu, help_id, "Help on Module")) wx.EVT_MENU(self.canvas._rwi, help_id, lambda e: self.show_module_help_from_glyph(glyph)) reload_id = wx.NewId() pmenu.AppendItem(wx.MenuItem(pmenu, reload_id, 'Reload Module')) wx.EVT_MENU(self.canvas._rwi, reload_id, lambda e: self._handler_reload_module(module, glyph)) del_id = wx.NewId() pmenu.AppendItem(wx.MenuItem(pmenu, del_id, 'Delete Module')) wx.EVT_MENU(self.canvas._rwi, del_id, lambda e: self._delete_module(glyph)) rename_moduleId = wx.NewId() pmenu.AppendItem(wx.MenuItem(pmenu, rename_moduleId, 'Rename Module')) wx.EVT_MENU(self.canvas._rwi, rename_moduleId, lambda e: self._handlerRenameModule(module,glyph)) inject_module_id = wx.NewId() pmenu.AppendItem(wx.MenuItem(pmenu, inject_module_id, 'Module -> Python shell')) wx.EVT_MENU(self.canvas._rwi, inject_module_id, lambda e: self._handler_inject_module(module)) pmenu.AppendSeparator() self._append_edit_commands(pmenu, self.canvas._rwi, self.canvas.event.world_pos) pmenu.AppendSeparator() self._append_network_commands( pmenu, self.canvas._rwi) # popup that menu! self.canvas._rwi.PopupMenu(pmenu, wx.Point(self.canvas.event.pos[0], self.canvas.event.pos[1])) def _observer_glyph_left_button_down(self, glyph): module = glyph.module_instance if self.canvas.event.wx_event.ControlDown() or \ self.canvas.event.wx_event.ShiftDown(): # with control or shift you can add or remove that glyph if glyph.selected: self._selected_glyphs.removeGlyph(glyph) else: self._selected_glyphs.addGlyph(glyph) self.canvas.redraw() else: # if the user already has a selection of which this is a part, # we're not going to muck around with that. if not glyph.selected: self._selected_glyphs.selectGlyph(glyph) self.canvas.redraw() def _observer_glyph_left_button_up(self, glyph): dprint("_observer_glyph_left_button_up::") if self.canvas.getDraggedObject(): dprint("_observer_glyph_left_button_up:: draggedObject, " + "draggedPort", self.canvas.getDraggedObject(), self.canvas.getDraggedObject().draggedPort) # whatever the case may be, stop rubber banding. if self._rbb_box: self._end_rubberbanding() # this might mean double redraws, cache it? self.canvas.redraw() canvas = self.canvas # when we receive the ButtonUp that ends the drag event, # canvas.getDraggedObject is still set! - it will be unset # right after (by the canvas) and then the final drag event # will be triggered if canvas.getDraggedObject() and \ canvas.getDraggedObject().draggedPort and \ canvas.getDraggedObject().draggedPort != (-1,-1): # this means the user was dragging a port... so we're # interested # first get rid of the preview line... self._kill_preview_line() # and redraw the canvas so it really disappears # (this is also necessary when the handler will do nothing # otherwise, for example if the user drops us above a # glyph) self.canvas.redraw() pcm = glyph.get_port_containing_mouse() dprint("_observer_glyph_left_button_up:: pcm",pcm) if pcm == (-1,-1): # the user was dragging an input or output port and # dropped us inside a glyph... try to connect us to # the first unconnected input port on 'glyph' try: first_available_port_idx = glyph.inputLines.index(None) except ValueError: # no available port ############################# if canvas.getDraggedObject().draggedPort[0] == 0: # if the user was dragging an input port, that # means we disconnect input_idx = canvas.getDraggedObject().draggedPort[1] self._disconnect(canvas.getDraggedObject(), input_idx) self.canvas.redraw() else: # the user was dragging an output port and # dropped us on a glyph with no available # inputs: do nothing. pass else: # there IS an input port available! # checkAndConnect knows what to do if we were # dragging an output port (connect it to this # glyph) or an input port (first disconnect it # from its existing consumer module, then # reconnect to this glyph) self._checkAndConnect( canvas.getDraggedObject(), canvas.getDraggedObject().draggedPort, glyph, first_available_port_idx) else: # this means the drag is ended above an input port! if pcm[0] == 0: # ended above an INPUT port # checkandconnect will route lines and redraw if # required self._checkAndConnect( canvas.getDraggedObject(), canvas.getDraggedObject().draggedPort, glyph, pcm[1]) else: # ended above an output port... we can't do anything # (I think) pass if canvas.getDraggedObject() and \ canvas.getDraggedObject().draggedPort == (-1,-1): dprint( "_observer_glyph_left_button_up:: end of glyph move") # this is the end of a glyph move: there is still a # draggedObject, but the left mouse button is up. # the new VTK canvas event system only switches off draggy # things AFTER the left mouse button up event all_lines = \ self.canvas.getObjectsOfClass(DeVIDECanvasLine) for line in all_lines: dprint("+-- routing line", line) self._route_line(line) # the old code also switch off the draggedPort here... self.canvas.redraw() def _observer_glyph_left_button_dclick(self, glyph): module = glyph.module_instance # double clicking on a module opens the View/Config. self._view_conf_module(module) def _cohenSutherLandClip(self, x0, y0, x1, y1, xmin, ymin, xmax, ymax): """Perform Cohen Sutherland line clipping given line defined by endpoints (x0, y0) and (x1, y1) and window (xmin, ymin, xmax, ymax). See for e.g.: http://www.cs.fit.edu/~wds/classes/graphics/Clip/clip/clip.html @returns: a list of point coordinates where the line is clipped by the window. @todo: should be moved out into utility module. """ def outCode(x, y, xmin, ymin, xmax, ymax): """Determine Cohen-Sutherland bitcode for a point (x,y) with respect to a window (xmin, ymin, xmax, ymax). point left of window (x < xmin): bit 1 point right of window (x > xmax): bit 2 point below window (y < ymin): bit 3 point above window (y > ymax): bit 4 """ a,b,c,d = (0,0,0,0) if y > ymax: a = 1 if y < ymin: b = 1 if x > xmax: c = 1 elif x < xmin: d = 1 return (a << 3) | (b << 2) | (c << 1) | d # determine bitcodes / outcodes for line endpoints oc0 = outCode(x0, y0, xmin, ymin, xmax, ymax) oc1 = outCode(x1, y1, xmin, ymin, xmax, ymax) clipped = False # true when the whole line has been clipped accepted = False # trivial accept (line is inside) while not clipped: if oc0 == 0 and oc1 == 0: # the line is completely inside clipped = True accepted = True elif oc0 & oc1 != 0: # trivial reject, the line is nowhere near clipped = True else: dx = float(x1 - x0) dy = float(y1 - y0) if dx != 0.0: m = dy / dx else: # if dx == 0.0, we won't need m in anycase (m is only # needed to calc intersection with a vertical edge) m = 0.0 if dy != 0.0: mi = dx / dy else: # same logic here mi = 0.0 # this means there COULD be a clip # pick "outside" point oc = [oc1, oc0][bool(oc0)] if oc & 8: # y is above (numerically) x = x0 + mi * (ymax - y0) y = ymax elif oc & 4: # y is below (numerically) x = x0 + mi * (ymin - y0) y = ymin elif oc & 2: # x is right x = xmax y = y0 + m * (xmax - x0) else: x = xmin y = y0 + m * (xmin - x0) if oc == oc0: # we're clipping off the line start x0 = x y0 = y oc0 = outCode(x0, y0, xmin, ymin, xmax, ymax) else: # we're clipping off the line end x1 = x y1 = y oc1 = outCode(x1, y1, xmin, ymin, xmax, ymax) clipPoints = [] if accepted: if x0 == xmin or x0 == xmax or y0 == ymin or y0 == ymax: clipPoints.append((x0, y0)) if x1 == xmin or x1 == xmax or y1 == ymin or y1 == ymax: clipPoints.append((x1, y1)) return clipPoints def _route_all_lines(self): """Call _route_line on each and every line on the canvas. Refresh canvas afterwards. """ # THEN reroute all lines allLines = self.canvas.getObjectsOfClass(DeVIDECanvasLine) for line in allLines: self._route_line(line) # redraw all self.canvas.redraw() def _route_all_glyph_lines_fast(self, glyph): """Fast route all lines going into and originating from glyph. This is used during glyph drags as a kind of preview. This will not request a redraw of the canvas, the calling method has to do that. @param glyph: glyph whose lines will all be fast routed. """ for l in glyph.inputLines: if l is not None: self._route_line_fast(l) for lines in glyph.outputLines: for l in lines: if l is not None: self._route_line_fast(l) def dummy(self): # dummy method: this code can be used at the end of the # previous method for debugging stippling problems. allLines = self.canvas.getObjectsOfClass(DeVIDECanvasLine) for line in allLines: should_draw = True if line in glyph.inputLines: should_draw = False else: for lines in glyph.outputLines: if line in lines: should_draw = False break if should_draw: line.set_normal() def _route_line(self, line): """Route line around all glyphs on canvas. Line is routed by inserting a number of control points to make it go around all glyphs the canvas. This is not terribly efficient: it's routing a line around ALL glyphs, instead of making use of some space partitioning scheme. However, in the worst practical case, this comes down to about 40 glyphs If you have some time on your hands, feel free to improve. @param line: DeVIDECanvasLine instance representing the line that has to be routed. """ # we have to get a list of all coGlyphs allGlyphs = self.canvas.getObjectsOfClass(DeVIDECanvasGlyph) # make sure the line is back to 4 points line.updateEndPoints() # this should be 5 for straight line drawing # at least 10 for spline drawing; also remember to change # the DrawLines -> DrawSplines in coLine as well as # coLine.updateEndPoints() (at the moment they use port height # to get that bit out of the glyph) overshoot = DeVIDECanvasLine.routingOvershoot # sometimes, for instance for spline routing, we need something # extra... for straight line drawing, this should be = overshoot #moreOvershoot = 2 * overshoot moreOvershoot = overshoot successfulInsert = True numInserts = 0 while successfulInsert and numInserts < 30: (x0, y0), (x1, y1) = line.getThirdLastSecondLast() clips = {} for glyph in allGlyphs: (xmin, ymin), (xmax, ymax) = glyph.get_bottom_left_top_right() clipPoints = self._cohenSutherLandClip(x0, y0, x1, y1, xmin, ymin, xmax, ymax) if clipPoints: clips[glyph] = clipPoints # now look for the clip point closest to the start of the current # line segment! currentSd = sys.maxint nearestGlyph = None nearestClipPoint = None for clip in clips.items(): for clipPoint in clip[1]: xdif = clipPoint[0] - x0 ydif = clipPoint[1] - y0 sd = xdif * xdif + ydif * ydif if sd < currentSd: currentSd = sd nearestGlyph = clip[0] nearestClipPoint = clipPoint successfulInsert = False # we have the nearest clip point if nearestGlyph: (xmin, ymin), (xmax, ymax) = \ nearestGlyph.get_bottom_left_top_right() # does it clip the horizontal bar if nearestClipPoint[1] == ymin or nearestClipPoint[1] == ymax: midPointX = xmin + (xmax - xmin) / 2.0 if x1 < midPointX: newX = xmin - moreOvershoot else: newX = xmax + moreOvershoot newY = nearestClipPoint[1] if newY == ymin: newY -= overshoot else: newY += overshoot # if there are clips on the new segment, add an extra # node to avoid those clips! for glyph in allGlyphs: (xmin2, ymin2), (xmax2, ymax2) = \ glyph.get_bottom_left_top_right() cp2 = self._cohenSutherLandClip(x0,y0,newX,newY, xmin2, ymin2, xmax2, ymax2) if cp2: break if cp2: line.insertRoutingPoint(nearestClipPoint[0], newY) numInserts += 1 successfulInsert = line.insertRoutingPoint(newX, newY) numInserts += 1 # or does it clip the vertical bar elif nearestClipPoint[0] == xmin or \ nearestClipPoint[0] == xmax: midPointY = ymin + (ymax - ymin) / 2.0 if y1 < midPointY: newY = ymin - moreOvershoot else: newY = ymax + moreOvershoot newX = nearestClipPoint[0] if newX == xmin: newX -= overshoot else: newX += overshoot # if there are clips on the new segment, add an extra # node to avoid those clips! for glyph in allGlyphs: (xmin2, ymin2), (xmax2, ymax2) = \ glyph.get_bottom_left_top_right() cp2 = self._cohenSutherLandClip(x0,y0,newX,newY, xmin2, ymin2, xmax2, ymax2) if cp2: break if cp2: line.insertRoutingPoint(newX, nearestClipPoint[1]) numInserts += 1 successfulInsert = line.insertRoutingPoint(newX, newY) numInserts += 1 else: print "HEEEEEEEEEEEEEEEEEEEELP!! This shouldn't happen." raise Exception line.set_normal() line.update_geometry() def _route_line_fast(self, line): """Similar to _route_line, but does not take into account any glyphs on the canvas. Simply route line from starting point to ending point. This is used for real-time updating during glyph moves. Think about changing this: keep all current routing points, only change two points that are attached to the glyph that is being dragged. """ # make sure the line is back to 4 points line.updateEndPoints() # then get it to update (applying the spline to the control # points) line.set_highlight() line.update_geometry() def _view_conf_module(self, module): mm = self._devide_app.get_module_manager() mm.view_module(module) def _delete_module(self, glyph, refreshCanvas=True): success = True try: # FIRST remove it from any selections; we have to do this # while everything is still more or less active self._selected_glyphs.removeGlyph(glyph) # first we disconnect all consumers consumerList = [] for lines in glyph.outputLines: for line in lines: consumerList.append((line.toGlyph, line.toInputIdx)) for consumer in consumerList: self._disconnect(consumer[0], consumer[1]) # then far simpler all suppliers for input_idx in range(len(glyph.inputLines)): self._disconnect(glyph, input_idx) # then get the module manager to NUKE the module itself mm = self._devide_app.get_module_manager() # this thing can also remove all links between supplying and # consuming objects (we hope) :) mm.delete_module(glyph.module_instance) except Exception, e: success = False self._devide_app.log_error_with_exception( 'Could not delete module (removing from canvas ' 'anyway): %s' % (str(e))) canvas = self.canvas # remove it from the canvas canvas.remove_object(glyph) # take care of possible lyings around glyph.close() # after all that work, we deserve a redraw if refreshCanvas: canvas.redraw() return success def set_current_filename(self, filename): """Set current filename. This will record this in an ivar, and also change the window title to reflect the current filename. """ self._current_filename = filename if filename is None: filename = 'unnamed.dvn' # this changes the window title self._interface.set_current_filename(filename) def show_module_help_from_glyph(self, glyph): module_instance = glyph.module_instance mm = self._devide_app.get_module_manager() spec = mm.get_module_spec(module_instance) self.show_module_help(spec) def show_module_help(self, module_spec): """module_spec is e.g. module:full.module.name """ if module_spec is None or not module_spec.startswith('module:'): return module_name = module_spec.split(':')[1] mm = self._devide_app.get_module_manager() try: ht = mm._available_modules[module_name].help except AttributeError: ht = 'No documentation available for this module.' mf = self._interface._main_frame mf.doc_window.SetPage(self._module_doc_to_html( module_name, ht))
Python
from main import WXInterface
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. import vtk from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import wx from module_kits.wx_kit import utils as wxutils import wx.lib.agw.aui as aui wx.aui = aui from wx.html import HtmlWindow class SimpleHTMLListBox(wx.HtmlListBox): """Simple class to emulate normal wx.ListBox (Append, Clear, GetClientData and GetString methods) with the super-powers of the wx.HtmlListBox. @author Charl P. Botha <http://cpbotha.net/> """ def __init__(self, *args, **kwargs): wx.HtmlListBox.__init__(self, *args, **kwargs) self.items = [] self.Clear() def Append(self, text, data=None, refresh=True): """Emulates wx.ListBox Append method, except for refresh bit. Set refresh to False if you're going to be appending bunches of items. When you're done, call the DoRefresh() method explicitly. """ self.items.append((text, data)) if refresh: self.SetItemCount(len(self.items)) self.Refresh() def DoRefresh(self): """To be used after adding large amounts of items with Append and refresh=False. """ self.SetItemCount(len(self.items)) self.Refresh() def Clear(self): del self.items[:] self.SetSelection(-1) self.SetItemCount(0) def GetClientData(self, n): if n >= 0 and n < len(self.items): return self.items[n][1] else: return None def GetCount(self): return len(self.items) def GetSelections(self): """Return list of selected indices just like the wx.ListBox. """ # coded up this method purely to see if we could use SimpleHTMLListBox also # for the module categories thingy sels = [] item, cookie = self.GetFirstSelected() while item != wx.NOT_FOUND: sels.append(item) # ... process item ... item = self.GetNextSelected(cookie) return sels def GetString(self, n): if n >= 0 and n < len(self.items): return self.items[n][0] else: return None def OnGetItem(self, n): try: return '<font size=-1>%s</font>' % (self.items[n][0],) except IndexError: return '' class ProgressStatusBar(wx.StatusBar): """ StatusBar with progress gauge embedded. Code adapted from wxPython demo.py | CustomStatusBar. """ def __init__(self, parent): wx.StatusBar.__init__(self, parent, -1) # This status bar has three fields self.SetFieldsCount(3) # Sets the three fields to be relative widths to each other. # status message gets the most room, then memory counter, then progress bar self.SetStatusWidths([-4, -1, -2]) self.sizeChanged = False self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_IDLE, self.OnIdle) # This will fall into field 1 (the second field) # check the Reposition method to see how this is positioned self.gauge = wx.Gauge(self, -1, 100) self.gauge.SetValue(50) # set the initial position of the checkbox self.Reposition() def OnSize(self, evt): self.Reposition() # for normal size events # Set a flag so the idle time handler will also do the repositioning. # It is done this way to get around a buglet where GetFieldRect is not # accurate during the EVT_SIZE resulting from a frame maximize. self.sizeChanged = True def OnIdle(self, evt): if self.sizeChanged: self.Reposition() # reposition the checkbox def Reposition(self): border = 3 rect = self.GetFieldRect(2) self.gauge.SetPosition((rect.x+border, rect.y+border)) self.gauge.SetSize((rect.width-border*2, rect.height-border*2)) self.sizeChanged = False class MainWXFrame(wx.Frame): """Class for building main user interface frame. All event handling and other intelligence should be elsewhere. """ def __init__(self, parent, id=-1, title="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE | wx.SUNKEN_BORDER | wx.CLIP_CHILDREN): wx.Frame.__init__(self, parent, id, title, pos, size, style) # tell FrameManager to manage this frame self._mgr = wx.aui.AuiManager() self._mgr.SetManagedWindow(self) self._make_menu() # statusbar self.statusbar = ProgressStatusBar(self) self.SetStatusBar(self.statusbar) self.SetMinSize(wx.Size(400, 300)) # could make toolbars here # now we need to add panes # on GTK, this sequence is flipped! search panel is at the # bottom, module list at the top. sp = self._create_module_search_panel() self._mgr.AddPane( sp, wx.aui.AuiPaneInfo().Name('module_search'). Caption('Module Search and Categories').Left().Position(0). MinSize(sp.GetSize()). CloseButton(False)) # a little trick I found in the PyAUI source code. This will make # sure that the pane is as low (small y) as it can be p = self._mgr.GetPane('module_search') p.dock_proportion = 0 self.module_list = self._create_module_list() self._mgr.AddPane( self.module_list, wx.aui.AuiPaneInfo().Name('module_list').Caption('Module List'). Left().CloseButton(False)) ################################################################## # setup VTK rendering pipeline for the graph editor self._rwi, self._ren = self._create_graph_canvas() self._mgr.AddPane( self._rwi, wx.aui.AuiPaneInfo().Name('graph_canvas'). Caption('Graph Canvas').CenterPane()) ################################################################## # these two also get swapped on GTK self._mgr.AddPane( self._create_documentation_window(), wx.aui.AuiPaneInfo().Name('doc_window'). Caption('Module Help').Bottom().CloseButton(False)) self._mgr.AddPane( self._create_log_window(), wx.aui.AuiPaneInfo().Name('log_window'). Caption('Log Messages').Bottom().CloseButton(False)) self._mgr.Update() # save this perspective self.perspective_default = self._mgr.SavePerspective() wx.EVT_MENU(self, self.window_default_view_id, lambda e: self._mgr.LoadPerspective( self.perspective_default) and self._mgr.Update()) def close(self): self._ren.RemoveAllViewProps() del self._ren self._rwi.GetRenderWindow().Finalize() self._rwi.SetRenderWindow(None) del self._rwi self.Destroy() def _create_documentation_window(self): self.doc_window = HtmlWindow(self, -1, size=(200,80)) fsa = wxutils.create_html_font_size_array() self.doc_window.SetFonts("", "", fsa) return self.doc_window def _create_graph_canvas(self): rwi = wxVTKRenderWindowInteractor(self, -1, size=(400,400)) # we have to call this, else moving a modal dialogue over the # graph editor will result in trails. Usually, a wxVTKRWI # refuses to render if its top-level parent is disabled. This # is to stop VTK pipeline updates whilst wx.SafeYield() is # being called. In _this_ case, the VTK pipeline is safe, so # we can disable this check. rwi.SetRenderWhenDisabled(True) ren = vtk.vtkRenderer() rwi.GetRenderWindow().AddRenderer(ren) rw = rwi.GetRenderWindow() rw.SetLineSmoothing(1) rw.SetPointSmoothing(1) # PolygonSmoothing is not really necessary for the GraphEditor # (yet), and on a GeForce 4600 Ti on Linux with driver version # 1.0-9639, you can see triangle lines bisecting quads. Not # a nice artifact, so I've disabled this for now. #rw.SetPolygonSmoothing(1) return (rwi, ren) def _create_log_window(self): tc = wx.TextCtrl( self, -1, "", size=(200, 80), style=wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL) self.message_log_text_ctrl = tc return tc def _create_module_list(self): self.module_list_box = SimpleHTMLListBox( self, -1, size=(200,200), style=wx.LB_SINGLE|wx.LB_NEEDED_SB) return self.module_list_box def _create_module_search_panel(self): search_panel = wx.Panel(self, -1) self.search = wx.SearchCtrl(search_panel, size=(200,-1), style=wx.TE_PROCESS_ENTER) self.search.ShowSearchButton(1) self.search.ShowCancelButton(1) self.module_cats_choice = wx.Choice(search_panel,-1, size=(200,-1)) tl_sizer = wx.BoxSizer(wx.VERTICAL) # option=0 so it doesn't fill vertically tl_sizer.Add(self.search, 0, wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT, 4) tl_sizer.Add(self.module_cats_choice, 0, wx.EXPAND|wx.ALL, 4) search_panel.SetAutoLayout(True) search_panel.SetSizer(tl_sizer) search_panel.GetSizer().Fit(search_panel) search_panel.GetSizer().SetSizeHints(search_panel) return search_panel def _create_progress_panel(self): progress_panel = wx.Panel(self, -1)#, size=wx.Size(100, 50)) self.progress_text = wx.StaticText(progress_panel, -1, "...") self.progress_text.SetFont( wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "")) self.progress_gauge = wx.Gauge(progress_panel, -1, 100) self.progress_gauge.SetValue(50) #self.progress_gauge.SetBackgroundColour(wx.Colour(50, 50, 204)) tl_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer = wx.BoxSizer(wx.VERTICAL) # these are in a vertical sizer, so expand will make them draw # out horizontally as well sizer.Add(self.progress_text, 0, wx.EXPAND | wx.BOTTOM, 4) sizer.Add(self.progress_gauge, 0, wx.EXPAND) tl_sizer.Add(sizer, 1, wx.EXPAND | wx.ALL, 7) #sizer.SetMinSize((100, 50)) progress_panel.SetAutoLayout(True) progress_panel.SetSizer(tl_sizer) progress_panel.GetSizer().Fit(progress_panel) progress_panel.GetSizer().SetSizeHints(progress_panel) return progress_panel def _make_menu(self): # Menu Bar self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) self.fileNewId = wx.NewId() self.fileOpenId = wx.NewId() self.fileOpenSegmentId = wx.NewId() self.fileSaveId = wx.NewId() self.id_file_save_as = wx.NewId() self.id_file_export = wx.NewId() self.fileSaveSelectedId = wx.NewId() self.fileExportAsDOTId = wx.NewId() self.fileExportSelectedAsDOTId = wx.NewId() self.fileExitId = wx.NewId() self.window_python_shell_id = wx.NewId() self.helpShowHelpId = wx.NewId() self.helpAboutId = wx.NewId() file_menu = wx.Menu() file_menu.Append(self.fileNewId, "&New\tCtrl-N", "Create new network.", wx.ITEM_NORMAL) file_menu.Append(self.fileOpenId, "&Open\tCtrl-O", "Open and load existing network.", wx.ITEM_NORMAL) file_menu.Append( self.fileOpenSegmentId, "Open as Se&gment\tCtrl-G", "Open a DeVIDE network as a segment in the copy buffer.", wx.ITEM_NORMAL) file_menu.Append(self.fileSaveId, "&Save\tCtrl-S", "Save the current network.", wx.ITEM_NORMAL) file_menu.Append(self.id_file_save_as, "Save &As", "Save the current network with a new filename.", wx.ITEM_NORMAL) file_menu.Append(self.id_file_export, "&Export\tCtrl-E", "Export the current network with relative filenames", wx.ITEM_NORMAL) file_menu.Append(self.fileSaveSelectedId, "Save se&lected Glyphs\tCtrl-L", "Save the selected glyphs as a network.", wx.ITEM_NORMAL) file_menu.AppendSeparator() file_menu.Append( self.fileExportAsDOTId, "Export as DOT file", "Export the current network as a GraphViz DOT file.", wx.ITEM_NORMAL) file_menu.Append(self.fileExportSelectedAsDOTId, "Export selection as DOT file", "Export the selected glyphs as a GraphViz DOT file.", wx.ITEM_NORMAL) file_menu.AppendSeparator() file_menu.Append(self.fileExitId, "E&xit\tCtrl-Q", "Exit DeVIDE!", wx.ITEM_NORMAL) self.menubar.Append(file_menu, "&File") self.edit_menu = wx.Menu() self.menubar.Append(self.edit_menu, "&Edit") modules_menu = wx.Menu() self.id_modules_search = wx.NewId() modules_menu.Append( self.id_modules_search, "Search for modules\tCtrl-F", "Change input " "focus to module search box.", wx.ITEM_NORMAL) self.id_rescan_modules = wx.NewId() modules_menu.Append( self.id_rescan_modules, "Rescan modules", "Recheck all module " "directories for new modules and metadata.", wx.ITEM_NORMAL) self.id_refresh_module_kits = wx.NewId() modules_menu.Append( self.id_refresh_module_kits, "Refresh module kits", "Attempt to refresh / reload all module_kits.", wx.ITEM_NORMAL) self.menubar.Append(modules_menu, "&Modules") self.network_menu = wx.Menu() self.menubar.Append(self.network_menu, "&Network") window_menu = wx.Menu() self.window_default_view_id = wx.NewId() window_menu.Append( self.window_default_view_id, "Restore &default view", "Restore default perspective / window configuration.", wx.ITEM_NORMAL) window_menu.Append(self.window_python_shell_id, "&Python Shell", "Show the Python Shell interface.", wx.ITEM_NORMAL) self.menubar.Append(window_menu, "&Window") help_menu = wx.Menu() help_menu.Append(self.helpShowHelpId, "Show &Help\tF1", "", wx.ITEM_NORMAL) help_menu.Append(self.helpAboutId, "About", "", wx.ITEM_NORMAL) self.menubar.Append(help_menu, "&Help") # Menu Bar end def set_progress(self, percentage, message): self.statusbar.gauge.SetValue(percentage) self.statusbar.SetStatusText(message, 0)
Python
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. ################################################################### # the following programmes should either be on your path, or you # should specify the full paths here. # Microsoft utility to rebase files. REBASE = "rebase" MAKE_NSIS = "makensis" STRIP = "strip" CHRPATH = "chrpath" # end of programmes ############################################### # NOTHING TO CONFIGURE BELOW THIS LINE ############################ import getopt import os import re import shutil import sys import tarfile PPF = "[*** DeVIDE make_dist ***]" S_PPF = "%s =====>>>" % (PPF,) # used for stage headers S_CLEAN_PYI = 'clean_pyi' S_RUN_PYI = 'run_pyi' S_WRAPITK_TREE = 'wrapitk_tree' S_REBASE_DLLS = 'rebase_dlls' S_POSTPROC_SOS = 'postproc_sos' S_PACKAGE_DIST = 'package_dist' DEFAULT_STAGES = '%s, %s, %s, %s, %s, %s' % \ (S_CLEAN_PYI, S_RUN_PYI, S_WRAPITK_TREE, S_REBASE_DLLS, S_POSTPROC_SOS, S_PACKAGE_DIST) HELP_MESSAGE = """ make_dist.py - build DeVIDE distributables. Invoke as follows: python make_dist.py -s specfile -i installer_script where specfile is the pyinstaller spec file and installer_script refers to the full path of the pyinstaller Build.py The specfile should be in the directory devide/installer, where devide is the directory containing the devide source that you are using to build the distributables. Other switches: --stages : by default all stages are run. With this parameter, a subset of the stages can be specified. The full list is: %s """ % (DEFAULT_STAGES,) #################################################################### class MDPaths: """Initialise all directories required for building DeVIDE distributables. """ def __init__(self, specfile, pyinstaller_script): self.specfile = os.path.normpath(specfile) self.pyinstaller_script = os.path.normpath(pyinstaller_script) # devide/installer self.specfile_dir = os.path.normpath( os.path.abspath(os.path.dirname(self.specfile))) self.pyi_dist_dir = os.path.join(self.specfile_dir, 'distdevide') self.pyi_build_dir = os.path.join(self.specfile_dir, 'builddevide') # devide self.devide_dir = \ os.path.normpath( os.path.join(self.specfile_dir, '..')) #################################################################### # UTILITY METHODS #################################################################### def get_status_output(command): """Run command, return output of command and exit code in status. In general, status is None for success and 1 for command not found. Method taken from johannes.utils. """ ph = os.popen(command) output = ph.read() status = ph.close() return (status, output) def find_command_with_ver(name, command, ver_re): """Try to run command, use ver_re regular expression to parse for the version string. This will print for example: CVS: version 2.11 found. @return: True if command found, False if not or if version could not be parsed. Method taken from johannes.utils. """ retval = False s,o = get_status_output(command) if s: msg2 = 'NOT FOUND!' else: mo = re.search(ver_re, o, re.MULTILINE) if mo: msg2 = 'version %s found.' % (mo.groups()[0],) retval = True else: msg2 = 'could not extract version.' print PPF, "%s: %s" % (name, msg2) return retval def find_files(start_dir, re_pattern='.*\.(pyd|dll)', exclude_pats=[]): """Recursively find all files (not directories) with filenames matching given regular expression. Case is ignored. @param start_dir: search starts in this directory @param re_pattern: regular expression with which all found files will be matched. example: re_pattern = '.*\.(pyd|dll)' will match all filenames ending in pyd or dll. @param exclude_pats: if filename (without directory) matches any one of these patterns, do not include it in the list @return: list of fully qualified filenames that satisfy the pattern """ cpat = re.compile(re_pattern, re.IGNORECASE) found_files = [] excluded_files = [] for dirpath, dirnames, filenames in os.walk(start_dir): ndirpath = os.path.normpath(os.path.abspath(dirpath)) for fn in filenames: if cpat.match(fn): # see if fn does not satisfy one of the exclude # patterns exclude_fn = False for exclude_pat in exclude_pats: if re.match(exclude_pat, fn, re.IGNORECASE): exclude_fn = True break if not exclude_fn: found_files.append(os.path.join(ndirpath,fn)) else: excluded_files.append(os.path.join(ndirpath,fn)) return found_files, excluded_files #################################################################### # METHODS CALLED FROM MAIN() #################################################################### def usage(): print HELP_MESSAGE def clean_pyinstaller(md_paths): """Clean out pyinstaller dist and build directories so that it has to do everything from scratch. We usually do this before building full release versions. """ print S_PPF, "clean_pyinstaller" if os.path.isdir(md_paths.pyi_dist_dir): print PPF, "Removing distdevide..." shutil.rmtree(md_paths.pyi_dist_dir) if os.path.isdir(md_paths.pyi_build_dir): print PPF, "Removing builddevide..." shutil.rmtree(md_paths.pyi_build_dir) def run_pyinstaller(md_paths): """Run pyinstaller with the given parameters. This does not clean out the dist and build directories before it begins """ print S_PPF, "run_pyinstaller" # first get rid of all pre-compiled and backup files. These HAVE # screwed up our binaries in the past! print PPF, 'Deleting PYC, *~ and #*# files' dead_files, _ = find_files(md_paths.devide_dir, '(.*\.pyc|.*~|#.*#)') for fn in dead_files: os.unlink(fn) cmd = '%s %s %s' % (sys.executable, md_paths.pyinstaller_script, md_paths.specfile) ret = os.system(cmd) if ret != 0: raise RuntimeError('Error running PYINSTALLER.') if os.name == 'nt': for efile in ['devide.exe.manifest', 'msvcm80.dll', 'Microsoft.VC80.CRT.manifest']: print PPF, "WINDOWS: copying", efile src = os.path.join( md_paths.specfile_dir, efile) dst = os.path.join( md_paths.pyi_dist_dir, efile) shutil.copyfile(src, dst) else: # rename binary and create invoking script # we only have to set LD_LIBRARY_PATH, PYTHONPATH is correct # copy devide binary to devide.bin invoking_fn = os.path.join(md_paths.pyi_dist_dir, 'devide') os.rename(invoking_fn, os.path.join(md_paths.pyi_dist_dir, 'devide.bin')) # copy our own script to devide shutil.copyfile( os.path.join( md_paths.specfile_dir, 'devideInvokingScript.sh'), invoking_fn) # chmod +x $SCRIPTFILE os.chmod(invoking_fn,0755) def package_dist(md_paths): """After pyinstaller has been executed, do all actions to package up a distribution. 4. package and timestamp distributables (nsis on win, tar on posix) """ print S_PPF, "package_dist" # get devide version (we need this to stamp the executables) cmd = '%s -v' % (os.path.join(md_paths.pyi_dist_dir, 'devide'),) s,o = get_status_output(cmd) # s == None if DeVIDE has executed successfully if s: raise RuntimeError('Could not exec DeVIDE to extract version.') mo = re.search('^DeVIDE\s+(v.*)$', o, re.MULTILINE) if mo: devide_ver = mo.groups()[0] else: raise RuntimeError('Could not extract DeVIDE version.') if os.name == 'nt': # we need to be in the installer directory before starting # makensis os.chdir(md_paths.specfile_dir) cmd = '%s devide.nsi' % (MAKE_NSIS,) ret = os.system(cmd) if ret != 0: raise RuntimeError('Error running NSIS.') # nsis creates devidesetup.exe - we're going to rename os.rename('devidesetup.exe', 'devidesetup-%s.exe' % (devide_ver,)) else: # go to the installer dir os.chdir(md_paths.specfile_dir) # rename distdevide to devide-version basename = 'devide-%s' % (devide_ver,) os.rename('distdevide', basename) # create tarball with juicy stuff tar = tarfile.open('%s.tar.bz2' % basename, 'w:bz2') # recursively add directory tar.add(basename) # finalize tar.close() # rename devide-version back to distdevide os.rename(basename, 'distdevide') def postproc_sos(md_paths): if os.name == 'posix': print S_PPF, "postproc_sos (strip, chrpath)" # strip all libraries so_files, _ = find_files(md_paths.pyi_dist_dir, '.*\.(so$|so\.)') print PPF, 'strip / chrpath %d SO files.' % (len(so_files),) for so_file in so_files: # strip debug info ret = os.system('%s %s' % (STRIP, so_file)) if ret != 0: print "Error stripping %s." % (so_file,) # remove rpath information ret = os.system('%s --delete %s' % (CHRPATH, so_file)) if ret != 0: print "Error chrpathing %s." % (so_file,) def rebase_dlls(md_paths): """Rebase all DLLs in the distdevide tree on Windows. """ if os.name == 'nt': print S_PPF, "rebase_dlls" # sqlite3.dll cannot be rebased; it even gets corrupted in the # process! see this test: # C:\TEMP>rebase -b 0x60000000 -e 0x1000000 sqlite3.dll # REBASE: *** RelocateImage failed (sqlite3.dll). # Image may be corrupted # get list of pyd / dll files, excluding sqlite3 so_files, excluded_files = find_files( md_paths.pyi_dist_dir, '.*\.(pyd|dll)', ['sqlite3\.dll']) # add newline to each and every filename so_files = ['%s\n' % (i,) for i in so_files] print "Found %d DLL PYD files..." % (len(so_files),) print "Excluded %d files..." % (len(excluded_files),) # open file in specfile_dir, write the whole list dll_list_fn = os.path.join( md_paths.specfile_dir, 'dll_list.txt') dll_list = file(dll_list_fn, 'w') dll_list.writelines(so_files) dll_list.close() # now run rebase on the list os.chdir(md_paths.specfile_dir) ret = os.system( '%s -b 0x60000000 -e 0x1000000 @dll_list.txt -v' % (REBASE,)) # rebase returns 99 after rebasing, no idea why. if ret != 99: raise RuntimeError('Could not rebase DLLs.') def wrapitk_tree(md_paths): print S_PPF, "wrapitk_tree" py_file = os.path.join(md_paths.specfile_dir, 'wrapitk_tree.py') cmd = "%s %s %s" % (sys.executable, py_file, md_paths.pyi_dist_dir) ret = os.system(cmd) if ret != 0: raise RuntimeError( 'Error creating self-contained WrapITK tree.') def posix_prereq_check(): print S_PPF, 'POSIX prereq check' # gnu # have the word version anywhere v = find_command_with_ver( 'strip', '%s --version' % (STRIP,), '([0-9\.]+)') v = v and find_command_with_ver( 'chrpath', '%s --version' % (CHRPATH,), 'version\s+([0-9\.]+)') return v def windows_prereq_check(): print S_PPF, 'WINDOWS prereq check' # if you give rebase any other command-line switches (even /?) it # exits with return code 99 and outputs its stuff to stderr # with -b it exits with return code 0 (expected) and uses stdout v = find_command_with_ver( 'Microsoft Rebase (rebase.exe)', '%s -b 0x60000000' % (REBASE,), '^(REBASE):\s+Total.*$') v = v and find_command_with_ver( 'Nullsoft Installer System (makensis.exe)', '%s /version' % (MAKE_NSIS,), '^(v[0-9\.]+)$') # now check that setuptools is NOT installed (it screws up # everything on Windows) try: import setuptools except ImportError: # this is what we want print PPF, 'setuptools not found. Good!' sut_v = True else: print PPF, """setuptools is installed. setuptools will break the DeVIDE dist build. Please uninstall by doing: \Python25\Scripts\easy_install -m setuptools del \Python25\Lib\site-packages\setuptools*.* You can reinstall later by using ez_setup.py again. """ sut_v = False return v and sut_v def main(): try: optlist, args = getopt.getopt( sys.argv[1:], 'hs:i:', ['help', 'spec=','pyinstaller-script=','stages=']) except getopt.GetoptError,e: usage return spec = None pyi_script = None stages = DEFAULT_STAGES for o, a in optlist: if o in ('-h', '--help'): usage() return elif o in ('-s', '--spec'): spec = a elif o in ('-i', '--pyinstaller-script'): pyi_script = a elif o in ('--stages'): stages = a if spec is None or pyi_script is None: # we need BOTH the specfile and pyinstaller script usage() return 1 # dependency checking if os.name == 'nt': if not windows_prereq_check(): print PPF, "ERR: Windows prerequisites do not check out." return 1 else: if not posix_prereq_check(): print PPF, "ERR: POSIX prerequisites do not check out." return 1 md_paths = MDPaths(spec, pyi_script) stages = [i.strip() for i in stages.split(',')] if S_CLEAN_PYI in stages: clean_pyinstaller(md_paths) if S_RUN_PYI in stages: run_pyinstaller(md_paths) if S_WRAPITK_TREE in stages: wrapitk_tree(md_paths) if S_REBASE_DLLS in stages: rebase_dlls(md_paths) if S_POSTPROC_SOS in stages: postproc_sos(md_paths) if S_PACKAGE_DIST in stages: package_dist(md_paths) if __name__ == '__main__': main()
Python
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. # RESTRUCTURE: # * remove_binaries (startswith and contains) # * remove_pure (startswith and contains) # NB: stay away from any absolute path dependencies!!! import os import fnmatch import re import sys def helper_remove_start(name, remove_names): """Helper function used to remove libraries from list. Returns true of name starts with anything from remove_names. """ name = name.lower() for r in remove_names: if name.startswith(r.lower()): return True return False def helper_remove_finds(name, remove_finds): """Helper function that returns true if any item in remove_finds (list) can be string-found in name. Everything is lowercased. """ name = name.lower() for r in remove_finds: if name.find(r.lower()) >= 0: return True return False def helper_remove_regexp(name, remove_regexps): """Helper function to remove things from list. Returns true if name matches any regexp in remove_regexps. """ for r in remove_regexps: if re.match(r, name) is not None: return True return False # argv[0] is the name of the Build.py script INSTALLER_DIR = os.path.abspath(os.path.dirname(sys.argv[0])) # argv[1] is the name of the spec file # first we get the path of the spec file, then we have to go one up specpath = os.path.abspath(os.path.dirname(sys.argv[1])) APP_DIR = os.path.split(specpath)[0] from distutils import sysconfig MPL_DATA_DIR = os.path.join(sysconfig.get_python_lib(), 'matplotlib/mpl-data') import gdcm gdcm_p3xml_fn = os.path.join(gdcm.GDCM_SOURCE_DIR, 'Source/InformationObjectDefinition', 'Part3.xml') if sys.platform.startswith('win'): exeName = 'builddevide/devide.exe' extraLibs = [] # we can keep msvcr71.dll and msvcp71.dll, in fact they should just # go in the installation directory with the other DLLs, see: # http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ # vclib/html/_crt_c_run.2d.time_libraries.asp remove_binaries = ['dciman32.dll', 'ddraw.dll', 'glu32.dll', 'msvcp60.dll', 'netapi32.dll', 'opengl32.dll', 'uxtheme.dll'] else: exeName = 'builddevide/devide' # under some linuxes, libpython is shared -- McMillan installer doesn't # know about this... extraLibs = [] # i'm hoping this isn't necessary anymore! if False: vi = sys.version_info if (vi[0], vi[1]) == (2,4): # ubuntu hoary extraLibs = [('libpython2.4.so.1.0', '/usr/lib/libpython2.4.so.1.0', 'BINARY')] elif (vi[0], vi[1]) == (2,2) and \ os.path.exists('/usr/lib/libpython2.2.so.0.0'): # looks like debian woody extraLibs = [('libpython2.2.so.0.0', '/usr/lib/libpython2.2.so.0.0', 'BINARY')] # RHEL3 64 has a static python library. ##################################################################### # on ubuntu 6.06, libdcmdata.so.1 and libofstd.so.1 could live in # /usr/lib, and are therefore thrown out by the McMillan Installer if os.path.exists('/usr/lib/libdcmdata.so.1') and \ os.path.exists('/usr/lib/libofstd.so.1'): extraLibs.append( ('libdcmdata.so.1', '/usr/lib/libdcmdata.so.1', 'BINARY')) extraLibs.append( ('libofstd.so.1', '/usr/lib/libofstd.so.1','BINARY')) ###################################################################### # to get this to work on Debian 3.1, we also need to ship libstdc++ # and libXinerama # FIXME: figure some other way out to include the CORRECT libstdc++, # the previous hardcoding of this caused problems with the VL-e POC stdc = '/usr/lib/libstdc++.so.6' if os.path.exists(stdc): extraLibs.append((os.path.basename(stdc), stdc, 'BINARY')) xine = '/usr/lib/libXinerama.so.1' if os.path.exists(xine): extraLibs.append((os.path.basename(xine), xine, 'BINARY')) ###################################################################### # ubuntu 7.10 has renumbered libtiff 3.7 (or .8) to 4. other dists of # course don't have this, so we have to include it. libtiff = '/usr/lib/libtiff.so.4' if os.path.exists(libtiff): extraLibs.append( (os.path.basename(libtiff), libtiff, 'BINARY')) ###################################################################### # also add some binary dependencies of numpy that are normally ignored # because they are in /lib and/or /usr/lib (see excludes in bindepend.py) from distutils import sysconfig npdir = os.path.join(sysconfig.get_python_lib(), 'numpy') ladir = os.path.join(npdir, 'linalg') lplpath = os.path.join(ladir, 'lapack_lite.so') # use mcmillan function to get LDD dependencies of lapack_lite.so import bindepend lpl_deps = bindepend.getImports(lplpath) for d in lpl_deps: if d.find('lapack') > 0 or d.find('blas') > 0 or \ d.find('g2c') > 0 or d.find('atlas') > 0: extraLibs.append( (os.path.basename(d), d, 'BINARY')) # end numpy-dependent extraLibs section ################################################################## # these libs will be removed from the package remove_binaries = ['libdl.so', 'libutil.so', 'libm.so', 'libc.so', 'libGLU.so', 'libGL.so', 'libGLcore.so', 'libnvidia-tls.so', 'ld-linux-x86-64.so.2', 'libgcc_s.so', 'libtermcap', 'libXft.so', 'libXrandr.so', 'libXrender.so', 'libpthread.so', 'libreadline.so', 'libICE.so', 'libSM.so', 'libX11.so', 'libXext.so', 'libXi.so', 'libXt.so', 'libpango', 'libfontconfig', 'libfreetype', 'libatk', 'libgtk', 'libgdk', 'libglib', 'libgmodule', 'libgobject', 'libgthread', 'librt', 'qt', '_tkinter'] # make sure remove_binaries is lowercase remove_binaries = [i.lower() for i in remove_binaries] # global removes: we want to include this file so that the user can edit it #remove_binaries += ['defaults.py'] # we have to remove these nasty built-in dependencies EARLY in the game dd = config['EXE_dependencies'] newdd = [i for i in dd if not helper_remove_start(i[0].lower(), remove_binaries)] config['EXE_dependencies'] = newdd print "[*] APP_DIR == %s" % (APP_DIR) print "[*] exeName == %s" % (exeName) mainScript = os.path.join(APP_DIR, 'devide.py') print "[*] mainScript == %s" % (mainScript) # generate available kit list ######################################### # simple form of the checking done by the module_kits package itself sys.path.insert(0, APP_DIR) import module_kits ####################################################################### # segments segTree = Tree(os.path.join(APP_DIR, 'segments'), 'segments', ['.svn']) # snippets snipTree = Tree(os.path.join(APP_DIR, 'snippets'), 'snippets', ['.svn']) # arb data dataTree = Tree(os.path.join(APP_DIR, 'data'), 'data', ['.svn']) # documents and help, exclude help source docsTree = Tree(os.path.join(APP_DIR, 'docs'), 'docs', ['.svn', 'source']) # all modules modules_tree = Tree(os.path.join(APP_DIR, 'modules'), 'modules', ['.svn', '*~']) # all module_kits module_kits_tree = Tree(os.path.join(APP_DIR, 'module_kits'), 'module_kits', ['.svn', '*~']) print "===== APP_DIR: ", APP_DIR # VTKPIPELINE ICONS # unfortunately, due to the vtkPipeline design, these want to live one # down from the main dir vpli_dir = os.path.join(APP_DIR, 'external/vtkPipeline/Icons') vpli = [(os.path.join('Icons', i), os.path.join(vpli_dir, i), 'DATA') for i in os.listdir(vpli_dir) if fnmatch.fnmatch(i, '*.xpm')] # MATPLOTLIB data dir mpl_data_dir = Tree(MPL_DATA_DIR, 'matplotlibdata') # GDCM Part3.xml gdcm_tree = [('gdcmdata/XML/Part3.xml', gdcm_p3xml_fn, 'DATA')] if False: from distutils import sysconfig numpy_tree = Tree( os.path.join(sysconfig.get_python_lib(),'numpy'), prefix=os.path.join('module_kits','numpy_kit','numpy'), excludes=['*.pyc', '*.pyo', 'doc', 'docs']) testing_tree = Tree(os.path.join(APP_DIR, 'testing'), 'testing', ['.svn', '*~', '*.pyc']) # and some miscellaneous files misc_tree = [('devide.cfg', '%s/devide.cfg' % (APP_DIR,), 'DATA')] ########################################################################## SUPPORT_DIR = os.path.join(INSTALLER_DIR, 'support') a = Analysis([os.path.join(SUPPORT_DIR, '_mountzlib.py'), os.path.join(SUPPORT_DIR, 'useUnicode.py'), mainScript], pathex=[], hookspath=[os.path.join(APP_DIR, 'installer', 'hooks')]) ###################################################################### # sanitise a.pure remove_pure_finds = [] # we remove all module and module_kits based things, because they're # taken care of by hooks/hook-moduleManager.py # we also remove itk (it seems to be slipping in in spite of the fact # that I'm explicitly excluding it from module_kits) remove_pure_starts = ['modules.', 'module_kits', 'testing', 'itk'] for i in range(len(a.pure)-1, -1, -1): if helper_remove_finds(a.pure[i][1], remove_pure_finds) or \ helper_remove_start(a.pure[i][0], remove_pure_starts): del a.pure[i] ###################################################################### # sanitise a.binaries remove_binary_finds = [] for i in range(len(a.binaries)-1, -1, -1): if helper_remove_finds(a.binaries[i][1], remove_binaries) or \ helper_remove_start(a.binaries[i][0], remove_binary_finds): del a.binaries[i] ###################################################################### # create the compressed archive with all the other pyc files # will be integrated with EXE archive pyz = PYZ(a.pure) # in Installer 6a2, the -f option is breaking things (the support directory # is deleted after the first invocation!) #options = [('f','','OPTION')] # LD_LIBRARY_PATH is correctly set on Linux #options = [('v', '', 'OPTION')] # Python is ran with -v options = [] # because we've already modified the config, we won't be pulling in # hardcoded dependencies that we don't want. exe = EXE(pyz, a.scripts + options, exclude_binaries=1, name=exeName, icon=os.path.join(APP_DIR, 'resources/graphics/devidelogo64x64.ico'), debug=0, strip=0, console=True) all_binaries = a.binaries + modules_tree + module_kits_tree + vpli + \ mpl_data_dir + \ extraLibs + segTree + snipTree + dataTree + docsTree + misc_tree + \ testing_tree + gdcm_tree coll = COLLECT(exe, all_binaries, strip=0, name='distdevide') # wrapitk_tree is packaged completely separately
Python
"""Module for independently packaging up whole WrapITK tree. """ import itkConfig import glob import os import shutil import sys # customise the following variables if os.name == 'nt': SO_EXT = 'dll' SO_GLOB = '*.%s' % (SO_EXT,) PYE_GLOB = '*.pyd' # this should be c:/opt/ITK/bin ITK_SO_DIR = os.path.normpath( os.path.join(itkConfig.swig_lib, '../../../../bin')) else: SO_EXT = 'so' SO_GLOB = '*.%s.*' % (SO_EXT,) PYE_GLOB = '*.so' curdir = os.path.abspath(os.curdir) # first go down to Insight/lib/InsightToolkit/WrapITK/lib os.chdir(itkConfig.swig_lib) # then go up twice os.chdir(os.path.join('..', '..')) # then find the curdir ITK_SO_DIR = os.path.abspath(os.curdir) # change back to where we started os.chdir(curdir) # we want: # itk_kit/wrapitk/py (*.py and Configuration and itkExtras subdirs from # WrapITK/Python) # itk_kit/wrapitk/lib (*.py and *.so from WrapITK/lib) def get_wrapitk_tree(): """Return tree relative to itk_kit/wrapitk top. """ # WrapITK/lib -> itk_kit/wrapitk/lib (py files, so/dll files) lib_files = glob.glob('%s/*.py' % (itkConfig.swig_lib,)) # on linux there are Python SO files, on Windows they're actually # all PYDs (and not DLLs) - these are ALL python extension modules lib_files.extend(glob.glob('%s/%s' % (itkConfig.swig_lib, PYE_GLOB))) # on Windows we also need the SwigRuntime.dll in c:/opt/WrapITK/bin! # the files above on Windows are in: # C:\\opt\\WrapITK\\lib\\InsightToolkit\\WrapITK\\lib if os.name == 'nt': lib_files.extend(glob.glob('%s/%s' % (ITK_SO_DIR, SO_GLOB))) wrapitk_lib = [('lib/%s' % (os.path.basename(i),), i) for i in lib_files] # WrapITK/Python -> itk_kit/wrapitk/python (py files) py_path = os.path.normpath(os.path.join(itkConfig.config_py, '..')) py_files = glob.glob('%s/*.py' % (py_path,)) wrapitk_py = [('python/%s' % (os.path.basename(i),), i) for i in py_files] # WrapITK/Python/Configuration -> itk_kit/wrapitk/python/Configuration config_files = glob.glob('%s/*.py' % (os.path.join(py_path,'Configuration'),)) wrapitk_config = [('python/Configuration/%s' % (os.path.basename(i),), i) for i in config_files] # itkExtras extra_files = glob.glob('%s/*.py' % (os.path.join(py_path, 'itkExtras'),)) wrapitk_extra = [('python/itkExtras/%s' % (os.path.basename(i),), i) for i in extra_files] # complete tree wrapitk_tree = wrapitk_lib + wrapitk_py + wrapitk_config + wrapitk_extra return wrapitk_tree def get_itk_so_tree(): """Get the ITK DLLs themselves. Return tree relative to itk_kit/wrapitk top. """ so_files = glob.glob('%s/%s' % (ITK_SO_DIR, SO_GLOB)) itk_so_tree = [('lib/%s' % (os.path.basename(i),), i) for i in so_files] return itk_so_tree def copy3(src, dst): """Same as shutil.copy2, but copies symlinks as they are, i.e. equivalent to --no-dereference parameter of cp. """ dirname = os.path.dirname(dst) if dirname and not os.path.exists(dirname): os.makedirs(dirname) if os.path.islink(src): linkto = os.readlink(src) os.symlink(linkto, dst) else: shutil.copy2(src, dst) def install(devide_app_dir): """Install a self-contained wrapitk installation in itk_kit_dir. """ itk_kit_dir = os.path.join(devide_app_dir, 'module_kits/itk_kit') print "Deleting existing wrapitk dir." sys.stdout.flush() witk_dest_dir = os.path.join(itk_kit_dir, 'wrapitk') if os.path.exists(witk_dest_dir): shutil.rmtree(witk_dest_dir) print "Creating list of WrapITK files..." sys.stdout.flush() wrapitk_tree = get_wrapitk_tree() print "Copying WrapITK files..." sys.stdout.flush() for f in wrapitk_tree: copy3(f[1], os.path.join(witk_dest_dir, f[0])) print "Creating list of ITK shared objects..." sys.stdout.flush() itk_so_tree = get_itk_so_tree() print "Copying ITK shared objects..." sys.stdout.flush() for f in itk_so_tree: copy3(f[1], os.path.join(witk_dest_dir, f[0])) if os.name == 'nt': # on Windows, it's not easy setting the DLL load path in a running # application. You could try SetDllDirectory, but that only works # since XP SP1. You could also change the current dir, but our DLLs # are lazy loaded, so no go. An invoking batchfile is out of the # question. print "Moving all SOs back to main DeVIDE dir [WINDOWS] ..." lib_path = os.path.join(witk_dest_dir, 'lib') so_files = glob.glob(os.path.join(lib_path, SO_GLOB)) so_files.extend(glob.glob(os.path.join(lib_path, PYE_GLOB))) for so_file in so_files: shutil.move(so_file, devide_app_dir) #also write list of DLLs that were moved to lib_path/moved_dlls.txt f = file(os.path.join(lib_path, 'moved_dlls.txt'), 'w') f.writelines(['%s\n' % (os.path.basename(fn),) for fn in so_files]) f.close() if __name__ == '__main__': if len(sys.argv) < 2: print "Specify devide app dir as argument." else: install(sys.argv[1])
Python
# miscellaneous imports used by snippets hiddenimports = ['tempfile']
Python
hiddenimports = ['matplotlib.numerix', 'matplotlib.numerix.fft', 'matplotlib.numerix.linear_algebra', 'matplotlib.numerix.ma', 'matplotlib.numerix.mlab', 'matplotlib.numerix.npyma', 'matplotlib.numerix.random_array', 'matplotlib.backends.backend_wxagg'] print "[*] hook-matplotlib.py - HIDDENIMPORTS" print hiddenimports
Python
# so vtktudoss.py uses a list of names to construct the various imports # at runtime, installer doesn't see this. :( import os if os.name == 'posix': hiddenimports = [ 'libvtktudossGraphicsPython', 'libvtktudossWidgetsPython', 'libvtktudossSTLibPython'] else: hiddenimports = [ 'vtktudossGraphicsPython', 'vtktudossWidgetsPython', 'vtktudossSTLibPython'] print "[*] hook-vtktudoss.py - HIDDENIMPORTS" print hiddenimports
Python
# so vtktud.py uses a list of names to construct the various imports # at runtime, installer doesn't see this. :( import os if os.name == 'posix': hiddenimports = ['libvtktudCommonPython', 'libvtktudImagingPython', 'libvtktudGraphicsPython', 'libvtktudWidgetsPython'] else: hiddenimports = ['vtktudCommonPython', 'vtktudImagingPython', 'vtktudGraphicsPython', 'vtktudWidgetsPython'] print "[*] hook-vtktud.py - HIDDENIMPORTS" print hiddenimports
Python
# this hook is responsible for including everything that the DeVIDE # modules could need. The top-level spec file explicitly excludes # them. import os import sys # normalize path of this file, get dirname hookDir = os.path.dirname(os.path.normpath(__file__)) # split dirname, select everything except the ending "installer/hooks" dd = hookDir.split(os.sep)[0:-2] # we have to do this trick, since on windows os.path.join('c:', 'blaat') # yields 'c:blaat', i.e. relative to current dir, and we know it's absolute dd[0] = '%s%s' % (dd[0], os.sep) # turn that into a path again by making use of join (the normpath will take # care of redundant slashes on *ix due to the above windows trick) devideDir = os.path.normpath(os.path.join(*dd)) # now we've inserted the devideDir into the module path, so # import modules should work sys.path.insert(0, devideDir) import module_kits # now also parse config file import ConfigParser config_defaults = {'nokits': ''} cp = ConfigParser.ConfigParser(config_defaults) cp.read(os.path.join(devideDir, 'devide.cfg')) nokits = [i.strip() for i in cp.get('DEFAULT', 'nokits').split(',')] module_kits_dir = os.path.join(devideDir, 'module_kits') mkds = module_kits.get_sorted_mkds(module_kits_dir) # 1. remove the no_kits # 2. explicitly remove itk_kit, it's handled completely separately by # the makePackage.sh script file mkl = [i.name for i in mkds if i.name not in nokits and i.name not in ['itk_kit','itktudoss_kit']] # other imports other_imports = ['genMixins', 'gen_utils', 'ModuleBase', 'module_mixins', 'module_utils', 'modules.viewers.DICOMBrowser', 'modules.viewers.slice3dVWR', 'modules.viewers.histogram1D', 'modules.viewers.TransferFunctionEditor'] # seems on Linux we have to make sure readline comes along (else # vtkObject introspection windows complain) try: import readline except ImportError: pass else: other_imports.append('readline') hiddenimports = ['module_kits.%s' % (i,) for i in mkl] + other_imports print "[*] hook-ModuleManager.py - HIDDENIMPORTS" print hiddenimports
Python
hiddenimports = ['wx.aui', 'wx.lib.mixins'] print "[*] hook-wx.py - HIDDENIMPORTS" print hiddenimports
Python
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. """Collection of module utility functions. @author: Charl P. Botha <http://cpbotha.net/> """ import wx import resources.graphics.images def create_eoca_buttons(d3module, viewFrame, viewFramePanel, ok_default=True, cancel_hotkey=True): """Add Execute, OK, Cancel and Apply buttons to the viewFrame. d3module is the module for which these buttons are being added. viewFrame is the actual dialog frame. viewFramePanel is the top-level panel in the frame, i.e. the panel completely filling the top-level sizer. IMPORTANT: viewFrame must have a top-level sizer that contains ONLY the viewFramePanel. This is the default for wxGlade created dialogs with a top-level panel. The viewFramePanel's sizer must be a vertical box sizer that contains ANOTHER sizer with a 7 pixel border all around. These ECAS buttons will be in a sibling sizer to that ANOTHER sizer. The buttons will be created with the viewFramePanel as their parent. They will be added to a horizontal sizer which will then be added to viewFramePanel.GetSizer(). The viewFramePanel sizer will then be used to fit the viewFramePanel. After this, the viewFrame.GetSizer() will be used to fit and layout the frame itself. """ # create the buttons viewFrame.executeButtonId = wx.NewId() viewFrame.executeButton = wx.Button(viewFramePanel, viewFrame.executeButtonId, "&Execute") viewFrame.executeButton.SetToolTip(wx.ToolTip( "Apply all changes, then execute the whole network "\ "(F5 or Alt-E).")) viewFrame.id_ok_button = wx.ID_OK viewFrame.ok_button = wx.Button( viewFramePanel, viewFrame.id_ok_button, "OK") viewFrame.ok_button.SetToolTip(wx.ToolTip( "Apply all changes, then close this dialogue (Enter).")) viewFrame.id_cancel_button = wx.ID_CANCEL viewFrame.cancel_button = wx.Button( viewFramePanel, viewFrame.id_cancel_button, "Cancel") viewFrame.cancel_button.SetToolTip(wx.ToolTip( "Cancel all changes, then close this dialogue (Esc).")) viewFrame.applyButtonId = wx.NewId() viewFrame.applyButton = wx.Button(viewFramePanel, viewFrame.applyButtonId, "Apply") viewFrame.applyButton.SetToolTip(wx.ToolTip( "Apply all changes, keep this dialogue open.")) # add them to their own sizer, each with a border of 4 pixels on the right buttonSizer = wx.BoxSizer(wx.HORIZONTAL) for button in (viewFrame.executeButton, viewFrame.ok_button, viewFrame.cancel_button): buttonSizer.Add(button, 0, wx.RIGHT, 7) # except for the right-most button, which has no border buttonSizer.Add(viewFrame.applyButton, 0) # add the buttonSizer to the viewFramePanel sizer with a border of 7 pixels # on the left, right and bottom... remember, this is below a sizer with # a 7 pixel border all around! # (we do it with 8, because the default execute button is quite big!) viewFramePanel.GetSizer().Add(buttonSizer, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_RIGHT, 8) # force the sizer to calculate new layout with all children (because # we've just added something) viewFramePanel.GetSizer().Layout() # fit and setsizehints (autolayout should remain on) viewFramePanel.GetSizer().Fit(viewFramePanel) viewFramePanel.GetSizer().SetSizeHints(viewFramePanel) # now we have to get the top level sizer to do its thing # WORKAROUND - if we don't remove and add, the # viewFrame.GetSizer().Layout() below doesn't do anything. viewFrame.GetSizer().Remove(viewFramePanel) viewFrame.GetSizer().Add(viewFramePanel, 1, wx.EXPAND, 0) # WORKAROUND ENDS viewFrame.GetSizer().Layout() # this should update the minimum size viewFrame.GetSizer().Fit(viewFrame) viewFrame.GetSizer().SetSizeHints(viewFrame) # EVENT BINDINGS mm = d3module._module_manager # call back into the graphEditor, if it exists ge = mm._devide_app.get_interface()._graph_editor # execute wx.EVT_BUTTON(viewFrame, viewFrame.executeButtonId, lambda e: (mm.apply_module_view_to_logic(d3module), mm.execute_network(d3module))) # OK (apply and close) wx.EVT_BUTTON(viewFrame, viewFrame.id_ok_button, lambda e, vf=viewFrame: (mm.apply_module_view_to_logic(d3module), vf.Show(False))) # Cancel def helper_cancel(): mm.syncModuleViewWithLogic(d3module) viewFrame.Show(False) wx.EVT_BUTTON(viewFrame, viewFrame.id_cancel_button, lambda e: helper_cancel()) # Apply wx.EVT_BUTTON(viewFrame, viewFrame.applyButtonId, lambda e: mm.apply_module_view_to_logic(d3module)) # make sure that OK is the default button # unless the user specifies otherwise - in frames where we make # use of an introspection shell, we don't want Enter to executeh # or Ctrl-Enter to execute the whole network. accel_list = [] if cancel_hotkey: # this doesn't work for frames, but I'm keeping it here just # in case. We use the EVT_CHAR_HOOK later to capture escape accel_list.append( (wx.ACCEL_NORMAL, wx.WXK_ESCAPE, viewFrame.id_cancel_button)) # add F5 hotkey to this dialogue as well so that we can execute accel_list.append( (wx.ACCEL_NORMAL, wx.WXK_F5, viewFrame.executeButtonId)) if ok_default: viewFrame.ok_button.SetDefault() accel_list.append( (wx.ACCEL_NORMAL, wx.WXK_RETURN, viewFrame.id_ok_button)) # setup some hotkeys as well viewFrame.SetAcceleratorTable(wx.AcceleratorTable(accel_list)) def handler_evt_char_hook(event): if event.KeyCode == wx.WXK_ESCAPE: helper_cancel() else: event.Skip() if cancel_hotkey: # this is the only way to capture escape on a frame viewFrame.Bind(wx.EVT_CHAR_HOOK, handler_evt_char_hook) def create_standard_object_introspection(d3module, viewFrame, viewFramePanel, objectDict, renderWindow=None): """Given a devide module and its viewframe, this will create a standard wxChoice and wxButton (+ labels) UI for object and introspection. In addition, it'll call setup_object_introspection in order to bind events to these controls. In order to use this, the module HAS to use the IntrospectModuleMixin. IMPORTANT: viewFrame must have a top-level sizer that contains ONLY the viewFramePanel. This is the default for wxGlade created dialogs with a top-level panel. The viewFramePanel's sizer must be a vertical box sizer. That sizer must contain yet ANOTHER sizer with a 7 pixel border all around. The introspection controls will be created as a sibling to the ANOTHER sizer. Also see the moduleWriting guide. """ introspect_button_id = wx.NewId() introspect_button = wx.Button(viewFramePanel, introspect_button_id, "Introspect") ocLabel = wx.StaticText(viewFramePanel, -1, "the") objectChoiceId = wx.NewId() objectChoice = wx.Choice(viewFramePanel, objectChoiceId, choices=[]) objectChoice.SetToolTip(wx.ToolTip( "Select an object from the drop-down box to introspect it.")) hSizer = wx.BoxSizer(wx.HORIZONTAL) hSizer.Add(introspect_button, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4) hSizer.Add(ocLabel, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4) hSizer.Add(objectChoice, 1, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 4) vSizer = wx.BoxSizer(wx.VERTICAL) sl = wx.StaticLine(viewFramePanel, -1) vSizer.Add(sl, 0, wx.CENTER|wx.EXPAND|wx.BOTTOM, 7) vSizer.Add(hSizer, 0, wx.CENTER|wx.EXPAND) # this will usually get added right below an existing sizer with 7 points # border all around. Below us the ECAS buttons will be added and these # assume that there is a 7 pixel border above them, which is why we # supply a 7 pixel below us. viewFramePanel.GetSizer().Add(vSizer, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 7) # force the sizer to calculate new layout with all children (because # we've just added something) viewFramePanel.GetSizer().Layout() # fit and setsizehints (autolayout should remain on) viewFramePanel.GetSizer().Fit(viewFramePanel) viewFramePanel.GetSizer().SetSizeHints(viewFramePanel) # now we have to get the top level sizer to do its thing # WORKAROUND - if we don't remove and add, the # viewFrame.GetSizer().Layout() below doesn't do anything. viewFrame.GetSizer().Remove(viewFramePanel) viewFrame.GetSizer().Add(viewFramePanel, 1, wx.EXPAND, 0) # WORKAROUND ENDS viewFrame.GetSizer().Layout() # this should update the minimum size viewFrame.GetSizer().Fit(viewFrame) viewFrame.GetSizer().SetSizeHints(viewFrame) # finally do the actual event setup setup_object_introspection(d3module, viewFrame, objectDict, renderWindow, objectChoice, introspect_button_id) def get_module_icon(): icon = wx.EmptyIcon() icon.CopyFromBitmap( resources.graphics.images.getdevidelogom32x32Bitmap()) return icon def create_module_view_frame_title(d3module): mm = d3module._module_manager return '%s View (%s)' % \ (d3module.__class__.__name__, mm.get_instance_name(d3module)) def instantiate_module_view_frame(d3module, module_manager, frameClass): # instantiate the frame pw = module_manager.get_module_view_parent_window() # name becomes the WM_CLASS under X viewFrame = frameClass(pw, -1, 'dummy', name='DeVIDE') # make sure that it's only hidden when it's closed wx.EVT_CLOSE(viewFrame, lambda e: viewFrame.Show(False)) # set its title (is there not an easier way to get the class name?) viewFrame.SetTitle(create_module_view_frame_title(d3module)) # set its icon! viewFrame.SetIcon(get_module_icon()) return viewFrame def setup_object_introspection(d3module, viewFrame, objectDict, renderWindow, objectChoice, introspect_button_id, ): """Setup all object introspection for standard module views with a choice for object introspection. Call this if you have a wx.Choice and wx.Button ready! viewFrame is the actual window of the module view. objectDict is a dictionary with object name strings as keys and object instances as values. renderWindow is an optional renderWindow that'll be used for updating, pass as None if you don't have this. objectChoice is the object choice widget. objectChoiceId is the event id connected to the objectChoice widget. In order to use this, the module HAS to use the IntrospectModuleMixin. """ # fill out the objectChoice with the object names objectChoice.Clear() for objectName in objectDict.keys(): objectChoice.Append(objectName) # default on first object objectChoice.SetSelection(0) # setup the two default callbacks wx.EVT_BUTTON(viewFrame, introspect_button_id, lambda e: d3module._defaultObjectChoiceCallback( viewFrame, renderWindow, objectChoice, objectDict)) def setup_vtk_object_progress(d3module, obj, progressText): # we DON'T use SetProgressMethod, as the handler object then needs # to store a binding to the vtkProcessObject, which means that # the objects never die... this way, there are no refs # in addition, the AddObserver is the standard way for doing this # we should probably not use ProgressText though... obj.SetProgressText(progressText) mm = d3module._module_manager obj.AddObserver( 'ProgressEvent', lambda vtko, name: mm.generic_progress_callback(vtko, vtko.GetClassName(), vtko.GetProgress(), progressText))
Python
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj from external.vtkPipeline.vtkMethodParser import VtkMethodParser from external.vtkPipeline.vtkPipeline import vtkPipelineBrowser import gen_utils from module_base import ModuleBase import module_utils import module_kits.vtk_kit.utils import os import wx import wx.lib.masked from external.filebrowsebutton import \ FileBrowseButton, FileBrowseButtonWithHistory,DirBrowseButton # so that modules using the file open mixins don't have to import wx # directly. WX_OPEN = wx.OPEN WX_SAVE = wx.SAVE import resources.python.filename_view_module_mixin_frame import re import module_kits from module_kits.wx_kit.python_shell import PythonShell class WindowRenameMixin: """Use this mixin if your class / module binds its main window to self._view_frame (the default) and you want to support renaming your window title. """ def rename(self, new_name): if self._view_frame: self._view_frame.SetTitle(module_utils.create_module_view_frame_title(self)) class IntrospectModuleMixin(object): """Mixin to use for modules that want to make use of the vtkPipeline functionality. Modules that use this as mixin can make use of the vtkObjectConfigure and vtkPipelineConfigure methods to use ConfigVtkObj and vtkPipelineBrowser, respectively. These methods will make sure that you use only one instance of a browser/config class per object. In your close() method, MAKE SURE to call the close method of this Mixin. """ def miscObjectConfigure(self, parentWindow, obj, objDescription=''): """This will instantiate and show a pythonShell with the object that is being examined. If it is called multiple times for the same object, it will merely bring the pertinent window to the top. """ if not hasattr(self, '_python_shells'): self._python_shells = {} if obj not in self._python_shells: icon = module_utils.get_module_icon() self._python_shells[obj] = PythonShell( parentWindow, 'Introspecting %s' % (objDescription,), icon, self._module_manager._devide_app) self._python_shells[obj].inject_locals({'obj' : obj}) self._python_shells[obj].set_statusbar_message( "'obj' is bound to the introspected object") self._python_shells[obj].show() def closeMiscObjectConfigure(self): if hasattr(self, '_python_shells'): for pythonShell in self._python_shells.values(): pythonShell.close() self._python_shells.clear() def vtkObjectConfigure(self, parent, renwin, vtk_obj): """This will instantiate and show only one object config frame per unique vtk_obj (per module instance). If it is called multiple times for the same object, it will merely bring the pertinent window to the top (by show()ing). parent: parent wxWindow derivative. It's important to pass a parent, else the here-created window might never be destroyed. renwin: render window (optionally None) which will be render()ed when changes are made to the vtk object which is being configured. vtk_obj: the object you want to config. """ if not hasattr(self, '_vtk_obj_cfs'): self._vtk_obj_cfs = {} if not self._vtk_obj_cfs.has_key(vtk_obj): self._vtk_obj_cfs[vtk_obj] = ConfigVtkObj(parent, renwin, vtk_obj) self._vtk_obj_cfs[vtk_obj].show() def closeVtkObjectConfigure(self): """Explicitly close() all ConfigVtkObj's that vtk_objct_configure has created. Usually, the ConfigVtkObj windows will be children of some frame, and when that frame gets destroyed, they will be too. However, when this is not the case, you can make use of this method. """ if hasattr(self, '_vtk_obj_cfs'): for cvo in self._vtk_obj_cfs.values(): cvo.close() self._vtk_obj_cfs.clear() def vtkPipelineConfigure(self, parent, renwin, objects=None): """This will instantiate and show only one pipeline config per specified renwin and objects. parent: parent wxWindow derivative. It's important to pass a parent, else the here-created window might never be destroy()ed. renwin: render window (optionally None) which will be render()ed when changes are made AND if objects is None, will be used to determine the pipeline. objects: if you don't want the pipeline to be extracted from the renderwindow, you can specify a sequence of objects to be used as the multiple roots of a partial pipeline. NOTE: renwin and objects can't BOTH be None/empty. """ if not hasattr(self, '_vtk_pipeline_cfs'): self._vtk_pipeline_cfs = {} # create a dictionary key: a tuple containing renwin + objects # (if objects != None) this_key = (renwin,) if objects: this_key = this_key + objects # see if we have this pipeline lying around or not # if not, create it and store if not self._vtk_pipeline_cfs.has_key(this_key): self._vtk_pipeline_cfs[this_key] = vtkPipelineBrowser( parent, renwin, objects) # yay display self._vtk_pipeline_cfs[this_key].show() def closePipelineConfigure(self): """Explicitly close() the pipeline browser of this module. This should happen automatically if a valid 'parent' was passed to vtk_pipeline_configure(), i.e. when the parent dies, the pipeline browser will die too. However, you can use this method to take care of it explicitly. """ if hasattr(self, '_vtk_pipeline_cfs'): for pipeline in self._vtk_pipeline_cfs.values(): pipeline.close() self._vtk_pipeline_cfs.clear() def close(self): """Shut down the whole shebang. All created ConfigVtkObjs and vtkPipelines should be explicitly closed down. """ self.closeMiscObjectConfigure() self.closePipelineConfigure() self.closeVtkObjectConfigure() def _defaultObjectChoiceCallback(self, viewFrame, renderWin, objectChoice, objectDict): """This callack is required for the create_standard_object_introspection method in module_utils. """ objectName = objectChoice.GetStringSelection() if objectDict.has_key(objectName): if hasattr(objectDict[objectName], "GetClassName"): self.vtkObjectConfigure(viewFrame, renderWin, objectDict[objectName]) elif objectDict[objectName]: self.miscObjectConfigure( viewFrame, objectDict[objectName], objectDict[objectName].__class__.__name__) def _defaultPipelineCallback(self, viewFrame, renderWin, objectDict): """This callack is required for the create_standard_object_introspection method in module_utils. """ # check that all objects are VTK objects (probably not necessary) objects1 = objectDict.values() objects = tuple([object for object in objects1 if hasattr(object, 'GetClassName')]) if len(objects) > 0: self.vtkPipelineConfigure(viewFrame, renderWin, objects) IntrospectModuleMixin = IntrospectModuleMixin vtkPipelineConfigModuleMixin = IntrospectModuleMixin # ---------------------------------------------------------------------------- class FileOpenDialogModuleMixin(object): """Module mixin to make use of file open dialog.""" def filename_browse(self, parent, message, wildcard, style=wx.OPEN): """Utility method to make use of wxFileDialog. This function will open up exactly one dialog per 'message' and this dialog won't be destroyed. This persistence makes sure that the dialog retains its previous settings and also that there is less overhead for subsequent creations. The dialog will be a child of 'parent', so when parent is destroyed, this dialog will be too. If style has wx.MULTIPLE, this method will return a list of complete file paths. """ if not hasattr(self, '_fo_dlgs'): self._fo_dlgs = {} if not self._fo_dlgs.has_key(message): self._fo_dlgs[message] = wx.FileDialog(parent, message, "", "", wildcard, style) if self._fo_dlgs[message].ShowModal() == wx.ID_OK: if style & wx.MULTIPLE: return self._fo_dlgs[message].GetPaths() else: return self._fo_dlgs[message].GetPath() else: return None filenameBrowse = filename_browse def closeFilenameBrowse(self): """Use this method to close all created dialogs explicitly. This should be taken care of automatically if you've passed in a valid 'parent'. Use this method in cases where this was not possible. """ if hasattr(self, '_fo_dlgs'): for key in self._fo_dlgs.keys(): self._fo_dlgs[key].Destroy() self._fo_dlgs.clear() def dirnameBrowse(self, parent, message, default_path=""): """Utility method to make use of wxDirDialog. This function will open up exactly one dialog per 'message' and this dialog won't be destroyed. This function is more or less identical to fn_browse(). """ if not hasattr(self, '_do_dlgs'): self._do_dlgs = {} if not self._do_dlgs.has_key(message): self._do_dlgs[message] = wx.DirDialog(parent, message, default_path) if self._do_dlgs[message].ShowModal() == wx.ID_OK: return self._do_dlgs[message].GetPath() else: return None FileOpenDialogModuleMixin = FileOpenDialogModuleMixin # ---------------------------------------------------------------------------- class FilenameViewModuleMixin(FileOpenDialogModuleMixin, vtkPipelineConfigModuleMixin): """Mixin class for those modules that only need a filename to operate. Please call __init__() and close() at the appropriate times from your module class. Call _createViewFrame() at the end of your __init__ and Show(1) the resulting frame. As with most Mixins, remember to call the close() method of this one at the end of your object. """ def __init__(self, browseMsg="Select a filename", fileWildcard= "VTK data (*.vtk)|*.vtk|All files (*)|*", objectDict=None, fileOpen=True): self._browse_msg = browseMsg self._file_wildcard = fileWildcard self._object_dict = objectDict self._file_open = fileOpen self._view_frame = None def close(self): del self._object_dict vtkPipelineConfigModuleMixin.close(self) if self._view_frame is not None: self._view_frame.Destroy() del self._view_frame def _create_view_frame(self): """By default, this will be a File Open dialog. If fileOpen is False, it will be a File Save dialog. """ if not self._module_manager._devide_app.view_mode: raise RuntimeError( 'Eror calling view-dependent createViewFrame() in ' 'backend-type DeVIDE.') self._view_frame = module_utils.instantiate_module_view_frame( self, self._module_manager, resources.python.filename_view_module_mixin_frame.\ FilenameViewModuleMixinFrame) wx.EVT_BUTTON(self._view_frame, self._view_frame.browseButtonId, lambda e: self.browseButtonCallback(self._browse_msg, self._file_wildcard)) if self._object_dict != None: module_utils.create_standard_object_introspection( self, self._view_frame, self._view_frame.viewFramePanel, self._object_dict, None) # new style standard ECAS buttons module_utils.create_eoca_buttons(self, self._view_frame, self._view_frame.viewFramePanel) # following module_base convention self.view_initialised = True def _getViewFrameFilename(self): return self._view_frame.filenameText.GetValue() def _setViewFrameFilename(self, filename): self._view_frame.filenameText.SetValue(filename) def browseButtonCallback(self, browse_msg="Select a filename", fileWildcard= "VTK data (*.vtk)|*.vtk|All files (*)|*"): if self._file_open == 1: path = self.filenameBrowse( self._view_frame, browse_msg, fileWildcard) else: path = self.filenameBrowse( self._view_frame, browse_msg, fileWildcard, style=wx.SAVE) if path != None: self._view_frame.filenameText.SetValue(path) def view(self): if self._view_frame is None: self._create_view_frame() self._module_manager.sync_module_view_with_logic(self) # and show the UI self._view_frame.Show(True) self._view_frame.Raise() # ---------------------------------------------------------------------------- class ColourDialogMixin(object): def __init__(self, parent): ccd = wx.ColourData() # often-used BONE custom colour ccd.SetCustomColour(0,wx.Colour(255, 239, 219)) # we want the detailed dialog under windows ccd.SetChooseFull(True) # create the dialog self._colourDialog = wx.ColourDialog(parent, ccd) def close(self): # destroy the dialog self._colourDialog.Destroy() # remove all references del self._colourDialog def getColourDialogColour(self): self._colourDialog.Show(True) self._colourDialog.Raise() if self._colourDialog.ShowModal() == wx.ID_OK: colour = self._colourDialog.GetColourData().GetColour() return tuple([c / 255.0 for c in (colour.Red(), colour.Green(), colour.Blue())]) else: return None def setColourDialogColour(self, normalisedRGBTuple): """This is the default colour we'll begin with. """ R,G,B = [t * 255.0 for t in normalisedRGBTuple] self._colourDialog.GetColourData().SetColour(wx.Colour(R, G, B)) # ---------------------------------------------------------------------------- class NoConfigModuleMixin(IntrospectModuleMixin, WindowRenameMixin): """Mixin class for those modules that don't make use of any user-config views. Please call __init__() and close() at the appropriate times from your module class. Call _create_view_frame() at the end of your __init__ and Show(1) the resulting frame. As with most Mixins, remember to call the close() method of this one at the end of your object. """ def __init__(self, object_dict=None): self._view_frame = None self._object_dict = object_dict def close(self): IntrospectModuleMixin.close(self) if self._view_frame is not None: self._view_frame.Destroy() del self._view_frame def _create_view_frame(self): """This will create the self._view_frame for this module. objectDict is a dictionary with VTK object descriptions as keys and the actual corresponding instances as values. If you specify objectDict as none, the introspection controls won't get added. """ parent_window = self._module_manager.get_module_view_parent_window() viewFrame = wx.Frame(parent_window, -1, module_utils.create_module_view_frame_title(self)) viewFrame.viewFramePanel = wx.Panel(viewFrame, -1) viewFramePanelSizer = wx.BoxSizer(wx.VERTICAL) # make sure there's a 7px border at the top # FIXME: changed 10, 7 to tuple for wxPython 2.6 viewFramePanelSizer.Add((10, 7), 0, wx.EXPAND) viewFrame.viewFramePanel.SetAutoLayout(True) viewFrame.viewFramePanel.SetSizer(viewFramePanelSizer) viewFrameSizer = wx.BoxSizer(wx.VERTICAL) viewFrameSizer.Add(viewFrame.viewFramePanel, 1, wx.EXPAND, 0) viewFrame.SetAutoLayout(True) viewFrame.SetSizer(viewFrameSizer) if self._object_dict != None: module_utils.create_standard_object_introspection( self, viewFrame, viewFrame.viewFramePanel, self._object_dict, None) module_utils.create_eoca_buttons(self, viewFrame, viewFrame.viewFramePanel) # make sure that a close of that window does the right thing wx.EVT_CLOSE(viewFrame, lambda e: viewFrame.Show(False)) # set cute icon viewFrame.SetIcon(module_utils.get_module_icon()) # follow ModuleBase convention to indicate that view is # available self.view_initialised = True self._view_frame = viewFrame return viewFrame _createWindow = _create_view_frame def view(self): if self._view_frame is None: self._create_view_frame() self._module_manager.sync_module_view_with_logic(self) # and show the UI self._view_frame.Show(True) self._view_frame.Raise() def config_to_logic(self): pass def logic_to_config(self): pass def config_to_view(self): pass def view_to_config(self): pass class ScriptedConfigModuleMixin(IntrospectModuleMixin, WindowRenameMixin): """ configList: list of tuples, where each tuple is (name/label, destinationConfigVar, typeDescription, widgetType, toolTip, optional data) e.g. ('Initial Distance', 'initialDistance', 'base:float', 'text', 'A tooltip for the initial distance text thingy.') typeDescription: basetype:subtype basetype: base, tuple, list (list not implemented yet), display_only subtype: in the case of scalar, the actual cast, e.g. float or int in the case of tuple, the actual cast followed by a comma and the number of elements. in the case of display_only, leave empty. widgetType: text, static_text - primarily for display_only use for things you want to give feedback on but not integrate with config tupleText - your type spec HAS to be a tuple; text boxes are created in a horizontal sizer checkbox, radiobox - optional data is a list of choices; returns integer 0-based index (so use base:int) choice - optional data is a list of choices, filebrowser - optional data is a dict with fileMask, fileMode and defaultExt keys, for example: {'fileMode' : wx.SAVE, 'fileMask' : 'Matlab text file (*.txt)|*.txt|All files (*.*)|*.*', 'defaultExt' : '.txt'}) dirbrowser, maskedText - optional data is the kwargs dict for MaskedTextCtrl instantiation, e.g.: {'mask': '\(#{3}, #{3}, #{3}\)', 'formatcodes':'F-_'} NOTE: this mixin assumes that your module is derived from module_base, e.g. class yourModule(ScriptedConfigModuleMixin, ModuleBase): It's important that ModuleBase comes after due to the new-style method resolution order. """ def __init__(self, configList, object_dict=None): self._view_frame = None self._configList = configList self._widgets = {} self._object_dict = object_dict def close(self): IntrospectModuleMixin.close(self) if self._view_frame is not None: self._view_frame.Destroy() del self._view_frame def _create_view_frame(self): parentWindow = self._module_manager.get_module_view_parent_window() import resources.python.defaultModuleViewFrame reload(resources.python.defaultModuleViewFrame) dMVF = resources.python.defaultModuleViewFrame.defaultModuleViewFrame viewFrame = module_utils.instantiate_module_view_frame( self, self._module_manager, dMVF) # this viewFrame doesn't have the 7-sizer yet sizer7 = wx.BoxSizer(wx.HORIZONTAL) viewFrame.viewFramePanel.GetSizer().Add(sizer7, 1, wx.ALL|wx.EXPAND, 7) # now let's add the wxGridSizer # as many rows as there are tuples in configList, 2 columns, # 7 pixels vgap, 4 pixels hgap gridSizer = wx.FlexGridSizer(len(self._configList), 2, 7, 4) # maybe after we've added everything? gridSizer.AddGrowableCol(1) panel = viewFrame.viewFramePanel for configTuple in self._configList: label = wx.StaticText(panel, -1, configTuple[0]) gridSizer.Add(label, 0, wx.ALIGN_CENTER_VERTICAL, 0) widget = None if configTuple[3] == 'static_text': widget = wx.StaticText(panel, -1, "") elif configTuple[3] == 'text': widget = wx.TextCtrl(panel, -1, "") elif configTuple[3] == 'tupleText': # find out how many elements typeD = configTuple[2] castString, numString = typeD.split(':')[1].split(',') num = int(numString) textWidgets = [] twSizer = wx.BoxSizer(wx.HORIZONTAL) for i in range(num): textWidgets.append(wx.TextCtrl(panel, -1, "")) twSizer.Add(textWidgets[-1], 0, wx.ALIGN_CENTER_VERTICAL, 1) if i < num - 1: twSizer.Add(wx.StaticText(panel, -1, ','), 0, wx.RIGHT, border=4) widget = None widgets = textWidgets widgetsSizer = twSizer elif configTuple[3] == 'maskedText': widget = wx.lib.masked.TextCtrl(panel, -1, '', **configTuple[5]) elif configTuple[3] == 'checkbox': # checkbox widget = wx.CheckBox(panel, -1, "") elif configTuple[3] == 'radiobox': # radiobox # configTuple[5] has to be a list of strings widget = wx.RadioBox(panel, -1, "", choices=configTuple[5]) elif configTuple[3] == 'choice': # choice widget = wx.Choice(panel, -1) # in this case, configTuple[5] has to be a list of strings for cString in configTuple[5]: widget.Append(cString) elif configTuple[3] == 'filebrowser': # filebrowser widget = FileBrowseButton( panel, -1, fileMask=configTuple[5]['fileMask'], fileMode=configTuple[5]['fileMode'], labelText=None, toolTip=configTuple[4]) else: # dirbrowser widget = DirBrowseButton( panel, -1, labelText=None, toolTip=configTuple[4]) if widget: if len(configTuple[4]) > 0: widget.SetToolTip(wx.ToolTip(configTuple[4])) gridSizer.Add(widget, 0, wx.EXPAND, 0) self._widgets[configTuple[0:5]] = widget elif len(widgets) > 0: if len(configTuple[4]) > 0: for w in widgets: w.SetToolTip(wx.ToolTip(configTuple[4])) gridSizer.Add(widgetsSizer, 0, wx.EXPAND, 0) self._widgets[configTuple[0:5]] = widgets sizer7.Add(gridSizer, 1, wx.EXPAND, 0) if self._object_dict != None: module_utils.create_standard_object_introspection( self, viewFrame, viewFrame.viewFramePanel, self._object_dict, None) module_utils.create_eoca_buttons(self, viewFrame, viewFrame.viewFramePanel) # following ModuleBase convention to indicate that view is # available. self.view_initialised = True self._view_frame = viewFrame return viewFrame # legacy _createWindow = _create_view_frame def _getWidget(self, configTupleIndex): """Returns widget(s) given the index of the relevant configTuple in the configList structure. """ return self._widgets[self._configList[configTupleIndex][0:5]] def view_to_config(self): for configTuple in self._configList: widget = self._widgets[configTuple[0:5]] typeD = configTuple[2] # some widgets are only for display, we won't process their values if typeD.startswith('display_only'): continue if configTuple[3] == 'choice': wv = widget.GetStringSelection() # if the user has asked for a base:int, we give her # the index of the choice that was made; otherwise # we return the string on the choice at that position if typeD.startswith('base:'): castString = typeD.split(':')[1] if castString == 'int': wv = widget.GetSelection() elif configTuple[3] == 'radiobox': wv = widget.GetSelection() elif configTuple[3] == 'tupleText': widgets = widget wv = [] for w in widgets: wv.append(w.GetValue()) wv = ','.join(wv) elif configTuple[3] == 'filebrowser': # get value from the widget wv = widget.GetValue() # if no extension has been supplied, but the programmer # has specified a default, append this. if not os.path.splitext(wv)[1]: wv += configTuple[5].get('defaultExt') else: wv = widget.GetValue() if typeD.startswith('base:'): # we're only supporting 'text' widget so far castString = typeD.split(':')[1] try: val = eval('%s(wv)' % (castString,)) except ValueError: # revert to default value val = eval('self._config.%s' % (configTuple[1],)) widget.SetValue(str(val)) elif typeD.startswith('tuple:'): # e.g. tuple:float,3 castString, numString = typeD.split(':')[1].split(',') val = gen_utils.textToTypeTuple( wv, eval('self._config.%s' % (configTuple[1],)), int(numString), eval(castString)) if configTuple[3] == 'tupleText': for i in range(len(widgets)): widgets[i].SetValue(str(val[i])) else: widget.SetValue(str(val)) else: raise ValueError, 'Invalid typeDescription.' setattr(self._config, configTuple[1], val) def config_to_view(self): # we have to do explicit casting for floats with %f, instead of just # using str(), as some filters return parameters as C++ float # (i.e. not doubles), and then str() shows us strings that are far too # long for configTuple in self._configList: typeD = configTuple[2] # some widgets are only for display, we won't process their values if typeD.startswith('display_only'): continue widget = self._widgets[configTuple[0:5]] val = getattr(self._config, configTuple[1]) if configTuple[3] == 'text' or configTuple[3] == 'maskedText': if typeD.startswith('base:'): castString = typeD.split(':')[1] if castString == 'float': widget.SetValue('%g' % (val,)) else: widget.SetValue(str(val)) else: # so this is a tuple # e.g. tuple:float,3 castString, numString = typeD.split(':')[1].split(',') if castString == 'float': num = int(numString) formatString = '(%s)' % ((num - 1) * '%g, ' + '%g') widget.SetValue(formatString % val) else: # some other tuple widget.SetValue(str(val)) elif configTuple[3] == 'tupleText': # for a tupleText, widget is a list widgets = widget if typeD.startswith('tuple'): # so this is a tuple # e.g. tuple:float,3 castString, numString = typeD.split(':')[1].split(',') num = int(numString) t = tuple(val) for i in range(num): if castString == 'float': widgets[i].SetValue('%g' % (t[i],)) else: widgets[i].SetValue(str(t[i])) elif configTuple[3] == 'checkbox': widget.SetValue(bool(val)) elif configTuple[3] == 'radiobox': widget.SetSelection(int(val)) elif configTuple[3] == 'filebrowser': widget.SetValue(str(val)) elif configTuple[3] == 'dirbrowser': widget.SetValue(str(val)) elif configTuple[3] == 'choice': # choice # if a choice has a type of 'int', it works with the index # of the selection. In all other cases, the actual # string selection is used setChoiceWithString = True if typeD.startswith('base:'): castString = typeD.split(':')[1] if castString == 'int': setChoiceWithString = False if setChoiceWithString: widget.SetStringSelection(str(val)) else: widget.SetSelection(int(val)) def view(self): if self._view_frame is None: self._create_view_frame() self._module_manager.sync_module_view_with_logic(self) # and show the UI self._view_frame.Show(True) self._view_frame.Raise()
Python
# this is (possibly broken) code to perform a marker-based watershed # segmentation on a mesh by making use of a pre-segmentation # modification of curvature homotopy # test this on some synthetic data (cube with markers on all six faces) # before you use it for anything serious. # IDEA: # use vtkPolyDataConnectivityFilter with minima as seed points from module_base import ModuleBase from module_mixins import NoConfigModuleMixin from wxPython.wx import * import vtk class testModule3(ModuleBase, NoConfigModuleMixin): """Module to prototype modification of homotopy and subsequent watershedding of curvature-on-surface image. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) mm = self._module_manager self._cleaner = vtk.vtkCleanPolyData() self._tf = vtk.vtkTriangleFilter() self._tf.SetInput(self._cleaner.GetOutput()) self._wspdf = vtk.vtkWindowedSincPolyDataFilter() #self._wspdf.SetNumberOfIterations(50) self._wspdf.SetInput(self._tf.GetOutput()) self._wspdf.SetProgressText('smoothing') self._wspdf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._wspdf)) self._cleaner2 = vtk.vtkCleanPolyData() self._cleaner2.SetInput(self._wspdf.GetOutput()) self._curvatures = vtk.vtkCurvatures() self._curvatures.SetCurvatureTypeToMean() self._curvatures.SetInput(self._cleaner2.GetOutput()) self._tf.SetProgressText('triangulating') self._tf.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._tf)) self._curvatures.SetProgressText('calculating curvatures') self._curvatures.SetProgressMethod(lambda s=self, mm=mm: mm.vtk_progress_cb(s._curvatures)) self._inputFilter = self._tf self._inputPoints = None self._inputPointsOID = None self._giaGlenoid = None self._outsidePoints = None self._outputPolyDataARB = vtk.vtkPolyData() self._outputPolyDataHM = vtk.vtkPolyData() self._createViewFrame('Test Module View', {'vtkTriangleFilter' : self._tf, 'vtkCurvatures' : self._curvatures}) self._viewFrame.Show(True) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._cleaner del self._cleaner2 del self._wspdf del self._curvatures del self._tf del self._inputPoints del self._outputPolyDataARB del self._outputPolyDataHM def get_input_descriptions(self): return ('vtkPolyData', 'Watershed minima') def set_input(self, idx, inputStream): if idx == 0: self._inputFilter.SetInput(inputStream) else: if inputStream is not self._inputPoints: if self._inputPoints: self._inputPoints.removeObserver(self._inputPointsOID) if inputStream: self._inputPointsOID = inputStream.addObserver( self._inputPointsObserver) self._inputPoints = inputStream # initial update self._inputPointsObserver(None) def get_output_descriptions(self): return ('ARB PolyData output', 'Homotopically modified polydata') def get_output(self, idx): if idx == 0: return self._outputPolyDataARB else: return self._outputPolyDataHM def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): if self._inputFilter.GetInput() and \ self._outsidePoints and self._giaGlenoid: self._curvatures.Update() # vtkCurvatures has added a mean curvature array to the # pointData of the output polydata pd = self._curvatures.GetOutput() # make a deep copy of the data that we can work with tempPd1 = vtk.vtkPolyData() tempPd1.DeepCopy(self._curvatures.GetOutput()) # and now we have to unsign it! tempPd1Scalars = tempPd1.GetPointData().GetScalars() for i in xrange(tempPd1Scalars.GetNumberOfTuples()): a = tempPd1Scalars.GetTuple1(i) tempPd1Scalars.SetTuple1(i, float(abs(a))) self._outputPolyDataARB.DeepCopy(tempPd1) # BUILDING NEIGHBOUR MAP #################################### # iterate through all points numPoints = tempPd1.GetNumberOfPoints() neighbourMap = [[] for i in range(numPoints)] cellIdList = vtk.vtkIdList() pointIdList = vtk.vtkIdList() for ptId in xrange(numPoints): # this has to be first neighbourMap[ptId].append(ptId) tempPd1.GetPointCells(ptId, cellIdList) # we now have all edges meeting at point i for cellIdListIdx in range(cellIdList.GetNumberOfIds()): edgeId = cellIdList.GetId(cellIdListIdx) tempPd1.GetCellPoints(edgeId, pointIdList) # there have to be two points per edge, # one if which is the centre-point itself # FIXME: we should check, cells aren't LIMITED to two # points, but could for instance be a longer line-segment # or a quad or somesuch for pointIdListIdx in range(pointIdList.GetNumberOfIds()): tempPtId = pointIdList.GetId(pointIdListIdx) if tempPtId not in neighbourMap[ptId]: neighbourMap[ptId].append(tempPtId) #print neighbourMap[ptId] if ptId % (numPoints / 20) == 0: self._module_manager.setProgress(100.0 * ptId / numPoints, "Building neighbour map") self._module_manager.setProgress(100.0, "Done building neighbour map") # DONE BUILDING NEIGBOUR MAP ################################ # BUILDING SEED IMAGE ####################################### # now let's build the seed image # wherever we want to enforce minima, the seed image # should be equal to the lowest value of the mask image # everywhere else it should be the maximum value of the mask # image cMin, cMax = tempPd1.GetScalarRange() print "range: %d - %d" % (cMin, cMax) seedPd = vtk.vtkPolyData() # first make a copy of the complete PolyData seedPd.DeepCopy(tempPd1) # now change EVERYTHING to the maximum value print seedPd.GetPointData().GetScalars().GetName() # we know that the active scalars thingy has only one component, # namely Mean_Curvature - set it all to MAX seedPd.GetPointData().GetScalars().FillComponent(0, cMax) # now find the minima and set them too gPtId = seedPd.FindPoint(self._giaGlenoid) seedPd.GetPointData().GetScalars().SetTuple1(gPtId, cMin) for outsidePoint in self._outsidePoints: oPtId = seedPd.FindPoint(outsidePoint) seedPd.GetPointData().GetScalars().SetTuple1(oPtId, cMin) # remember vtkDataArray: array of tuples, each tuple made up # of n components # DONE BUILDING SEED IMAGE ################################### # MODIFY MASK IMAGE ########################################## # make sure that the minima as indicated by the user are cMin # in the mask image! gPtId = tempPd1.FindPoint(self._giaGlenoid) tempPd1.GetPointData().GetScalars().SetTuple1(gPtId, cMin) for outsidePoint in self._outsidePoints: oPtId = tempPd1.FindPoint(outsidePoint) tempPd1.GetPointData().GetScalars().SetTuple1(oPtId, cMin) # DONE MODIFYING MASK IMAGE ################################## # BEGIN erosion + supremum (modification of image homotopy) newSeedPd = vtk.vtkPolyData() newSeedPd.DeepCopy(seedPd) # get out some temporary variables tempPd1Scalars = tempPd1.GetPointData().GetScalars() seedPdScalars = seedPd.GetPointData().GetScalars() newSeedPdScalars = newSeedPd.GetPointData().GetScalars() stable = False iteration = 0 while not stable: for nbh in neighbourMap: # by definition, EACH position in neighbourmap must have # at least ONE (1) ptId # create list with corresponding curvatures nbhC = [seedPdScalars.GetTuple1(ptId) for ptId in nbh] # sort it nbhC.sort() # replace the centre point in newSeedPd with the lowest val newSeedPdScalars.SetTuple1(nbh[0], nbhC[0]) # now put result of supremum of newSeed and tempPd1 (the mask) # directly into seedPd - the loop can then continue # in theory, these two polydatas have identical pointdata # go through them, constructing newSeedPdScalars # while we're iterating through this loop, also check if # newSeedPdScalars is identical to seedPdScalars stable = True for i in xrange(newSeedPdScalars.GetNumberOfTuples()): a = newSeedPdScalars.GetTuple1(i) b = tempPd1Scalars.GetTuple1(i) c = [b, a][bool(a > b)] if stable and c != seedPdScalars.GetTuple1(i): # we only check if stable == True # if a single scalar is different, stable becomes # false and we'll never have to check again stable = False print "unstable on point %d" % (i) # stuff the result directly into seedPdScalars, ready # for the next iteration seedPdScalars.SetTuple1(i, c) self._module_manager.setProgress(iteration / 500.0 * 100.0, "Homotopic modification") print "iteration %d done" % (iteration) iteration += 1 #if iteration == 2: # stable = True # seedPd is the output of the homotopic modification # END of erosion + supremum # BEGIN watershed pointLabels = [-1 for i in xrange(seedPd.GetNumberOfPoints())] # mark all minima as separate regions gPtId = seedPd.FindPoint(self._giaGlenoid) pointLabels[gPtId] = 1 i = 1 for outsidePoint in self._outsidePoints: oPtId = seedPd.FindPoint(outsidePoint) pointLabels[oPtId] = i * 200 i += 1 # now, iterate through all non-marked points seedPdScalars = seedPd.GetPointData().GetScalars() for ptId in xrange(seedPd.GetNumberOfPoints()): if pointLabels[ptId] == -1: print "starting ws with ptId %d" % (ptId) pathDone = False # this will contain all the pointIds we walk along, # starting with ptId (new path!) thePath = [ptId] while not pathDone: # now search for a neighbour with the lowest curvature # but also lower than ptId itself nbh = neighbourMap[thePath[-1]] nbhC = [seedPdScalars.GetTuple1(pi) for pi in nbh] cmi = 0 # curvature minimum index cmi # remember that in the neighbourhood map # the "centre" point is always first cms = nbhC[cmi] for ci in range(len(nbhC)): # contour index ci if nbhC[ci] < cms: cmi = ci cms = nbhC[ci] if cmi != 0: # this means we found a point we can move on to if pointLabels[nbh[cmi]] != -1: # if this is a labeled point, we know which # basin thePath belongs to theLabel = pointLabels[nbh[cmi]] for newLabelPtId in thePath: pointLabels[newLabelPtId] = theLabel print "found new path: %d (%d)" % \ (theLabel, len(thePath)) # and our loop is done pathDone = True else: # this is not a labeled point, which means # we just add it to our path thePath.append(nbh[cmi]) # END if cmi != 0 else: # we couldn't find any point lower than us! # let's eat as many plateau points as we can, # until we reach a lower-labeled point # c0 is the "current" curvature plateau, plateauNeighbours, plateauLabel = \ self._getPlateau(nbh[0], neighbourMap, seedPdScalars, pointLabels) if plateauLabel != -1: # this means the whole plateau is with a basin for i in plateau: thePath.append(i) for newLabelPtId in thePath: pointLabels[newLabelPtId] = plateauLabel print "found new path: %d (%d)" % \ (plateauLabel, len(thePath)) # and our loop is done pathDone = True elif not plateauNeighbours: # i.e. we have a single point or a floating # plateau... print "floating plateau!" pathDone = True else: # now look for the lowest neighbour # (c0 is the plateau scalar) minScalar = cms minId = -1 for nId in plateauNeighbours: si = seedPdScalars.GetTuple1(nId) if si < minScalar: minId = nId minScalar = si if minId != -1: # this means we found the smallest # neighbour # everything on the plateau gets added to # the path for i in plateau: thePath.append(i) if pointLabels[minId] != -1: # if this is a labeled point, we know # which basin thePath belongs to theLabel = pointLabels[minId] for newLabelPtId in thePath: pointLabels[newLabelPtId] = \ theLabel print "found new path: %d (%d)" % \ (theLabel, len(thePath)) # and our loop is done pathDone = True else: # this is not a labeled point, which # means we just add it to our path thePath.append(minId) else: print "HELP! - we found a minimum plateau!" # we're done with our little path walking... now we have to assign # our watershedded thingy to the output data self._outputPolyDataHM.DeepCopy(seedPd) for ptId in xrange(len(pointLabels)): self._outputPolyDataHM.GetPointData().GetScalars().SetTuple1( ptId, pointLabels[ptId]) def _getPlateau(self, initPt, neighbourMap, scalars, pointLabels): """Grow outwards from ptId nbh[0] and include all points with the same scalar value. return 2 lists: one with plateau ptIds and one with ALL the neighbour Ids. """ # by definition, the plateau will contain at least the initial point plateau = [initPt] plateauNeighbours = [] plateauLabel = -1 # we're going to use this to check VERY quickly whether we've # already stored a point donePoints = [False for i in xrange(len(neighbourMap))] donePoints[initPt] = True # and this is the scalar value of the plateau initScalar = scalars.GetTuple1(initPt) # setup for loop currentNeighbourPts = neighbourMap[initPt] # everything in currentNeighbourPts that has equal scalar # gets added to plateau while currentNeighbourPts: newNeighbourPts = [] for npt in currentNeighbourPts: if not donePoints[npt]: ns = scalars.GetTuple1(npt) if ns == initScalar: plateau.append(npt) # it could be that a point in our plateau is already # labeled - check for this if pointLabels[npt] != -1: plateauLabel = pointLabels[npt] else: plateauNeighbours.append(npt) donePoints[npt] = True # we've added a new point, now we need to get # its neighbours as well for i in neighbourMap[npt]: newNeighbourPts.append(i) currentNeighbourPts = newNeighbourPts return (plateau, plateauNeighbours, plateauLabel) def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise() def _inputPointsObserver(self, obj): # extract a list from the input points if self._inputPoints: # extract the two points with labels 'GIA Glenoid' # and 'GIA Humerus' giaGlenoid = [i['world'] for i in self._inputPoints if i['name'] == 'GIA Glenoid'] outsidePoints = [i['world'] for i in self._inputPoints \ if i['name'] == 'Outside'] if giaGlenoid and outsidePoints: # we only apply these points to our internal parameters # if they're valid and if they're new self._giaGlenoid = giaGlenoid[0] self._outsidePoints = outsidePoints
Python
import itk import module_kits.itk_kit as itk_kit from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import math class BSplineRegistration(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._create_pipeline() self._view_frame = None def _create_pipeline(self): interpolator = itk.LinearInterpolateImageFunction\ [itk.Image.F3, itk.D].New() metric = itk.MeanSquaresImageToImageMetric\ [itk.Image.F3, itk.Image.F3].New() optimizer = itk.LBFGSOptimizer.New() transform = itk.BSplineDeformableTransform[itk.D, 3, 3].New() r = itk.ImageRegistrationMethod[itk.Image.F3, itk.Image.F3].\ New( Interpolator=interpolator.GetPointer(), Metric=metric.GetPointer(), Optimizer=optimizer.GetPointer(), Transform=transform.GetPointer()) self._interpolator = interpolator self._metric = metric self._optimizer = optimizer self._transform = transform self._registration = r itk_kit.utils.setupITKObjectProgress( self, self._registration, 'BSpline Registration', 'Performing registration') itk_kit.utils.setupITKObjectProgress( self, self._optimizer, 'LBFGSOptimizer', 'Optimizing') def get_input_descriptions(self): return ('Fixed image', 'Moved image') def set_input(self, idx, input_stream): if idx == 0: self._fixed_image = input_stream self._registration.SetFixedImage(input_stream) else: self._moving_image = input_stream self._registration.SetMovingImage(input_stream) def get_output_descriptions(self): return ('BSpline Transform',) def get_output(self, idx): return self._registration.GetTransform() def execute_module(self): # itk.Size[3]() # itk.ImageRegion[3]() # we want a 1 node border on low x,y,z and a 2 node border on # high x,y,z; so if we want a bspline grid of 5x5x5, we need a # bspline region of 8x8x8 grid_size_on_image = [5,5,5] fi_region = self._fixed_image.GetBufferedRegion() self._registration.SetFixedImageRegion(fi_region) fi_size1 = fi_region.GetSize() fi_size = [fi_size1.GetElement(i) for i in range(3)] spacing = 3 * [0] origin = 3 * [0] for i in range(3): spacing[i] = self._fixed_image.GetSpacing().GetElement(i) * \ math.floor( (fi_size[i] - 1) / float(grid_size_on_image[i] - 1)) origin[i] = self._fixed_image.GetOrigin().GetElement(i) \ - spacing[i] self._transform.SetGridSpacing(spacing) self._transform.SetGridOrigin(origin) bspline_region = itk.ImageRegion[3]() bspline_region.SetSize([i + 3 for i in grid_size_on_image]) self._transform.SetGridRegion(bspline_region) num_params = self._transform.GetNumberOfParameters() params = itk.Array[itk.D](num_params) params.Fill(0.0) self._transform.SetParameters(params) self._registration.SetInitialTransformParameters( self._transform.GetParameters()) self._optimizer.SetGradientConvergenceTolerance( 0.05 ) self._optimizer.SetLineSearchAccuracy( 0.9 ) self._optimizer.SetDefaultStepLength( 1.5 ) self._optimizer.TraceOn() self._optimizer.SetMaximumNumberOfFunctionEvaluations( 1000 ) self._registration.Update() def logic_to_config(self): pass def config_to_logic(self): pass
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class ivWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkIVWriter() # sorry about this, but the files get REALLY big if we write them # in ASCII - I'll make this a gui option later. #self._writer.SetFileTypeToBinary() # following is the standard way of connecting up the devide progress # callback to a VTK object; you should do this for all objects in module_utils.setup_vtk_object_progress( self, self._writer, 'Writing polydata to Inventor Viewer format') # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'InventorViewer data (*.iv)|*.iv|All files (*)|*', {'vtkIVWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
# $Id: vtpWRT.py 2401 2006-12-20 20:29:15Z cpbotha $ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import types class MatlabPointsWriter(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'MATLAB file (*.m)|*.m|All files (*)|*', {'Module (self)': self}, fileOpen=False) # set up some defaults self._config.filename = '' self._input_points = None self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('DeVIDE points',) def set_input(self, idx, input_stream): self._input_points = input_stream def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if self._input_points and hasattr(self._input_points, 'devideType') \ and self._input_points.devideType == 'namedPoints' \ and self._config.filename: fh = file(self._config.filename, 'w') for p in self._input_points: tup = (p['name'],) + tuple(p['world']) fh.write('%s = [%f %f %f];\n' % tup) fh.close()
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class vtiWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkXMLImageDataWriter() # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'VTK Image Data (*.vti)|*.vti|All files (*)|*', {'vtkXMLImageDataWriter': self._writer}, fileOpen=False) module_utils.setup_vtk_object_progress( self, self._writer, 'Writing VTK ImageData') self._writer.SetDataModeToBinary() # set up some defaults self._config.filename = '' self._module_manager.sync_module_logic_with_config(self) def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()) and self._writer.GetInput(): self._writer.GetInput().UpdateInformation() self._writer.GetInput().SetUpdateExtentToWholeExtent() self._writer.GetInput().Update() self._writer.Write() def streaming_execute_module(self): if len(self._writer.GetFileName()) and self._writer.GetInput(): sp = self._module_manager.get_app_main_config().streaming_pieces self._writer.SetNumberOfPieces(sp) self._writer.Write()
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class vtkStructPtsWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkStructuredPointsWriter() module_utils.setup_vtk_object_progress( self, self._writer, 'Writing vtk structured points data') # we do this to save space - if you're going to be transporting files # to other architectures, change this to ASCII # we've set this back to ASCII. Seems the binary mode is screwed # for some files and manages to produce corrupt files that segfault # VTK on Windows. self._writer.SetFileTypeToASCII() # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'VTK data (*.vtk)|*.vtk|All files (*)|*', {'vtkStructuredPointsWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkStructuredPoints',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
class batchConverter: kits = ['vtk_kit', 'wx_kit'] cats = ['Readers','Writers','Converters'] keywords = ['batch','convert','read','write','vti','mha','gipl'] help = """Batch converts image volume files from one type to another. Source and target types can be VTK ImageData (.vti), MetaImage (.mha), or Guys Image Processing Lab (.gipl). All the files in the specified directory matching the given source extension are converted. The user may specify whether source files should be deleted or target files should be automatically overwritten (be careful with these settings!) Known bug: writing to GIPL (forced binary uchar) will result in a thrown exception. Circumvent this by first casting to binary uchar when writing to VTI, and then converting to GIPL in a second pass. (Module by Francois Malan)""" class cptBrepWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes polydata to disc in the format required by the Closest Point Transform (CPT) driver software. Input data is put through a triangle filter first, as that is what the CPT requires. See the <a href="http://www.acm.caltech.edu/~seanm/projects/cpt/cpt.html">CPT home page</a> for more information about the algorithm and the software. """ class DICOMWriter: kits = ['vtk_kit', 'gdcm_kit'] cats = ['Writers', 'Medical', 'DICOM'] help = """Writes image data to disc as DICOM images. This GDCM2-based module writes data to disc as one (multi-frame) or more DICOM files. As input, it requires a special DeVIDE datastructure containing the raw data, the medical image properties and direction cosines (indicating the orientation of the dataset in world / scanner space). You can create such a datastructure by making use of the DVMedicalImageData module. """ class ivWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """ivWRT is an Inventor Viewer polygonal data writer devide module. """ class metaImageWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes VTK image data or structured points in MetaImage format. """ class pngWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes a volume as a series of PNG images. Set the file pattern by making use of the file browsing dialog. Replace the increasing index by a %d format specifier. %3d can be used for example, in which case %d will be replaced by an integer zero padded to 3 digits, i.e. 000, 001, 002 etc. %d starts from 0. Module by Joris van Zwieten. """ class MatlabPointsWriter: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes slice3dVWR world-points to an m-file. """ class points_writer: # BUG: empty kits list screws up dependency checking kits = ['vtk_kit'] cats = ['Writers'] help = """TBD """ class stlWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes STL format data. """ class vtiWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes VTK image data or structured points in the VTK XML format. The data attribute is compressed. This is the preferred way of saving image data in DeVIDE. """ class vtkPolyDataWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Module for writing legacy VTK polydata. vtpWRT should be preferred for all VTK-compatible polydata storage. """ class vtkStructPtsWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Module for writing legacy VTK structured points data. vtiWRT should be preferred for all VTK-compatible image data storage. """ class vtpWRT: kits = ['vtk_kit'] cats = ['Writers'] help = """Writes VTK PolyData in the VTK XML format. The data attribute is compressed. This is the preferred way of saving PolyData in DeVIDE. """
Python
# $Id: vtpWRT.py 2401 2006-12-20 20:29:15Z cpbotha $ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import types class points_writer(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'DeVIDE points (*.dvp)|*.dvp|All files (*)|*', {'Module (self)': self}, fileOpen=False) # set up some defaults self._config.filename = '' self._input_points = None self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('DeVIDE points',) def set_input(self, idx, input_stream): self._input_points = input_stream def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if self._input_points and hasattr(self._input_points, 'devideType') \ and self._input_points.devideType == 'namedPoints' \ and self._config.filename: fh = file(self._config.filename, 'w') fh.write(str(self._input_points)) fh.close()
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx # needs this for wx.OPEN, we need to make this constant available # elsewhere class pngWRT(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin # FilenameViewModuleMixin.__init__(self) self._shiftScale = vtk.vtkImageShiftScale() self._shiftScale.SetOutputScalarTypeToUnsignedShort() module_utils.setup_vtk_object_progress( self, self._shiftScale, 'Converting input to unsigned short.') self._writer = vtk.vtkPNGWriter() self._writer.SetFileDimensionality(3) self._writer.SetInput(self._shiftScale.GetOutput()) module_utils.setup_vtk_object_progress( self, self._writer, 'Writing PNG file(s)') self._config.filePattern = '%d.png' configList = [ ('File pattern:', 'filePattern', 'base:str', 'filebrowser', 'Filenames will be built with this. See module help.', {'fileMode' : wx.OPEN, 'fileMask' : 'PNG files (*.png)|*.png|All files (*.*)|*.*'})] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self, 'vtkPNGWriter' : self._writer}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._writer def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, input_stream): self._shiftScale.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): self._config.filePattern = self._writer.GetFilePattern() def config_to_logic(self): self._writer.SetFilePattern(self._config.filePattern) def execute_module(self): if len(self._writer.GetFilePattern()) and self._shiftScale.GetInput(): inp = self._shiftScale.GetInput() inp.Update() minv,maxv = inp.GetScalarRange() self._shiftScale.SetShift(-minv) self._shiftScale.SetScale(65535 / (maxv - minv)) self._shiftScale.Update() self._writer.Write() self._module_manager.setProgress( 100.0, "vtkPNGWriter: Writing PNG file(s). [DONE]")
Python
# BatchConverter.py by Francois Malan - 2010-03-05. Updated 2011-12-11# import os.path from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import wx import os import vtk import itk class batchConverter( ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._config.source_folder = '' self._config.source_file_type = -1 self._config.source_forced_numerical_type = 0 self._config.source_numerical_type = 0 self._config.target_folder = '' self._config.target_file_type = -2 self._config.target_forced_numerical_type = 0 self._config.target_numerical_type = 0 self._config.overwrite = False self._config.delete_after_conversion = False #Make sure that the values below match the definitions in the config list! self._config.extensions = {0 : '.vti', 1 : '.mha', 2 : '.mhd', 3 : '.gipl'} self._vtk_data_types = (0, 1, 2) #The list of the above extensions which are VTK types #Make sure that these two dictionaries match the definitions in the config list! self._config.data_types_by_number = {0 : 'auto', 1 : 'float', 2 : 'short', 3 : 'unsigned char', 4 : 'binary (uchar)'} self._config.data_types_by_name = {'auto' : 0, 'float' : 1, 'short' : 2, 'unsigned char' : 3, 'binary (uchar)' : 4} config_list = [ ('Source Folder:', 'source_folder', 'base:str', 'dirbrowser', 'Select the source directory'), ('Source type:', 'source_file_type', 'base:int', 'choice', 'The source file type', ('VTK Imagedata (.vti)', 'MetaImage (.mha)', 'MetaImage: header + raw (.mhd, .raw)', 'Guys Image Processing Lab (.gipl)')), ('Read input as:', 'source_forced_numerical_type', 'base:int', 'choice', 'The data type we assume the input to be in', ('auto detect', 'float', 'signed int', 'unsigned char', 'binary (uchar)')), ('Delete source after conversion', 'delete_after_conversion', 'base:bool', 'checkbox', 'Do you want to delete the source files after conversion? (not recommended)'), ('Destination Folder:', 'target_folder', 'base:str', 'dirbrowser', 'Select the target directory'), ('Destination type:', 'target_file_type', 'base:int', 'choice', 'The destination file type', ('VTK Imagedata (.vti)', 'MetaImage (.mha)', 'MetaImage: header + raw (.mhd, .raw)', 'Guys Image Processing Lab (.gipl)')), ('Cast output to:', 'target_forced_numerical_type', 'base:int', 'choice', 'The data type we cast and write the output to', ('auto detect', 'float', 'signed int', 'unsigned char', 'binary (uchar)')), ('Automatically overwrite', 'overwrite', 'base:bool', 'checkbox', 'Do you want to automatically overwrite existing files?'), ] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) #for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of GUI ScriptedConfigModuleMixin.close(self) def set_input(self): pass def get_input_descriptions(self): return () def get_output_descriptions(self): return () # def get_output(self, idx): # return () def logic_to_config(self): pass def config_to_logic(self): pass def _read_input(self, source_file_path): """ Reads the input specified by the source file path, according to the parameters chosen by the user """ #We choose the correct reader for the job reader = None if self._config.source_file_type == 0: # VTI reader = vtk.vtkXMLImageDataReader() elif self._config.source_file_type == 1 or self._config.source_file_type == 2: # MHA or MHD reader = vtk.vtkMetaImageReader() elif self._config.source_file_type == 3: # GIPL. #GIPL needs an ITK reader, and that needs an explicit type if self._config.source_forced_numerical_type == 0: #auto # create ImageFileReader we'll be using for autotyping autotype_reader = itk.ImageFileReader[itk.Image.F3].New() #and the actual reader reader = itk.ImageFileReader[itk.Image.F3].New() reader_type_text_default = 'F3' autotype_reader.SetFileName(source_file_path) autotype_reader.UpdateOutputInformation() iio = autotype_reader.GetImageIO() comp_type = iio.GetComponentTypeAsString(iio.GetComponentType()) if comp_type == 'short': comp_type = 'signed_short' # lc will convert e.g. unsigned_char to UC short_type = ''.join([i[0].upper() for i in comp_type.split('_')]) dim = iio.GetNumberOfDimensions() num_comp = iio.GetNumberOfComponents() reader_type_text = '%s%d' % (short_type, dim) if num_comp > 1: # e.g. VF33 reader_type_text = 'V%s%d' % (reader_type_text, num_comp) # if things have changed, make a new reader, else re-use the old if reader_type_text != reader_type_text_default: # equivalent to e.g. itk.Image.UC3 reader = itk.ImageFileReader[ getattr(itk.Image, reader_type_text)].New() print '%s was auto-detected as ITK %s' % (source_file_path, reader_type_text) if reader_type_text == 'F3': self._config.source_numerical_type = 1 elif reader_type_text == 'SS3': self._config.source_numerical_type = 2 elif reader_type_text == 'UC3': self._config.source_numerical_type = 3 else: print "Warning: data of type '%s' is not explicitly supported. Reverting to IF3 (float)." % reader_type_text self._config.source_numerical_type = 1 reader = autotype_reader elif self._config.source_forced_numerical_type == 1: #float reader = itk.ImageFileReader.IF3.New() self._config.source_numerical_type = 1 elif self._config.source_forced_numerical_type == 2: #short reader = itk.ImageFileReader.ISS3.New() self._config.source_numerical_type = 2 elif self._config.source_forced_numerical_type == 3 or self._config.source_forced_numerical_type == 4: #unsigned char reader = itk.ImageFileReader.IUC3.New() self._config.source_numerical_type = 3 else: raise Exception('Undefined input data type with numerical index %d' % self._config.source_forced_numerical_type) else: raise Exception('Undefined file type with numerical index %d' % self._config.source_file_type) print "Reading %s ..." % source_file_path reader.SetFileName(source_file_path) reader.Update() return reader.GetOutput() def _convert_input(self, input_data): """ Converts the input data so that it can be sent to the writer. This includes VTK to ITK conversion as well as type casting. """ #These values will be used to determine if conversion is required source_is_vtk = self._config.source_file_type in self._vtk_data_types target_is_vtk = self._config.target_file_type in self._vtk_data_types #Set up the relevant data converter (e.g. VTK2ITK or ITK2VTK) converter = None caster = None output_data = None if source_is_vtk: #We autotype the VTK data, and compare it to the specified input type, if specified auto_data_type_as_string = input_data.GetPointData().GetArray(0).GetDataTypeAsString() auto_data_type_as_number = self._config.data_types_by_name[auto_data_type_as_string] if self._config.source_forced_numerical_type == 0: #auto self._config.source_numerical_type = auto_data_type_as_number else: set_data_type_as_string = self._config.data_types_by_number[self._config.source_forced_numerical_type] if auto_data_type_as_number == self._config.source_forced_numerical_type: self._config.source_numerical_type = self._config.source_forced_numerical_type else: raise Exception("Auto-detected data type (%s) doesn't match specified type (%s)" % (auto_data_type_as_string, set_data_type_as_string) ) #Perform type casting, if required if (self._config.source_numerical_type == self._config.target_forced_numerical_type) or (self._config.target_forced_numerical_type == 0): self._config.target_numerical_type = self._config.source_numerical_type else: self._config.target_numerical_type = self._config.target_forced_numerical_type print 'Type casting VTK data from (%s) to (%s)...' % (self._config.data_types_by_number[self._config.source_numerical_type], self._config.data_types_by_number[self._config.target_numerical_type]) caster = vtk.vtkImageCast() caster.SetInput(input_data) if self._config.target_numerical_type == 1: #float caster.SetOutputScalarTypeToFloat() elif self._config.target_numerical_type == 2: #short caster.SetOutputScalarTypeToShort() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char caster.SetOutputScalarTypeToUnsignedChar() if target_is_vtk: if caster == None: output_data = input_data else: caster.Update() output_data = vtk.vtkImageData() output_data.DeepCopy(caster.GetOutput()) else: #target is ITK - requires vtk2itk print 'Converting from VTK to ITK... (%s)' % self._config.data_types_by_number[self._config.target_numerical_type] if self._config.target_numerical_type == 1: #float converter = itk.VTKImageToImageFilter[itk.Image.F3].New() elif self._config.target_numerical_type == 2: #short converter = itk.VTKImageToImageFilter[itk.Image.SS3].New() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char converter = itk.VTKImageToImageFilter[itk.Image.UC3].New() else: raise Exception('Conversion of VTK %s to ITK not currently supported.' % data_types_by_number[self._config.source_file_type]) if caster == None: converter.SetInput(input_data) else: converter.SetInput(caster.GetOutput()) converter.Update() output_data = converter.GetOutput() else: #Source is ITK #The source type was already set when the data was read, so we don't need to autotype. #We don't know how to autotype ITK data anyway if self._config.source_numerical_type == 0: raise 'This should never happen - ITK data should be typed upon being read and not require autotyping' #Perform type casting, if required if (self._config.source_numerical_type == self._config.target_forced_numerical_type) or (self._config.target_forced_numerical_type == 0): self._config.target_numerical_type = self._config.source_numerical_type else: self._config.target_numerical_type = self._config.target_forced_numerical_type print 'Type casting ITK data from (%s) to (%s)...' % (self._config.data_types_by_number[self._config.source_numerical_type], self._config.data_types_by_number[self._config.target_numerical_type]) if self._config.source_numerical_type == 1: #float if self._config.target_numerical_type == 2: #short caster = itk.CastImageFilter.IF3ISS3() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char caster = itk.CastImageFilter.IF3IUC3() else: raise Exceception('Error - this case should not occur!') if self._config.source_numerical_type == 2: #short if self._config.target_numerical_type == 1: #float caster = itk.CastImageFilter.ISS3IF3() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char caster = itk.CastImageFilter.ISS3IUC3() else: raise Exceception('Error - this case should not occur!') if self._config.source_numerical_type == 3 or self._config.source_numerical_type == 4: #unsigned short if self._config.target_numerical_type == 1: #float caster = itk.CastImageFilter.IUC3IF3() elif self._config.target_numerical_type == 2: #short caster = itk.CastImageFilter.IUC3ISS3() else: raise Exceception('Error - this case should not occur!') caster.SetInput(input_data) if not target_is_vtk: if caster == None: output_data = input_data else: caster.Update() output_data = vtk.vtkImageData() output_data.DeepCopy(caster.GetOutput()) else: #target is VTK - requires itk2vtk print 'Converting from ITK to VTK... (%s)' % self._config.data_types_by_number[self._config.target_numerical_type] if self._config.target_numerical_type == 1: #float converter = itk.ImageToVTKImageFilter[itk.Image.F3].New() elif self._config.target_numerical_type == 2: #short converter = itk.ImageToVTKImageFilter[itk.Image.SS3].New() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char converter = itk.ImageToVTKImageFilter[itk.Image.UC3].New() else: raise Exception('Conversion of ITK %s to VTK not currently supported.' % self._config.data_types_by_number[self._config.target_numerical_type]) data_to_convert = None if caster == None: data_to_convert = input_data else: data_to_convert = caster.GetOutput() #These three lines are from DeVIDE's ITKtoVTK. Not clear why, but it's necessary data_to_convert.UpdateOutputInformation() data_to_convert.SetBufferedRegion(data_to_convert.GetLargestPossibleRegion()) data_to_convert.Update() converter.SetInput(data_to_convert) converter.Update() output_data = vtk.vtkImageData() output_data.DeepCopy(converter.GetOutput()) return output_data def _write_output(self, data, target_file_path): #Check for existing target file, and ask for overwrite confirmation if required if (not self._config.overwrite) and os.path.exists(target_file_path): dlg = wx.MessageDialog(self._view_frame, "%s already exists! \nOverwrite?" % target_file_path,"File already exists",wx.YES_NO|wx.NO_DEFAULT) if dlg.ShowModal() == wx.ID_NO: print 'Skipped writing %s' % target_file_path if self._config.delete_after_conversion: print 'Source %s not deleted, since no output was written' % source_file_path return #skip this file if overwrite is denied writer = None if self._config.target_file_type == 0: # VTI writer = vtk.vtkXMLImageDataWriter() elif self._config.target_file_type == 1: # MHA writer = vtk.vtkMetaImageWriter() writer.SetCompression(True) writer.SetFileDimensionality(3) elif self._config.target_file_type == 2: # MHD writer = vtk.vtkMetaImageWriter() writer.SetCompression(False) writer.SetFileDimensionality(3) elif self._config.target_file_type == 3: # GIPL. We assume floating point values. if self._config.target_numerical_type == 1: #float writer = itk.ImageFileWriter.IF3.New() elif self._config.target_numerical_type == 2: #short writer = itk.ImageFileWriter.ISS3.New() elif self._config.target_numerical_type == 3 or self._config.target_numerical_type == 4: #unsigned char writer = itk.ImageFileWriter.IUC3.New() else: raise Exception('Writing ITK %s is not currently supported.' % data_types_by_number[self._config.source_file_type]) else: raise Exception('Undefined file type with numerical index %d' % self._config.target_file_type) final_data = data if self._config.target_numerical_type == 4: th = vtk.vtkImageThreshold() th.ThresholdByLower(0.0) th.SetInValue(0.0) th.SetOutValue(1.0) th.SetOutputScalarTypeToUnsignedChar() th.SetInput(data) th.Update() final_data = th.GetOutput() #Write the output writer.SetInput(final_data) writer.SetFileName(target_file_path) print "Writing %s ..." % target_file_path writer.Write() def execute_module(self): if self._config.source_folder == '': dlg = wx.MessageDialog(self._view_frame, "No source folder specified", "No source folder",wx.OK) dlg.ShowModal() return elif self._config.target_folder == '': dlg = wx.MessageDialog(self._view_frame, "No destination folder specified", "No destination folder",wx.OK) dlg.ShowModal() return elif self._config.source_file_type < 0: dlg = wx.MessageDialog(self._view_frame, "No source type selected", "No source type",wx.OK) dlg.ShowModal() return elif self._config.target_file_type < 0: dlg = wx.MessageDialog(self._view_frame, "No destination type selected", "No destination type",wx.OK) dlg.ShowModal() return source_ext = self._config.extensions[self._config.source_file_type] target_ext = self._config.extensions[self._config.target_file_type] print 'Source type = %s, target type = %s' % (source_ext, target_ext) print 'source dir = %s' % (self._config.source_folder) print 'target dir = %s' % (self._config.target_folder) all_files = os.listdir(self._config.source_folder) #First we set up a list of files with the correct extension file_list = [] source_ext = self._config.extensions[self._config.source_file_type] for f in all_files: file_name = os.path.splitext(f) if file_name[1] == source_ext: file_list.append(file_name[0]) source_file_type_str = self._config.extensions[self._config.source_file_type] target_extension_str = self._config.extensions[self._config.target_file_type] #Iterate over all input files for file_prefix in file_list: #Read the input file source_file_name = '%s%s' % (file_prefix, source_file_type_str) source_file_path = os.path.join(self._config.source_folder, source_file_name) input_data = self._read_input(source_file_path) converted_data = self._convert_input(input_data) target_file_name = '%s%s' % (file_prefix, target_extension_str) target_file_path = os.path.join(self._config.target_folder, target_file_name) self._write_output(converted_data, target_file_path) #Now we delete the input IFF the check-box is checked, and only if source and destination names differ if self._config.delete_after_conversion: if source_file_path != target_file_path: print 'Deleting source %s' % source_file_path os.remove(source_file_path) else: print 'Source not deleted, since already overwritten by output: %s' % source_file_path print 'Done'
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class cptBrepWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._triFilter = vtk.vtkTriangleFilter() module_utils.setup_vtk_object_progress( self, self._triFilter, 'Converting to triangles') # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'brep files (*.brep)|*.brep|All files (*)|*', {'Module (self)' : self, 'vtkTriangleFilter': self._triFilter}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._triFilter FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._triFilter.SetInput(inputStream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._config.filename) and self._triFilter.GetInput(): # make sure our input is up to date polyData = self._triFilter.GetOutput() polyData.Update() # this will throw an exception if something went wrong. # list of tuples, each tuple contains three indices into vertices # list constituting a triangle face faces = [] self._module_manager.setProgress(10,'Extracting triangles') # blaat. numCells = polyData.GetNumberOfCells() for cellIdx in xrange(numCells): c = polyData.GetCell(cellIdx) # make sure we're working with triangles if c.GetClassName() == 'vtkTriangle': pointIds = c.GetPointIds() if pointIds.GetNumberOfIds() == 3: faces.append((pointIds.GetId(0), pointIds.GetId(1), pointIds.GetId(2))) # now we can finally write f = file(self._config.filename, 'w') f.write('%d\n%d\n' % (polyData.GetNumberOfPoints(), len(faces))) numPoints = polyData.GetNumberOfPoints() for ptIdx in xrange(numPoints): # polyData.GetPoint() returns a 3-tuple f.write('%f %f %f\n' % polyData.GetPoint(ptIdx)) pp = ptIdx / numPoints * 100.0 if pp % 10 == 0: self._module_manager.setProgress( pp, 'Writing points') numFaces = len(faces) faceIdx = 0 for face in faces: f.write('%d %d %d\n' % face) # this is just for progress faceIdx += 1 pp = faceIdx / numFaces * 100.0 if pp % 10 == 0: self._module_manager.setProgress( pp, 'Writing triangles')
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx # need this for wx.SAVE class metaImageWRT(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkMetaImageWriter() module_utils.setup_vtk_object_progress( self, self._writer, 'Writing VTK ImageData') # set up some defaults self._config.filename = '' self._config.compression = True config_list = [ ('Filename:', 'filename', 'base:str', 'filebrowser', 'Output filename for MetaImage file.', {'fileMode' : wx.SAVE, 'fileMask' : 'MetaImage single file (*.mha)|*.mha|MetaImage separate header/(z)raw files (*.mhd)|*.mhd|All files (*)|*', 'defaultExt' : '.mha'} ), ('Compression:', 'compression', 'base:bool', 'checkbox', 'Compress the image / volume data') ] ScriptedConfigModuleMixin.__init__(self, config_list, {'Module (self)' : self}) def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer # deinit our mixins ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename self._config.compression = self._writer.GetCompression() def config_to_logic(self): self._writer.SetFileName(self._config.filename) self._writer.SetCompression(self._config.compression) def execute_module(self): if self._writer.GetFileName() and self._writer.GetInput(): self._writer.GetInput().UpdateInformation() self._writer.GetInput().SetUpdateExtentToWholeExtent() self._writer.GetInput().Update() self._writer.Write() def streaming_execute_module(self): if self._writer.GetFileName() and self._writer.GetInput(): # if you use Update(), everything crashes (VTK 5.6.1, Ubuntu 10.04 x86_64) self._writer.Write()
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class vtkPolyDataWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkPolyDataWriter() # sorry about this, but the files get REALLY big if we write them # in ASCII - I'll make this a gui option later. self._writer.SetFileTypeToBinary() module_utils.setup_vtk_object_progress( self, self._writer, 'Writing VTK Polygonal data') # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'VTK data (*.vtk)|*.vtk|All files (*)|*', {'vtkPolyDataWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkStructuredPoints',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
# dumy __init__ so this directory can function as a package
Python
# Copyright (c) Charl P. Botha, TU Delft # All rights reserved. # See COPYRIGHT for details. # Random development notes: # * SetFileDimensionality(2) if you want multiple slices written from # a single volume # * just generate im%05d.dcm filenames, as many as there are slices # * study / series UIDs are auto generated from module_base import ModuleBase from module_mixins import \ ScriptedConfigModuleMixin import module_utils import os import vtk import vtkgdcm import wx # need this for wx.SAVE RADIOBOX_IDX, DIR_IDX, FILE_IDX = 0, 1, 2 class DICOMWriter(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._writer = vtkgdcm.vtkGDCMImageWriter() # NB NB NB: for now we're SWITCHING off the VTK-compatible # Y-flip, until the X-mirror issues can be solved. self._writer.SetFileLowerLeft(1) module_utils.setup_vtk_object_progress(self, self._writer, 'Writing DICOM data') self._caster = vtk.vtkImageCast() self._caster.SetOutputScalarTypeToShort() module_utils.setup_vtk_object_progress(self, self._caster, 'Casting DICOM data to short') self._input_data = None self._input_metadata = None self._config.output_mode = 0 self._config.output_directory = '' self._config.output_filename = '' self._config.cast_to_short = True config_list = [ ('Output mode:', 'output_mode', 'base:int', 'radiobox', 'Output mode', ['Slice-per-file (directory)', 'Multi-slice per file (file)']), ('Output directory:', 'output_directory', 'base:str', 'dirbrowser', 'Directory that takes slice-per-file output'), ('Output filename:', 'output_filename', 'base:str', 'filebrowser', 'Output filename for multi-slice per file output.', {'fileMode' : wx.SAVE, 'fileMask' : 'DICOM file (*.dcm)|*.dcm|' 'All files (*.*)|*.*'} ), ('Cast to short:', 'cast_to_short', 'base:bool', 'checkbox', 'Should the data be cast to signed 16-bit (short), ' 'common for DICOM.') ] ScriptedConfigModuleMixin.__init__(self, config_list, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) del self._writer def get_input_descriptions(self): return ('VTK image data', 'Medical Meta Data') def set_input(self, idx, input_stream): if idx == 0: self._input_data = input_stream if input_stream is None: # we explicitly disconnect our filters too self._caster.SetInput(None) self._writer.SetInput(None) else: self._input_metadata = input_stream def get_output_descriptions(self): return () def get_output(self, idx): raise RuntimeError def execute_module(self): if self._config.output_mode == 0: # slice-per-file mode if not os.path.isdir(self._config.output_directory): raise RuntimeError( 'Please specify a valid output directory.') # generate filenamelist with as many entries as there are # z-slices self._input_data.UpdateInformation() # shouldn't be nec. z_len = self._input_data.GetDimensions()[2] odir = self._config.output_directory fn_list = [os.path.join(odir,'im%05d.dcm' % (i,)) for i in range(1, z_len+1)] fn_sa = vtk.vtkStringArray() [fn_sa.InsertNextValue(fn) for fn in fn_list] self._writer.SetFileNames(fn_sa) self._writer.SetFileDimensionality(2) else: # output_mode == 1, multi-slices per file if not self._config.output_filename: raise RuntimeError( 'Please specify an output filename.') self._writer.SetFileName(self._config.output_filename) self._writer.SetFileDimensionality(3) # now setup the common stuff mip = vtk.vtkMedicalImageProperties() try: mip.DeepCopy(self._input_metadata.medical_image_properties) except AttributeError: # this simply means that we have no input metadata pass self._writer.SetMedicalImageProperties(mip) try: self._writer.SetDirectionCosines( self._input_metadata.direction_cosines) except AttributeError: # we have no input metadata, set the default # identity matrix m = vtk.vtkMatrix4x4() self._writer.SetDirectionCosines(m) if self._config.cast_to_short: self._caster.SetInput(self._input_data) # if we don't call this update, it crashes on Windows with # GDCM 2.0.5, and everything else shortly before DeVIDE # 8.5. The crash is inside the vtkGDCMImageWriter. self._caster.Update() self._writer.SetInput(self._caster.GetOutput()) else: # just to be sure self._caster.SetInput(None) self._writer.SetInput(self._input_data) self._writer.Write() def logic_to_config(self): pass def config_to_logic(self): pass def view(self): # call to our parent ScriptedConfigModuleMixin.view(self) # get binding to radiobox radiobox = self._getWidget(RADIOBOX_IDX) # bind change event to it radiobox.Bind(wx.EVT_RADIOBOX, self._handler_output_mode_radiobox) # make sure the initial state is ok self._toggle_filedir(radiobox.GetSelection()) def _handler_output_mode_radiobox(self, event): self._toggle_filedir(event.GetEventObject().GetSelection()) def _toggle_filedir(self, idx): dir_widget = self._getWidget(DIR_IDX) file_widget = self._getWidget(FILE_IDX) if idx == 0: # user wants slice-per-file, so we enable dir widget dir_widget.Enable() file_widget.Disable() else: dir_widget.Disable() file_widget.Enable()
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class stlWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # need to make sure that we're all happy triangles and stuff self._cleaner = vtk.vtkCleanPolyData() self._tf = vtk.vtkTriangleFilter() self._tf.SetInput(self._cleaner.GetOutput()) self._writer = vtk.vtkSTLWriter() self._writer.SetInput(self._tf.GetOutput()) # sorry about this, but the files get REALLY big if we write them # in ASCII - I'll make this a gui option later. #self._writer.SetFileTypeToBinary() # following is the standard way of connecting up the devide progress # callback to a VTK object; you should do this for all objects in mm = self._module_manager for textobj in (('Cleaning data', self._cleaner), ('Converting to triangles', self._tf), ('Writing STL data', self._writer)): module_utils.setup_vtk_object_progress(self, textobj[1], textobj[0]) # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'STL data (*.stl)|*.stl|All files (*)|*', {'vtkSTLWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, input_stream): self._cleaner.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
# $Id$ from module_base import ModuleBase from module_mixins import FilenameViewModuleMixin import module_utils import vtk class vtpWRT(FilenameViewModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._writer = vtk.vtkXMLPolyDataWriter() module_utils.setup_vtk_object_progress( self, self._writer, 'Writing VTK PolyData') self._writer.SetDataModeToBinary() # ctor for this specific mixin FilenameViewModuleMixin.__init__( self, 'Select a filename', 'VTK PolyData (*.vtp)|*.vtp|All files (*)|*', {'vtkXMLPolyDataWriter': self._writer}, fileOpen=False) # set up some defaults self._config.filename = '' self.sync_module_logic_with_config() def close(self): # we should disconnect all inputs self.set_input(0, None) del self._writer FilenameViewModuleMixin.close(self) def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, input_stream): self._writer.SetInput(input_stream) def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): filename = self._writer.GetFileName() if filename == None: filename = '' self._config.filename = filename def config_to_logic(self): self._writer.SetFileName(self._config.filename) def view_to_config(self): self._config.filename = self._getViewFrameFilename() def config_to_view(self): self._setViewFrameFilename(self._config.filename) def execute_module(self): if len(self._writer.GetFileName()): self._writer.Write()
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class testModule(NoConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # we'll be playing around with some vtk objects, this could # be anything self._triangleFilter = vtk.vtkTriangleFilter() self._curvatures = vtk.vtkCurvatures() self._curvatures.SetCurvatureTypeToMaximum() self._curvatures.SetInput(self._triangleFilter.GetOutput()) # initialise any mixins we might have NoConfigModuleMixin.__init__(self, {'Module (self)' : self, 'vtkTriangleFilter' : self._triangleFilter, 'vtkCurvatures' : self._curvatures}) module_utils.setup_vtk_object_progress(self, self._triangleFilter, 'Triangle filtering...') module_utils.setup_vtk_object_progress(self, self._curvatures, 'Calculating curvatures...') self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._triangleFilter del self._curvatures def get_input_descriptions(self): return ('vtkPolyData',) def set_input(self, idx, inputStream): self._triangleFilter.SetInput(inputStream) def get_output_descriptions(self): return (self._curvatures.GetOutput().GetClassName(),) def get_output(self, idx): return self._curvatures.GetOutput() def execute_module(self): self._curvatures.Update() def streaming_execute_module(self): self._curvatures.Update()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageEigenvectors(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageEigenvectors = vtktud.vtkImageEigenvectors() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageEigenvectors' : self._imageEigenvectors}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageEigenvectors def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageEigenvectors.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData','vtkImageData','vtkImageData') def get_output(self, idx): return self._imageEigenvectors.GetOutput(idx) def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageEigenvectors.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageGradientStructureTensor(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageGradientStructureTensor = vtktud.vtkImageGradientStructureTensor() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageGradientStructureTensor' : self._imageGradientStructureTensor}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageGradientStructureTensor def get_input_descriptions(self): return ('vtkImageData', 'vtkImageData', 'vtkImageData') def set_input(self, idx, inputStream): self._imageGradientStructureTensor.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageGradientStructureTensor.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageGradientStructureTensor.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import wx import vtk class myTubeFilter(ScriptedConfigModuleMixin, ModuleBase): """Simple demonstration of ScriptedConfigModuleMixin-based wrapping of a single VTK object. It would of course be even easier using simpleVTKClassModuleBase. $Revision: 1.1 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._tubeFilter = vtk.vtkTubeFilter() module_utils.setup_vtk_object_progress(self, self._tubeFilter, 'Generating tubes.') self._config.NumberOfSides = 3 self._config.Radius = 0.01 configList = [ ('Number of sides:', 'NumberOfSides', 'base:int', 'text', 'Number of sides that the tube should have.'), ('Tube radius:', 'Radius', 'base:float', 'text', 'Radius of the generated tube.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkTubeFilter' : self._tubeFilter}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._tubeFilter def get_input_descriptions(self): return ('vtkPolyData lines',) def set_input(self, idx, inputStream): self._tubeFilter.SetInput(inputStream) def get_output_descriptions(self): return ('vtkPolyData tubes', ) def get_output(self, idx): return self._tubeFilter.GetOutput() def logic_to_config(self): self._config.NumberOfSides = self._tubeFilter.GetNumberOfSides() self._config.Radius = self._tubeFilter.GetRadius() def config_to_logic(self): self._tubeFilter.SetNumberOfSides(self._config.NumberOfSides) self._tubeFilter.SetRadius(self._config.Radius) def execute_module(self): self._tubeFilter.GetOutput().Update()
Python
# $Id$ class simplestVTKExample: kits = ['vtk_kit'] cats = ['User'] class isolated_points_check: kits = ['vtk_kit'] cats = ['User'] class testModule: kits = ['vtk_kit'] cats = ['User']
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageCurvatureMagnitude(ModuleBase, NoConfigModuleMixin): def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageCurvatureMagnitude = vtktud.vtkImageCurvatureMagnitude() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageCurvatureMagnitude' : self._imageCurvatureMagnitude}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageCurvatureMagnitude def get_input_descriptions(self): return ('vtkImageData', 'vtkImageData', 'vtkImageData','vtkImageData', 'vtkImageData') def set_input(self, idx, inputStream): self._imageCurvatureMagnitude.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageCurvatureMagnitude.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageCurvatureMagnitude.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtktud class imageCurvature(ModuleBase, NoConfigModuleMixin): """Calculates image curvature with VTKTUD vtkImageCurvature filter. You need 8 inputs, and in the following sequence: dx, dy, dz, dxx, dyy, dzz, dxy, dxz, dyz. This will output some curvature measure. The underlying filter will be adapted to make the raw curvature data (principal curvatures and directions of the isophote surface) available as well. All code by Joris van Zwieten. This bit of documentation by cpbotha. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageCurvature = vtktud.vtkImageCurvature() # module_utils.setup_vtk_object_progress(self, self._clipPolyData, # 'Calculating normals') self._viewFrame = self._createViewFrame( {'ImageCurvature' : self._imageCurvature}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) # get rid of our reference del self._imageCurvature def get_input_descriptions(self): return ('dx', 'dy', 'dz', 'dxx', 'dyy', 'dzz', 'dxy', 'dxz', 'dyz') def set_input(self, idx, inputStream): self._imageCurvature.SetInput(idx, inputStream) def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._imageCurvature.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageCurvature.Update() def view(self, parent_window=None): # if the window was visible already. just raise it if not self._viewFrame.Show(True): self._viewFrame.Raise()
Python
# $Id: module_index.py 1894 2006-02-23 08:55:45Z cpbotha $ class DilateExample: kits = ['vtk_kit'] cats = ['User','Cartilage3D']
Python
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class DilateExample(ScriptedConfigModuleMixin, ModuleBase): """Performs a greyscale 3D dilation on the input. $Revision: 1.2 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageDilate = vtk.vtkImageContinuousDilate3D() module_utils.setup_vtk_object_progress(self, self._imageDilate, 'Performing greyscale 3D dilation') self._config.kernelSize = (3, 3, 3) configList = [ ('Kernel size:', 'kernelSize', 'tuple:int,3', 'text', 'Size of the kernel in x,y,z dimensions.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createWindow( {'Module (self)' : self, 'vtkImageContinuousDilate3D' : self._imageDilate}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.logic_to_config() self.config_to_view() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._imageDilate def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._imageDilate.SetInput(inputStream) def get_output_descriptions(self): return (self._imageDilate.GetOutput().GetClassName(), ) def get_output(self, idx): return self._imageDilate.GetOutput() def logic_to_config(self): self._config.kernelSize = self._imageDilate.GetKernelSize() def config_to_logic(self): ks = self._config.kernelSize self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2]) def execute_module(self): self._imageDilate.Update() #def view(self, parent_window=None): # # if the window was visible already. just raise it # self._viewFrame.Show(True) # self._viewFrame.Raise()
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk import vtkdevide class imageBacktracker(NoConfigModuleMixin, ModuleBase): """JORIK'S STUFF. """ def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageBacktracker = vtkdevide.vtkImageBacktracker() module_utils.setup_vtk_object_progress(self, self._imageBacktracker, 'Backtracking...') # we'll use this to keep a binding (reference) to the passed object self._inputPoints = None # inputPoints observer ID self._inputPointsOID = None # this will be our internal list of points self._seedPoints = [] self._viewFrame = None self._createViewFrame({'Module (self)' : self, 'vtkImageBacktracker' : self._imageBacktracker}) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) self.set_input(0, None) self.set_input(1, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # take out our view interface del self._imageBacktracker ModuleBase.close(self) def get_input_descriptions(self): return ('vtkImageData', 'Seed points') def set_input(self, idx, inputStream): if idx == 0: # will work for None and not-None self._imageBacktracker.SetInput(inputStream) else: if inputStream is not self._inputPoints: if self._inputPoints: self._inputPoints.removeObserver(self._inputPointsObserver) if inputStream: inputStream.addObserver(self._inputPointsObserver) self._inputPoints = inputStream # initial update self._inputPointsObserver(None) def get_output_descriptions(self): return ('Backtracked polylines (vtkPolyData)',) def get_output(self, idx): return self._imageBacktracker.GetOutput() def execute_module(self): self._imageBacktracker.Update() def _inputPointsObserver(self, obj): # extract a list from the input points tempList = [] if self._inputPoints: for i in self._inputPoints: tempList.append(i['discrete']) if tempList != self._seedPoints: self._seedPoints = tempList self._imageBacktracker.RemoveAllSeeds() for seedPoint in self._seedPoints: self._imageBacktracker.AddSeed(seedPoint[0], seedPoint[1], seedPoint[2]) print "adding %s" % (str(seedPoint))
Python
import gen_utils from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import wx import vtk import vtkdevide class modifyHomotopySlow(NoConfigModuleMixin, ModuleBase): """ WARNING, WARNING, DANGER WILL ROBINSON: this filter exists purely for experimental purposes. If you really want to use modifyHomotopy, use the module in modules.Filters (also part of 'Morphology'). This filter implements the modification according to very basic math and is dog-slow. In addition, it's throw-away code. Modifies homotopy of input image I so that the only minima will be at the user-specified seed-points or marker image, all other minima will be suppressed and ridge lines separating minima will be preserved. Either the seed-points or the marker image (or both) can be used. The marker image has to be >1 at the minima that are to be enforced and 0 otherwise. This module is often used as a pre-processing step to ensure that the watershed doesn't over-segment. $Revision: 1.1 $ """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) # these will be our markers self._inputPoints = None # we can't connect the image input directly to the masksource, # so we have to keep track of it separately. self._inputImage = None self._inputImageObserverID = None # we need to modify the mask (I) as well. The problem with a # ProgrammableFilter is that you can't request GetOutput() before # the input has been set... self._maskSource = vtk.vtkProgrammableSource() self._maskSource.SetExecuteMethod(self._maskSourceExecute) # we'll use this to synthesise a volume according to the seed points self._markerSource = vtk.vtkProgrammableSource() self._markerSource.SetExecuteMethod(self._markerSourceExecute) # second input is J (the marker) # we'll use this to change the markerImage into something we can use self._imageThreshold = vtk.vtkImageThreshold() # everything equal to or above 1.0 will be "on" self._imageThreshold.ThresholdByUpper(1.0) self._imageThresholdObserverID = self._imageThreshold.AddObserver( 'EndEvent', self._observerImageThreshold) self._viewFrame = self._createViewFrame( {'Module (self)' : self}) # we're not going to give imageErode any input... that's going to # to happen manually in the execute_module function :) self._imageErode = vtk.vtkImageContinuousErode3D() self._imageErode.SetKernelSize(3,3,3) module_utils.setup_vtk_object_progress(self, self._imageErode, 'Performing greyscale 3D erosion') self._sup = vtk.vtkImageMathematics() self._sup.SetOperationToMax() self._sup.SetInput1(self._imageErode.GetOutput()) self._sup.SetInput2(self._maskSource.GetStructuredPointsOutput()) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies NoConfigModuleMixin.close(self) ModuleBase.close(self) # self._imageThreshold.RemoveObserver(self._imageThresholdObserverID) # get rid of our reference del self._markerSource del self._maskSource del self._imageThreshold del self._sup del self._imageErode def get_input_descriptions(self): return ('VTK Image Data', 'Minima points', 'Minima image') def set_input(self, idx, inputStream): if idx == 0: if inputStream != self._inputImage: # if we have a different image input, the seeds will have to # be rebuilt! self._markerSource.Modified() # and obviously the masksource has to know that its "input" # has changed self._maskSource.Modified() if inputStream: # we have to add an observer s = inputStream.GetSource() if s: self._inputImageObserverID = s.AddObserver( 'EndEvent', self._observerInputImage) else: # if we had an observer, remove it if self._inputImage: s = self._inputImage.GetSource() if s and self._inputImageObserverID: s.RemoveObserver( self._inputImageObserverID) self._inputImageObserverID = None # finally store the new data self._inputImage = inputStream elif idx == 1: if inputStream != self._inputPoints: # check that the inputStream is either None (meaning # disconnect) or a valid type try: if inputStream != None and \ inputStream.devideType != 'namedPoints': raise TypeError except (AttributeError, TypeError): raise TypeError, 'This input requires a points-type' if self._inputPoints: self._inputPoints.removeObserver( self._observerInputPoints) self._inputPoints = inputStream if self._inputPoints: self._inputPoints.addObserver(self._observerInputPoints) # the input points situation has changed, make sure # the marker source knows this... self._markerSource.Modified() # as well as the mask source of course self._maskSource.Modified() else: if inputStream != self._imageThreshold.GetInput(): self._imageThreshold.SetInput(inputStream) # we have a different inputMarkerImage... have to recalc self._markerSource.Modified() self._maskSource.Modified() def get_output_descriptions(self): return ('Modified VTK Image Data', 'I input', 'J input') def get_output(self, idx): if idx == 0: return self._sup.GetOutput() elif idx == 1: return self._maskSource.GetStructuredPointsOutput() else: return self._markerSource.GetStructuredPointsOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): # FIXME: if this module ever becomes anything other than an experiment, build # this logic into yet another ProgrammableSource # make sure marker is up to date self._markerSource.GetStructuredPointsOutput().Update() self._maskSource.GetStructuredPointsOutput().Update() tempJ = vtk.vtkStructuredPoints() tempJ.DeepCopy(self._markerSource.GetStructuredPointsOutput()) self._imageErode.SetInput(tempJ) self._diff = vtk.vtkImageMathematics() self._diff.SetOperationToSubtract() self._accum = vtk.vtkImageAccumulate() self._accum.SetInput(self._diff.GetOutput()) # now begin our loop stable = False while not stable: # do erosion, get supremum of erosion and mask I self._sup.GetOutput().Update() # compare this result with tempJ self._diff.SetInput1(tempJ) self._diff.SetInput2(self._sup.GetOutput()) self._accum.Update() print "%f == %f ?" % (self._accum.GetMin()[0], self._accum.GetMax()[0]) if abs(self._accum.GetMin()[0] - self._accum.GetMax()[0]) < 0.0001: stable = True else: # not stable yet... print "Trying again..." tempJ.DeepCopy(self._sup.GetOutput()) def _markerSourceExecute(self): imageI = self._inputImage if imageI: imageI.Update() # setup and allocate J output outputJ = self._markerSource.GetStructuredPointsOutput() # _dualGreyReconstruct wants inputs the same with regards to # dimensions, origin and type, so this is okay. outputJ.CopyStructure(imageI) outputJ.AllocateScalars() # we need this to build up J minI, maxI = imageI.GetScalarRange() mi = self._imageThreshold.GetInput() if mi: if mi.GetOrigin() == outputJ.GetOrigin() and \ mi.GetExtent() == outputJ.GetExtent(): self._imageThreshold.SetInValue(minI) self._imageThreshold.SetOutValue(maxI) self._imageThreshold.SetOutputScalarType(imageI.GetScalarType()) self._imageThreshold.GetOutput().SetUpdateExtentToWholeExtent() self._imageThreshold.Update() outputJ.DeepCopy(self._imageThreshold.GetOutput()) else: vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: marker input should be same dimensions as image input!') # we can continue as if we only had seeds scalars = outputJ.GetPointData().GetScalars() scalars.FillComponent(0, maxI) else: # initialise all scalars to maxI scalars = outputJ.GetPointData().GetScalars() scalars.FillComponent(0, maxI) # now go through all seed points and set those positions in # the scalars to minI if self._inputPoints: for ip in self._inputPoints: x,y,z = ip['discrete'] outputJ.SetScalarComponentFromDouble(x, y, z, 0, minI) def _maskSourceExecute(self): inputI = self._inputImage if inputI: inputI.Update() self._markerSource.Update() outputJ = self._markerSource.GetStructuredPointsOutput() # we now have an outputJ if not inputI.GetScalarPointer() or \ not outputJ.GetScalarPointer() or \ not inputI.GetDimensions() > (0,0,0): vtk.vtkOutputWindow.GetInstance().DisplayErrorText( 'modifyHomotopy: Input is empty.') return iMath = vtk.vtkImageMathematics() iMath.SetOperationToMin() iMath.SetInput1(outputJ) iMath.SetInput2(inputI) iMath.GetOutput().SetUpdateExtentToWholeExtent() iMath.Update() outputI = self._maskSource.GetStructuredPointsOutput() outputI.DeepCopy(iMath.GetOutput()) def _observerInputPoints(self, obj): # this will be called if anything happens to the points # simply make sure our markerSource knows that it's now invalid self._markerSource.Modified() self._maskSource.Modified() def _observerInputImage(self, obj, eventName): # the inputImage has changed, so the marker will have to change too self._markerSource.Modified() # logical, input image has changed self._maskSource.Modified() def _observerImageThreshold(self, obj, eventName): # if anything in the threshold has changed, (e.g. the input) we # have to invalidate everything else after it self._markerSource.Modified() self._maskSource.Modified()
Python
from module_mixins import simpleVTKClassModuleBase import vtk import vtkdevide class imageBorderMask(simpleVTKClassModuleBase): def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtkdevide.vtkImageBorderMask(), 'Creating border mask.', ('VTK Image Data',), ('Border Mask (vtkImageData)',))
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud class cubicBCSplineKernel(ScriptedConfigModuleMixin, ModuleBase): """First test of a cubic B-Spline implicit kernel $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config self._config.order = 0 self._config.support = 4.0 self._config.B = 0.0; self._config.C = 0.5; # and then our scripted config configList = [ ('Order: ', 'order', 'base:int', 'text', 'The order of the cubic B-Spline kernel (0-2).'), ('B: ', 'B', 'base:float', 'text', 'B'), ('C: ', 'C', 'base:float', 'text', 'C'), ('Support: ', 'support', 'base:float', 'text', 'The support of the cubic B-Spline kernel.')] # mixin ctor ScriptedConfigModuleMixin.__init__(self, configList) # now create the necessary VTK modules self._cubicBCSplineKernel = vtktud.vtkCubicBCSplineKernel() # setup progress for the processObject # module_utils.setup_vtk_object_progress(self, self._superquadricSource, # "Synthesizing polydata.") self._createWindow( {'Module (self)' : self, 'vtkCubicBCSplineKernel' : self._cubicBCSplineKernel}) self.config_to_logic() self.syncViewWithLogic() def close(self): # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._cubicBCSplineKernel def execute_module(self): return () def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('vtkSeparableKernel',) def get_output(self, idx): return self._cubicBCSplineKernel def config_to_logic(self): # sanity check if self._config.support < 0.0: self._config.support = 0.0 self._cubicBCSplineKernel.SetOrder( self._config.order ) self._cubicBCSplineKernel.SetB( self._config.B ) self._cubicBCSplineKernel.SetC( self._config.C ) self._cubicBCSplineKernel.SetSupport( self._config.support ) def logic_to_config(self): self._config.order = self._cubicBCSplineKernel.GetOrder() self._config.B = self._cubicBCSplineKernel.GetB() self._config.C = self._cubicBCSplineKernel.GetC() self._config.support = self._cubicBCSplineKernel.GetSupport()
Python
# $Id$ import fixitk as itk import gen_utils from module_base import ModuleBase import module_utils import module_utilsITK from module_mixins import ScriptedConfigModuleMixin class hessianDoG(ScriptedConfigModuleMixin, ModuleBase): """Calculates Hessian matrix of volume by convolution with second and cross derivatives of Gaussian kernel. $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._config.gaussianSigma = 0.7 self._config.normaliseAcrossScale = False configList = [ ('Gaussian sigma', 'gaussianSigma', 'base:float', 'text', 'Sigma in terms of image spacing.'), ('Normalise across scale', 'normaliseAcrossScale', 'base:bool', 'checkbox', 'Determine normalisation factor.')] ScriptedConfigModuleMixin.__init__(self, configList) # setup the pipeline g = itk.itkGradientMagnitudeRecursiveGaussianImageFilterF3F3_New() self._gradientMagnitude = g module_utilsITK.setupITKObjectProgress( self, g, 'itkGradientMagnitudeRecursiveGaussianImageFilter', 'Calculating gradient image') self._createWindow( {'Module (self)' : self, 'itkGradientMagnitudeRecursiveGaussianImageFilter' : self._gradientMagnitude}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gradientMagnitude def execute_module(self): self._gradientMagnitude.Update() def get_input_descriptions(self): return ('ITK Image (3D, float)',) def set_input(self, idx, inputStream): self._gradientMagnitude.SetInput(inputStream) def get_output_descriptions(self): return ('ITK Image (3D, float)',) def get_output(self, idx): return self._gradientMagnitude.GetOutput() def config_to_logic(self): self._gradientMagnitude.SetSigma(self._config.gaussianSigma) self._gradientMagnitude.SetNormalizeAcrossScale( self._config.normaliseAcrossScale) def logic_to_config(self): # durnit, there's no GetSigma(). Doh. self._config.normaliseAcrossScale = self._gradientMagnitude.\ GetNormalizeAcrossScale()
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class reconstructSurface(ModuleBase, NoConfigModuleMixin): """Given a binary volume, fit a surface through the marked points. A doubleThreshold could be used to extract points of interest from a volume. By passing it through this module, a surface will be fit through those points of interest. The points of interest have to be of value 1 or greater. This is not to be confused with traditional iso-surface extraction. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) # we'll be playing around with some vtk objects, this could # be anything self._thresh = vtk.vtkThresholdPoints() # this is wacked syntax! self._thresh.ThresholdByUpper(1) self._reconstructionFilter = vtk.vtkSurfaceReconstructionFilter() self._reconstructionFilter.SetInput(self._thresh.GetOutput()) self._mc = vtk.vtkMarchingCubes() self._mc.SetInput(self._reconstructionFilter.GetOutput()) self._mc.SetValue(0, 0.0) module_utils.setup_vtk_object_progress(self, self._thresh, 'Extracting points...') module_utils.setup_vtk_object_progress(self, self._reconstructionFilter, 'Reconstructing...') module_utils.setup_vtk_object_progress(self, self._mc, 'Extracting surface...') self._iObj = self._thresh self._oObj = self._mc self._viewFrame = self._createViewFrame({'threshold' : self._thresh, 'reconstructionFilter' : self._reconstructionFilter, 'marchingCubes' : self._mc}) def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._thresh del self._reconstructionFilter del self._mc del self._iObj del self._oObj def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): self._iObj.SetInput(inputStream) def get_output_descriptions(self): return (self._oObj.GetOutput().GetClassName(),) def get_output(self, idx): return self._oObj.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._oObj.Update() def view(self, parent_window=None): self._viewFrame.Show(True) self._viewFrame.Raise()
Python
from module_base import ModuleBase from module_mixins import NoConfigModuleMixin import module_utils import vtk class testModule2(NoConfigModuleMixin, ModuleBase): """Resample volume according to 4x4 homogeneous transform. """ def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # initialise any mixins we might have NoConfigModuleMixin.__init__(self) self._imageReslice = vtk.vtkImageReslice() self._imageReslice.SetInterpolationModeToCubic() self._matrixToHT = vtk.vtkMatrixToHomogeneousTransform() self._matrixToHT.Inverse() module_utils.setup_vtk_object_progress(self, self._imageReslice, 'Resampling volume') self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageReslice' : self._imageReslice}) # pass the data down to the underlying logic self.config_to_logic() # and all the way up from logic -> config -> view to make sure self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # don't forget to call the close() method of the vtkPipeline mixin NoConfigModuleMixin.close(self) # get rid of our reference del self._imageReslice def get_input_descriptions(self): return ('VTK Image Data', 'VTK Transform') def set_input(self, idx, inputStream): if idx == 0: self._imageReslice.SetInput(inputStream) else: try: self._matrixToHT.SetInput(inputStream.GetMatrix()) except AttributeError: # this means the inputStream has no GetMatrix() # i.e. it could be None or just the wrong type # if it's none, we just have to disconnect if inputStream == None: self._matrixToHT.SetInput(None) self._imageReslice.SetResliceTransform(None) # if not, we have to complain else: raise TypeError, \ "transformVolume input 2 requires a transform." else: self._imageReslice.SetResliceTransform(self._matrixToHT) def get_output_descriptions(self): return ('Transformed VTK Image Data',) def get_output(self, idx): return self._imageReslice.GetOutput() def logic_to_config(self): pass def config_to_logic(self): pass def view_to_config(self): pass def config_to_view(self): pass def execute_module(self): self._imageReslice.Update()
Python
from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import wx class myImageClip(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._clipper = vtk.vtkImageClip() module_utils.setup_vtk_object_progress(self, self._clipper, 'Reading PNG images.') self._config.outputWholeExtent = (0,-1,0,-1,0,-1) configList = [ ('OutputWholeExtent:', 'outputWholeExtent', 'tuple:float,6', 'text', 'The size of the clip volume.')] ScriptedConfigModuleMixin.__init__(self, configList) self._viewFrame = self._createViewFrame( {'Module (self)' : self, 'vtkImageClip' : self._clipper}) self.config_to_logic() self.syncViewWithLogic() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) # get rid of our reference del self._clipper def get_input_descriptions(self): return ('vtkImageData',) def set_input(self, idx, inputStream): if idx == 0: self._clipper.SetInput(inputStream) else: raise Exception def get_output_descriptions(self): return ('vtkImageData',) def get_output(self, idx): return self._clipper.GetOutput() def logic_to_config(self): self._config.outputWholeExtent = self._clipper.GetOutputWholeExtent() def config_to_logic(self): self._clipper.SetOutputWholeExtent( self._config.outputWholeExtent, None ) def execute_module(self): self._clipper.Update()
Python
# EmphysemaViewerFrame by Corine Slagboom & Noeska Smit # Description # # Based on SkeletonAUIViewerFrame: # Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. import cStringIO from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import wx # wxPython 2.8.8.1 wx.aui bugs severely on GTK. See: # http://trac.wxwidgets.org/ticket/9716 # Until this is fixed, use this PyAUI to which I've added a # wx.aui compatibility layer. if wx.Platform == "__WXGTK__": from external import PyAUI wx.aui = PyAUI else: import wx.aui # one could have loaded a wxGlade created resource like this: #from resources.python import DICOMBrowserPanels #reload(DICOMBrowserPanels) class EmphysemaViewerFrame(wx.Frame): """wx.Frame child class used by Emphysemaviewer for its interface. This is an AUI-managed window, so we create the top-level frame, and then populate it with AUI panes. """ def __init__(self, parent, id=-1, title="", name=""): """Populates the menu and adds all required panels """ wx.Frame.__init__(self, parent, id=id, title=title, pos=wx.DefaultPosition, size=(1000,875), name=name) self.menubar = wx.MenuBar() self.SetMenuBar(self.menubar) file_menu = wx.Menu() self.id_file_open = wx.NewId() self.id_mask_open = wx.NewId() file_menu.Append(self.id_file_open, "&Open Volume\tCtrl-O", "Open a volume", wx.ITEM_NORMAL) file_menu.Append(self.id_mask_open, "&Open Mask\tCtrl-M", "Open a mask", wx.ITEM_NORMAL) self.id_mask_save = wx.NewId() file_menu.Append(self.id_mask_save, "&Save\tCtrl-S", "Save file", wx.ITEM_NORMAL) self.menubar.Append(file_menu, "&File") views_menu = wx.Menu() views_default_id = wx.NewId() views_menu.Append(views_default_id, "&Default\tCtrl-0", "Activate default view layout.", wx.ITEM_NORMAL) views_max_image_id = wx.NewId() views_menu.Append(views_max_image_id, "&Maximum image size\tCtrl-1", "Activate maximum image view size layout.", wx.ITEM_NORMAL) self.menubar.Append(views_menu, "&Views") # tell FrameManager to manage this frame self._mgr = wx.aui.AuiManager() self._mgr.SetManagedWindow(self) self._mgr.AddPane(self._create_rwi_pane(), wx.aui.AuiPaneInfo(). Name("rwi").Caption("3D Renderer"). Center(). BestSize(wx.Size(600,800)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_controls_pane(), wx.aui.AuiPaneInfo(). Name("controls").Caption("Controls"). Top(). BestSize(wx.Size(1000,75)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_overlay_slices_pane(), wx.aui.AuiPaneInfo(). Name("overlay").Caption("Emphysema Overlay"). Right(). BestSize(wx.Size(400,400)). CloseButton(False).MaximizeButton(True)) self._mgr.AddPane(self._create_original_slices_pane(), wx.aui.AuiPaneInfo(). Name("original").Caption("Original Scan"). Right(). BestSize(wx.Size(400,400)). CloseButton(False).MaximizeButton(True)) self.SetMinSize(wx.Size(400, 300)) # first we save this default perspective with all panes # visible self._perspectives = {} self._perspectives['default'] = self._mgr.SavePerspective() # then we hide all of the panes except the renderer self._mgr.GetPane("controls").Hide() self._mgr.GetPane("overlay").Hide() self._mgr.GetPane("original").Hide() # save the perspective again self._perspectives['max_image'] = self._mgr.SavePerspective() # and put back the default perspective / view self._mgr.LoadPerspective(self._perspectives['default']) # finally tell the AUI manager to do everything that we've # asked self._mgr.Update() # we bind the views events here, because the functionality is # completely encapsulated in the frame and does not need to # round-trip to the DICOMBrowser main module. self.Bind(wx.EVT_MENU, self._handler_default_view, id=views_default_id) self.Bind(wx.EVT_MENU, self._handler_max_image_view, id=views_max_image_id) self.CreateStatusBar() self.SetStatusText("This is the statusbar ^^") def close(self): """Selfdestruct :) """ self.Destroy() def _create_rwi_pane(self): """Create a RenderWindowInteractor panel """ panel = wx.Panel(self, -1) self.rwi = wxVTKRenderWindowInteractor(panel, -1, (600,800)) self.button1 = wx.Button(panel, -1, "Reset Camera") self.button2 = wx.Button(panel, -1, "Reset All") button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(self.button1) button_sizer.Add(self.button2) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.rwi, 1, wx.EXPAND|wx.BOTTOM, 7) sizer1.Add(button_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_controls_pane(self): """Create a pane for the controls (containing the threshold sliders and buttons for setting default or calculated values) """ panel = wx.Panel(self, -1) self.upper_slider = wx.Slider(panel, -1, -950, -1100, -900, (0, 0), (300, 50),wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) self.label = wx.StaticText(panel, -1, "Emfysema Threshold (HU)" , wx.Point(0, 0)) self.label.SetForegroundColour(wx.Colour(127,0,255)) self.lower_slider = wx.Slider(panel, -1, -970, -1100, -900, (0, 0), (300, 50),wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS) self.label2 = wx.StaticText(panel, -1, "Severe Emfysema Threshold (HU)" , wx.Point(0, 0)) self.label2.SetForegroundColour(wx.Colour(255,0,0)) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.upper_slider) sizer.Add(self.label) sizer2 = wx.BoxSizer(wx.VERTICAL) sizer2.Add(self.lower_slider) sizer2.Add(self.label2) self.button5 = wx.Button(panel, -1, "-950 / -970 HU",pos=(8, 8), size=(175, 28)) self.button6 = wx.Button(panel, -1, "12% / 10% Lowest HU",pos=(8, 8), size=(175, 28)) button_sizer = wx.BoxSizer(wx.VERTICAL) button_sizer.Add(self.button5) button_sizer.Add(self.button6) slider_sizer = wx.BoxSizer(wx.HORIZONTAL) slider_sizer.Add(sizer) slider_sizer.Add(sizer2) slider_sizer.Add(button_sizer) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(slider_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_overlay_slices_pane(self): """Create a RenderWindowInteractor for the original data and added emphysema overlay """ panel = wx.Panel(self, -1) self.overlay = wxVTKRenderWindowInteractor(panel, -1, (400,400)) self.button3 = wx.Button(panel, -1, "Reset Camera") self.button4 = wx.Button(panel, -1, "Reset All") button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(self.button3) button_sizer.Add(self.button4) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.overlay, 1, wx.EXPAND|wx.BOTTOM, 7) sizer1.Add(button_sizer) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def _create_original_slices_pane(self): """Create a RenderWindowInteractor for the original data and added emphysema overlay """ panel = wx.Panel(self, -1) self.original = wxVTKRenderWindowInteractor(panel, -1, (400,400)) sizer1 = wx.BoxSizer(wx.VERTICAL) sizer1.Add(self.original, 1, wx.EXPAND|wx.BOTTOM, 7) tl_sizer = wx.BoxSizer(wx.VERTICAL) tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7) panel.SetSizer(tl_sizer) tl_sizer.Fit(panel) return panel def render(self): """Update embedded RWI, i.e. update the image. """ self.rwi.Render() self.overlay.Render() self.original.Render() def _handler_default_view(self, event): """Event handler for when the user selects View | Default from the main menu. """ self._mgr.LoadPerspective( self._perspectives['default']) def _handler_max_image_view(self, event): """Event handler for when the user selects View | Max Image from the main menu. """ self._mgr.LoadPerspective( self._perspectives['max_image'])
Python
class EmphysemaViewer: kits = ['vtk_kit'] cats = ['Viewers'] help = """Module to visualize lungemphysema from a CT-thorax scan and a lung mask. EmphysemaViewer consists of a volume rendering and two linked slice-based views; one with the original data and one with an emphysema overlay. The volume rendering shows 3 contours: the lungedges and 2 different contours of emphysema; a normal one and a severe one. There are two ways of setting the emphysema values. - The first way is choosing the 'default' values, which are literature-based. They are set on -950 HU (emphysema) and -970 HU (severe). - The other way is a computational way: The lowest 11% values, that are present in the data are marked as emphysema, the lowest 8,5% values are marked as severe emphysema. The theory behind this is the hypothesis that the histograms of emphysema patients differ from healthy people in a way that in emphysema patients there are relatively more lower values present. In both ways you can finetune the values, or completely change them (if you want to). After loading your image data and mask data, you can inspect the data and examine the severity of the emphysema of the patient. Controls:\n LMB: The left mouse button can be used to rotate objects in the 3D scene, or to poll Houndsfield Units in areas of interest (click and hold to see the values)\n RMB: For the slice viewers, you can set the window and level values by clicking and holding the right mouse button in a slice and moving your mouse. You can see the current window and level values in the bottom of the viewer. Outside of the slice, this zooms the camera in and out\n MMB: The middle mouse button enables stepping through the slices if clicked and held in the center of the slice. When clicking on de edges of a slice, this re-orients the entire slice. Outside of the slice, this pans the camera\n Scrollwheel: The scrollwheel can be used for zooming in and out of a scene, but also for sliceviewing if used with the CTRL- or SHIFT-key\n SHIFT: By holding the SHIFT-key, it is possible to use the mouse scrollwheel to scroll through the slices.\n CTRL: Holding the CTRL-key does the same, but enables stepping through the data in steps of 10 slices.\n """
Python
# EmphysemaViewer by Corine Slagboom & Noeska Smit # # # Based on SkeletonAUIViewer: # Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. # skeleton of an AUI-based viewer module # copy and modify for your own purposes. # set to False for 3D viewer, True for 2D image viewer IMAGE_VIEWER = True # import the frame, i.e. the wx window containing everything import EmphysemaViewerFrame # and do a reload, so that the GUI is also updated at reloads of this # module. reload(EmphysemaViewerFrame) from module_kits.misc_kit import misc_utils from module_base import ModuleBase from module_mixins import IntrospectModuleMixin from comedi_utils import CMSliceViewer from comedi_utils import SyncSliceViewers import module_utils import os import sys import traceback import vtk import wx class EmphysemaViewer(IntrospectModuleMixin, ModuleBase): """Module to visualize lungemphysema in a CT scan. A lung mask is also needed. EmphysemaViewer consists of a volume rendering and two linked slice-based views; one with the original data and one with an emphysema overlay. The volume rendering shows 3 contours: the lungedges and 2 different contours of emphysema; a normal one and a severe one. There are two ways of setting the emphysema values. - The first way is choosing the 'default' values, which are literature-based. They are set on -950 HU (emphysema) and -970 HU (severe). - The other way is a computational way: The lowest 11% values, that are present in the data are marked as emphysema, the lowest 8,5% values are marked as severe emphysema. The theory behind this is the hypothesis that the histograms of emphysema patients differ from healthy people in a way that in emphysema patients there are relatively more lower values present. In both ways you can finetune the values, or completely change them (if you want to). After loading your image data and mask data, you can inspect the data and examine the severity of the emphysema of the patient. Controls: LMB: The left mouse button can be used to rotate objects in the 3D scene, or to poll Houndsfield Units in areas of interest (click and hold to see the values)\n RMB: For the slice viewers, you can set the window and level values by clicking and holding the right mouse button in a slice and moving your mouse. You can see the current window and level values in the bottom of the viewer. Outside of the slice, this zooms the camera in and out\n MMB: The middle mouse button enables stepping through the slices if clicked and held in the center of the slice. When clicking on de edges of a slice, this re-orients the entire slice. Outside of the slice, this pans the camera\n Scrollwheel: The scrollwheel can be used for zooming in and out of a scene, but also for sliceviewing if used with the CTRL- or SHIFT-key\n SHIFT: By holding the SHIFT-key, it is possible to use the mouse scrollwheel to scroll through the slices.\n CTRL: Holding the CTRL-key does the same, but enables stepping through the data in steps of 10 slices.\n """ def __init__(self, module_manager): """Standard constructor. All DeVIDE modules have these, we do the required setup actions. """ # we record the setting here, in case the user changes it # during the lifetime of this model, leading to different # states at init and shutdown. self.IMAGE_VIEWER = IMAGE_VIEWER # we need all this for our contours self.mask_data = None self.image_data = None self.lungVolume = None self.contour_severe_actor = vtk.vtkActor() self.contour_moderate_actor = vtk.vtkActor() self.contour_lungedge_actor = vtk.vtkActor() self.severe_mapper = vtk.vtkPolyDataMapper() self.severe_mapper.ScalarVisibilityOff() self.moderate_mapper = vtk.vtkPolyDataMapper() self.moderate_mapper.ScalarVisibilityOff() self.lung_mapper = vtk.vtkPolyDataMapper() self.lung_mapper.ScalarVisibilityOff() self.contour_severe_actor.SetMapper(self.severe_mapper) self.contour_severe_actor.GetProperty().SetColor(1,0,0) self.contour_severe_actor.GetProperty().SetOpacity(0.5) self.contour_moderate_actor.SetMapper(self.moderate_mapper) self.contour_moderate_actor.GetProperty().SetColor(0.5,0,1) self.contour_moderate_actor.GetProperty().SetOpacity(0.25) self.contour_lungedge_actor.SetMapper(self.lung_mapper) self.contour_lungedge_actor.GetProperty().SetColor(0.9,0.9,0.9) self.contour_lungedge_actor.GetProperty().SetOpacity(0.1) ModuleBase.__init__(self, module_manager) # create the view frame self._view_frame = module_utils.instantiate_module_view_frame( self, self._module_manager, EmphysemaViewerFrame.EmphysemaViewerFrame) # change the title to something more spectacular (or at least something non-default) self._view_frame.SetTitle('EmphysemaViewer') # create the necessary VTK objects: we only need a renderer, # the RenderWindowInteractor in the view_frame has the rest. self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.5,0.5,0.5) self._view_frame.rwi.GetRenderWindow().AddRenderer(self.ren) self.ren.AddActor(self.contour_severe_actor) self.ren.AddActor(self.contour_moderate_actor) self.ren.AddActor(self.contour_lungedge_actor) self.ren2 = vtk.vtkRenderer() self.ren2.SetBackground(0.5,0.5,0.5) self._view_frame.overlay.GetRenderWindow().AddRenderer(self.ren2) self.slice_viewer1 = CMSliceViewer(self._view_frame.overlay, self.ren2) self.ren3 = vtk.vtkRenderer() self.ren3.SetBackground(0.5,0.5,0.5) self._view_frame.original.GetRenderWindow().AddRenderer(self.ren3) self.slice_viewer2 = CMSliceViewer(self._view_frame.original, self.ren3) self.slice_viewer3 = CMSliceViewer(self._view_frame.rwi, self.ren) self.sync = SyncSliceViewers() self.sync.add_slice_viewer(self.slice_viewer1) self.sync.add_slice_viewer(self.slice_viewer2) self.sync.add_slice_viewer2(self.slice_viewer3) # hook up all event handlers self._bind_events() # anything you stuff into self._config will be saved self._config.last_used_dir = '' # make our window appear (this is a viewer after all) self.view() # all modules should toggle this once they have shown their # views. self.view_initialised = True # apply config information to underlying logic self.sync_module_logic_with_config() # then bring it all the way up again to the view self.sync_module_view_with_logic() def close(self): """Clean-up method called on all DeVIDE modules when they are deleted. FIXME: Still get a nasty X error :( """ # with this complicated de-init, we make sure that VTK is # properly taken care of self.ren.RemoveAllViewProps() self.ren2.RemoveAllViewProps() self.ren3.RemoveAllViewProps() # this finalize makes sure we don't get any strange X # errors when we kill the module. self.slice_viewer1.close() self.slice_viewer2.close() self.slice_viewer3.close() self._view_frame.rwi.GetRenderWindow().Finalize() self._view_frame.rwi.SetRenderWindow(None) self._view_frame.overlay.GetRenderWindow().Finalize() self._view_frame.overlay.SetRenderWindow(None) self._view_frame.original.GetRenderWindow().Finalize() self._view_frame.original.SetRenderWindow(None) del self._view_frame.rwi del self._view_frame.overlay del self._view_frame.original del self.slice_viewer3 del self.slice_viewer2 del self.slice_viewer1 # done with VTK de-init # now take care of the wx window self._view_frame.close() # then shutdown our introspection mixin IntrospectModuleMixin.close(self) def get_input_descriptions(self): # define this as a tuple of input descriptions if you want to # take input data e.g. return ('vtkPolyData', 'my kind of # data') return () def get_output_descriptions(self): # define this as a tuple of output descriptions if you want to # generate output data. return () def set_input(self, idx, input_stream): # this gets called right before you get executed. take the # input_stream and store it so that it's available during # execute_module() pass def get_output(self, idx): # this can get called at any time when a consumer module wants # you output data. pass def execute_module(self): # when it's you turn to execute as part of a network # execution, this gets called. pass def logic_to_config(self): pass def config_to_logic(self): pass def config_to_view(self): pass def view_to_config(self): pass def view(self): self._view_frame.Show() self._view_frame.Raise() # because we have an RWI involved, we have to do this # SafeYield, so that the window does actually appear before we # call the render. If we don't do this, we get an initial # empty renderwindow. wx.SafeYield() self.render() def create_volumerender(self, contourValueModerate, contourValueSevere): """Creates a volumerender of the masked data using iso-contour surfaces created by the Marching Cubes algorithm at the specified contourvalues. """ self._view_frame.SetStatusText("Creating Volumerender...") self.image_data mask = vtk.vtkImageMask() severeFraction = 0.10 moderateFraction = 0.12 # We only want to contour the lungs, so mask it mask.SetMaskInput(self.mask_data) mask.SetInput(self.image_data) mask.Update() self.lungVolume = mask.GetOutput() if contourValueModerate == 0 and contourValueSevere == 0: # This means we get to calculate the percentual values ourselves! scalars = self.lungVolume.GetScalarRange() range = scalars[1]-scalars[0] contourValueSevere = scalars[0]+range*severeFraction contourValueModerate = scalars[0]+range*moderateFraction self._view_frame.upper_slider.SetValue(contourValueModerate) self._view_frame.lower_slider.SetValue(contourValueSevere) self.create_overlay(contourValueModerate,contourValueSevere) # Create the contours self.adjust_contour(self.lungVolume, contourValueSevere, self.severe_mapper) self.adjust_contour(self.lungVolume, contourValueModerate, self.moderate_mapper) #self.adjust_contour(self.mask_data, 0.5, self.lung_mapper) self.create_lungcontour() # Set the camera to a nice view cam = self.ren.GetActiveCamera() cam.SetPosition(0,-100,0) cam.SetFocalPoint(0,0,0) cam.SetViewUp(0,0,1) self.ren.ResetCamera() self.render() self._view_frame.SetStatusText("Created Volumerender") def adjust_contour(self, volume, contourValue, mapper): """Adjust or create an isocontour using the Marching Cubes surface at the given value using the given mapper """ self._view_frame.SetStatusText("Calculating new volumerender...") contour = vtk.vtkMarchingCubes() contour.SetValue(0,contourValue) contour.SetInput(volume) mapper.SetInput(contour.GetOutput()) mapper.Update() self.render() self._view_frame.SetStatusText("Calculated new volumerender") def create_lungcontour(self): """Create a lungcontour using the Marching Cubes algorithm and smooth the surface """ self._view_frame.SetStatusText("Calculating lungcontour...") contourLung = vtk.vtkMarchingCubes() contourLung.SetValue(0,1) contourLung.SetInput(self.mask_data) smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInput(contourLung.GetOutput()) smoother.BoundarySmoothingOn() smoother.SetNumberOfIterations(40) smoother.Update() self.lung_mapper.SetInput(smoother.GetOutput()) self.lung_mapper.Update() self._view_frame.SetStatusText("Calculated lungcontour") def create_overlay(self, emphysemavalue, severeemphysemavalue): """Creates an overlay for the slice-based volume view 0: no emphysema 1: moderate emphysema 2: severe emphysema """ self._view_frame.SetStatusText("Creating Overlay...") mask = vtk.vtkImageMask() mask2 = vtk.vtkImageMask() threshold = vtk.vtkImageThreshold() threshold2 = vtk.vtkImageThreshold() math=vtk.vtkImageMathematics() mask.SetInput(self.image_data) mask.SetMaskInput(self.mask_data) threshold.SetInput(mask.GetOutput()) threshold.ThresholdByLower(emphysemavalue) threshold.SetOutValue(0) threshold.SetInValue(1) threshold2.SetInput(mask.GetOutput()) threshold2.ThresholdByLower(severeemphysemavalue) threshold2.SetOutValue(1) threshold2.SetInValue(2) math.SetOperationToMultiply() math.SetInput1(threshold.GetOutput()) math.SetInput2(threshold2.GetOutput()) math.Update() overlay = math.GetOutput() self.slice_viewer1.set_overlay_input(None) self.slice_viewer1.set_overlay_input(overlay) self.render() self._view_frame.SetStatusText("Created Overlay") def load_data_from_file(self, file_path): """Loads scanvolume data from file. Also sets the volume as input for the sliceviewers """ self._view_frame.SetStatusText("Opening file: %s..." % (file_path)) filename = os.path.split(file_path)[1] fileBaseName =os.path.splitext(filename)[0] reader = vtk.vtkMetaImageReader() reader.SetFileName(file_path) reader.Update() self.image_data = reader.GetOutput() self.slice_viewer1.set_input(self.image_data) self.slice_viewer1.reset_camera() self.slice_viewer1.render() self.slice_viewer2.set_input(self.image_data) self.slice_viewer2.reset_camera() self.slice_viewer2.render() self.slice_viewer3.set_input(self.image_data) self.slice_viewer3.render() self.slice_viewer3.set_opacity(0.1) cam = self.ren.GetActiveCamera() cam.SetPosition(0,-100,0) cam.SetFocalPoint(0,0,0) cam.SetViewUp(0,0,1) self.ren.ResetCamera() if (self.mask_data) is not None: # We can start calculating the volumerender self.create_volumerender(0,0) else: self._view_frame.SetStatusText("Opened file") def load_mask_from_file(self, file_path): """Loads mask file """ self._view_frame.SetStatusText( "Opening mask: %s..." % (file_path)) filename = os.path.split(file_path)[1] fileBaseName =os.path.splitext(filename)[0] reader = vtk.vtkMetaImageReader() reader.SetFileName(file_path) reader.Update() self.mask_data = reader.GetOutput() if (self.image_data) is not None: self.create_volumerender(0,0) else: self._view_frame.SetStatusText("Opened mask file") def save_to_file(self, file_path): """Save data from main renderwindow (the contour one) to a PNG-file """ w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(self._view_frame.rwi.GetRenderWindow()); w2i.Update() writer = vtk.vtkPNGWriter() writer.SetInput(w2i.GetOutput()) writer.SetFileName(file_path) writer.Update() result = writer.Write() if result == 0: self._view_frame.SetStatusText( "Saved file") else: self._view_frame.SetStatusText( "Saved file to: %s..." % (file_path)) def _bind_events(self): """Bind wx events to Python callable object event handlers. """ vf = self._view_frame vf.Bind(wx.EVT_MENU, self._handler_file_open, id = vf.id_file_open) vf.Bind(wx.EVT_MENU, self._handler_mask_open, id = vf.id_mask_open) vf.Bind(wx.EVT_MENU, self._handler_file_save, id = vf.id_mask_save) self._view_frame.button1.Bind(wx.EVT_BUTTON, self._handler_button1) self._view_frame.button2.Bind(wx.EVT_BUTTON, self._handler_button2) self._view_frame.button3.Bind(wx.EVT_BUTTON, self._handler_button3) self._view_frame.button4.Bind(wx.EVT_BUTTON, self._handler_button4) self._view_frame.button5.Bind(wx.EVT_BUTTON, self._handler_button5) self._view_frame.button6.Bind(wx.EVT_BUTTON, self._handler_button6) self._view_frame.upper_slider.Bind(wx.EVT_SCROLL_CHANGED, self._handler_slider1) self._view_frame.lower_slider.Bind(wx.EVT_SCROLL_CHANGED, self._handler_slider2) def _handler_button1(self, event): """Reset the camera of the main render window """ self.ren.ResetCamera() self.render() def _handler_button2(self, event): """Reset all for the main render window """ cam = self.ren.GetActiveCamera() cam.SetPosition(0,-100,0) cam.SetFocalPoint(0,0,0) cam.SetViewUp(0,0,1) self.ren.ResetCamera() self.render() def _handler_button3(self, event): """Reset the camera for the sliceviewers """ self.slice_viewer1.reset_camera() self.slice_viewer2.reset_camera() self.render() def _handler_button4(self, event): """Reset all for the sliceviewers """ self.slice_viewer1.reset_to_default_view(2) self.slice_viewer2.reset_to_default_view(2) orientations = [2, 0, 1] for i, ipw in enumerate(self.slice_viewer1.ipws): ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) self.render() for i, ipw in enumerate(self.slice_viewer2.ipws): ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) self.render() def _handler_button5(self, event): """Adjust the contourvalues to values recommended in literature """ if self.lungVolume == None: return else: self._view_frame.upper_slider.SetValue(-950) self._view_frame.lower_slider.SetValue(-970) self.adjust_contour(self.lungVolume, -950, self.moderate_mapper) self.adjust_contour(self.lungVolume, -970, self.severe_mapper) self.create_overlay(-950,-970) def _handler_button6(self, event): """Adjust the contourvalues to values calculated from data """ if self.lungVolume == None: return else: self.create_volumerender(0, 0) def _handler_file_open(self, event): """Handler for file opening """ filters = 'Volume files (*.mhd)|*.mhd;' dlg = wx.FileDialog(self._view_frame, "Please choose a CT-thorax file", self._config.last_used_dir, "", filters, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() self._config.last_used_dir=dlg.GetDirectory() full_file_path = "%s/%s" % (self._config.last_used_dir, filename) self.load_data_from_file(full_file_path) dlg.Destroy() def _handler_mask_open(self, event): """Handler for mask opening """ filters = 'Mask files (*.mhd;#.mha)|*.mhd;*mha;' dlg = wx.FileDialog(self._view_frame, "Please choose a CT-thorax mask file", self._config.last_used_dir, "", filters, wx.OPEN) if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() self._config.last_used_dir=dlg.GetDirectory() full_file_path = "%s/%s" % (self._config.last_used_dir, filename) self.load_mask_from_file(full_file_path) dlg.Destroy() def _handler_file_save(self, event): """Handler for filesaving """ self._view_frame.SetStatusText( "Saving file...") filters = 'png file (*.png)|*.png' dlg = wx.FileDialog(self._view_frame, "Choose a destination", self._config.last_used_dir, "", filters, wx.SAVE) if dlg.ShowModal() == wx.ID_OK: filename=dlg.GetFilename() self._config.last_used_dir=dlg.GetDirectory() file_path = "%s/%s" % (self._config.last_used_dir, filename) self.save_to_file(file_path) dlg.Destroy() self._view_frame.SetStatusText( "Saved file") def _handler_slider1(self, event): """Handler for slider adjustment (Severe emphysema) """ if self.lungVolume == None: return else: contourValue = self._view_frame.upper_slider.GetValue() self.adjust_contour(self.lungVolume, contourValue, self.moderate_mapper) self.create_overlay(contourValue, self._view_frame.lower_slider.GetValue()) def _handler_slider2(self, event): """Handler for slider adjustment (Moderate emphysema) """ if self.lungVolume == None: return else: contourValue = self._view_frame.lower_slider.GetValue() self.adjust_contour(self.lungVolume, contourValue, self.severe_mapper) self.create_overlay(self._view_frame.upper_slider.GetValue(),contourValue) def render(self): """Method that calls Render() on the embedded RenderWindow. Use this after having made changes to the scene. """ self._view_frame.render() self.slice_viewer1.render()
Python
# Copyright (c) Charl P. Botha, TU Delft. # All rights reserved. # See COPYRIGHT for details. # --------------------------------------- # Edited by Corine Slagboom & Noeska Smit to add possibility of adding overlay to the sliceviewer and some special synching. # And by edited we mean mutilated :) from module_kits.vtk_kit.utils import DVOrientationWidget import operator import vtk import wx class SyncSliceViewers: """Class to link a number of CMSliceViewer instances w.r.t. camera. FIXME: consider adding option to block certain slice viewers from participation. Is this better than just removing them? """ def __init__(self): # store all slice viewer instances that are being synced self.slice_viewers = [] # edit nnsmit self.slice_viewers2 = [] # end edit self.observer_tags = {} # if set to False, no syncing is done. # user is responsible for doing the initial sync with sync_all # after this variable is toggled from False to True self.sync = True def add_slice_viewer(self, slice_viewer): if slice_viewer in self.slice_viewers: return # we'll use this to store all observer tags for this # slice_viewer t = self.observer_tags[slice_viewer] = {} istyle = slice_viewer.rwi.GetInteractorStyle() # the following two observers are workarounds for a bug in VTK # the interactorstyle does NOT invoke an InteractionEvent at # mousewheel, so we make sure it does in our workaround # observers. t['istyle MouseWheelForwardEvent'] = \ istyle.AddObserver('MouseWheelForwardEvent', self._observer_mousewheel_forward) t['istyle MouseWheelBackwardEvent'] = \ istyle.AddObserver('MouseWheelBackwardEvent', self._observer_mousewheel_backward) # this one only gets called for camera interaction (of course) t['istyle InteractionEvent'] = \ istyle.AddObserver('InteractionEvent', lambda o,e: self._observer_camera(slice_viewer)) # this gets call for all interaction with the slice # (cursoring, slice pushing, perhaps WL) for idx in range(3): # note the i=idx in the lambda expression. This is # because that gets evaluated at define time, whilst the # body of the lambda expression gets evaluated at # call-time t['ipw%d InteractionEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('InteractionEvent', lambda o,e,i=idx: self._observer_ipw(slice_viewer, i)) t['ipw%d WindowLevelEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('WindowLevelEvent', lambda o,e,i=idx: self._observer_window_level(slice_viewer,i)) self.slice_viewers.append(slice_viewer) # edit nnsmit # not the prettiest 'fix' in the book, but unfortunately short on time def add_slice_viewer2(self, slice_viewer): if slice_viewer in self.slice_viewers: return # we'll use this to store all observer tags for this # slice_viewer t = self.observer_tags[slice_viewer] = {} istyle = slice_viewer.rwi.GetInteractorStyle() # the following two observers are workarounds for a bug in VTK # the interactorstyle does NOT invoke an InteractionEvent at # mousewheel, so we make sure it does in our workaround # observers. t['istyle MouseWheelForwardEvent'] = \ istyle.AddObserver('MouseWheelForwardEvent', self._observer_mousewheel_forward) t['istyle MouseWheelBackwardEvent'] = \ istyle.AddObserver('MouseWheelBackwardEvent', self._observer_mousewheel_backward) # this gets call for all interaction with the slice for idx in range(3): # note the i=idx in the lambda expression. This is # because that gets evaluated at define time, whilst the # body of the lambda expression gets evaluated at # call-time t['ipw%d InteractionEvent' % (idx,)] = \ slice_viewer.ipws[idx].AddObserver('InteractionEvent', lambda o,e,i=idx: self._observer_ipw(slice_viewer, i)) self.slice_viewers2.append(slice_viewer) #end edit def close(self): for sv in self.slice_viewers: self.remove_slice_viewer(sv) def _observer_camera(self, sv): """This observer will keep the cameras of all the participating slice viewers synched. It's only called when the camera is moved. """ if not self.sync: return cc = self.sync_cameras(sv) [sv.render() for sv in cc] def _observer_mousewheel_forward(self, vtk_o, vtk_e): vtk_o.OnMouseWheelForward() vtk_o.InvokeEvent('InteractionEvent') def _observer_mousewheel_backward(self, vtk_o, vtk_e): vtk_o.OnMouseWheelBackward() vtk_o.InvokeEvent('InteractionEvent') def _observer_ipw(self, slice_viewer, idx=0): """This is called whenever the user does ANYTHING with the IPW. """ if not self.sync: return cc = self.sync_ipws(slice_viewer, idx) [sv.render() for sv in cc] def _observer_window_level(self, slice_viewer, idx=0): """This is called whenever the window/level is changed. We don't have to render, because the SetWindowLevel() call does that already. """ if not self.sync: return self.sync_window_level(slice_viewer, idx) def remove_slice_viewer(self, slice_viewer): if slice_viewer in self.slice_viewers: # first remove all observers that we might have added t = self.observer_tags[slice_viewer] istyle = slice_viewer.rwi.GetInteractorStyle() istyle.RemoveObserver( t['istyle InteractionEvent']) istyle.RemoveObserver( t['istyle MouseWheelForwardEvent']) istyle.RemoveObserver( t['istyle MouseWheelBackwardEvent']) for idx in range(3): ipw = slice_viewer.ipws[idx] ipw.RemoveObserver( t['ipw%d InteractionEvent' % (idx,)]) ipw.RemoveObserver( t['ipw%d WindowLevelEvent' % (idx,)]) # then delete our record of these observer tags del self.observer_tags[slice_viewer] # then delete our record of the slice_viewer altogether idx = self.slice_viewers.index(slice_viewer) del self.slice_viewers[idx] def sync_cameras(self, sv, dest_svs=None): """Sync all cameras to that of sv. Returns a list of changed SVs (so that you know which ones to render). """ cam = sv.renderer.GetActiveCamera() pos = cam.GetPosition() fp = cam.GetFocalPoint() vu = cam.GetViewUp() ps = cam.GetParallelScale() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if not other_sv is sv: other_ren = other_sv.renderer other_cam = other_ren.GetActiveCamera() other_cam.SetPosition(pos) other_cam.SetFocalPoint(fp) other_cam.SetViewUp(vu) # you need this too, else the parallel mode does not # synchronise. other_cam.SetParallelScale(ps) other_ren.UpdateLightsGeometryToFollowCamera() other_ren.ResetCameraClippingRange() changed_svs.append(other_sv) return changed_svs def sync_ipws(self, sv, idx=0, dest_svs=None): """Sync all slice positions to that of sv. Returns a list of changed SVs so that you know on which to call render. """ ipw = sv.ipws[idx] o,p1,p2 = ipw.GetOrigin(), \ ipw.GetPoint1(), ipw.GetPoint2() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if other_sv is not sv: # nnsmit edit if other_sv.overlay_active == 1: for i, ipw_overlay in enumerate(other_sv.overlay_ipws): other_sv.observer_sync_overlay(sv.ipws,i) # end edit other_ipw = other_sv.ipws[idx] # we only synchronise slice position if it's actually # changed. if o != other_ipw.GetOrigin() or \ p1 != other_ipw.GetPoint1() or \ p2 != other_ipw.GetPoint2(): other_ipw.SetOrigin(o) other_ipw.SetPoint1(p1) other_ipw.SetPoint2(p2) other_ipw.UpdatePlacement() changed_svs.append(other_sv) # edit nnsmit # This fix is so nasty it makes me want to cry # TODO fix it properly :) if len(self.slice_viewers2) != 0: for other_sv in self.slice_viewers2: if other_sv is not sv: if other_sv.overlay_active == 1: for i, ipw_overlay in enumerate(other_sv.overlay_ipws): other_sv.observer_sync_overlay(sv.ipws,i) other_ipw = other_sv.ipws[idx] # we only synchronise slice position if it's actually # changed. if o != other_ipw.GetOrigin() or \ p1 != other_ipw.GetPoint1() or \ p2 != other_ipw.GetPoint2(): other_ipw.SetOrigin(o) other_ipw.SetPoint1(p1) other_ipw.SetPoint2(p2) other_ipw.UpdatePlacement() other_sv.render() # end edit return changed_svs def sync_window_level(self, sv, idx=0, dest_svs=None): """Sync all window level settings with that of SV. Returns list of changed SVs: due to the SetWindowLevel call, these have already been rendered! """ ipw = sv.ipws[idx] w,l = ipw.GetWindow(), ipw.GetLevel() if dest_svs is None: dest_svs = self.slice_viewers changed_svs = [] for other_sv in dest_svs: if other_sv is not sv: other_ipw = other_sv.ipws[idx] if w != other_ipw.GetWindow() or \ l != other_ipw.GetLevel(): other_ipw.SetWindowLevel(w,l,0) changed_svs.append(other_sv) return changed_svs def sync_all(self, sv, dest_svs=None): """Convenience function that performs all syncing possible of dest_svs to sv. It also take care of making only the necessary render calls. """ # FIXME: take into account all other slices too. c1 = set(self.sync_cameras(sv, dest_svs)) c2 = set(self.sync_ipws(sv, 0, dest_svs)) c3 = set(self.sync_window_level(sv, 0, dest_svs)) # we only need to call render on SVs that are in c1 or c2, but # NOT in c3, because WindowLevel syncing already does a # render. Use set operations for this: c4 = (c1 | c2) - c3 [isv.render() for isv in c4] ########################################################################### class CMSliceViewer: """Simple class for enabling 1 or 3 ortho slices in a 3D scene. """ def __init__(self, rwi, renderer): # nnsmit-edit self.overlay_active = 0; # end edit self.rwi = rwi self.renderer = renderer istyle = vtk.vtkInteractorStyleTrackballCamera() rwi.SetInteractorStyle(istyle) # we unbind the existing mousewheel handler so it doesn't # interfere rwi.Unbind(wx.EVT_MOUSEWHEEL) rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel) self.ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)] lut = self.ipws[0].GetLookupTable() for ipw in self.ipws: ipw.SetInteractor(rwi) ipw.SetLookupTable(lut) # nnsmit-edit self.overlay_ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)] lut2 = self.overlay_ipws[0].GetLookupTable() lut2.SetNumberOfTableValues(3) lut2.SetTableValue(0,0,0,0,0) lut2.SetTableValue(1,0.5,0,1,1) lut2.SetTableValue(2,1,0,0,1) lut2.Build() for ipw_overlay in self.overlay_ipws: ipw_overlay.SetInteractor(rwi) ipw_overlay.SetLookupTable(lut2) ipw_overlay.AddObserver('InteractionEvent', wx.EVT_MOUSEWHEEL) # now actually connect the sync_overlay observer for i,ipw in enumerate(self.ipws): ipw.AddObserver('InteractionEvent',lambda vtk_o, vtk_e, i=i: self.observer_sync_overlay(self.ipws,i)) # end edit # we only set the picker on the visible IPW, else the # invisible IPWs block picking! self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.005) self.ipws[0].SetPicker(self.picker) self.outline_source = vtk.vtkOutlineCornerFilter() m = vtk.vtkPolyDataMapper() m.SetInput(self.outline_source.GetOutput()) a = vtk.vtkActor() a.SetMapper(m) a.PickableOff() self.outline_actor = a self.dv_orientation_widget = DVOrientationWidget(rwi) # this can be used by clients to store the current world # position self.current_world_pos = (0,0,0) self.current_index_pos = (0,0,0) # nnsmit-edit def observer_sync_overlay(self,ipws,ipw_idx): # get the primary IPW pipw = ipws[ipw_idx] # get the overlay IPW oipw = self.overlay_ipws[ipw_idx] # get plane geometry from primary o,p1,p2 = pipw.GetOrigin(),pipw.GetPoint1(),pipw.GetPoint2() # and apply to the overlay oipw.SetOrigin(o) oipw.SetPoint1(p1) oipw.SetPoint2(p2) oipw.UpdatePlacement() # end edit def close(self): self.set_input(None) self.dv_orientation_widget.close() self.set_overlay_input(None) def activate_slice(self, idx): if idx in [1,2]: self.ipws[idx].SetEnabled(1) self.ipws[idx].SetPicker(self.picker) def deactivate_slice(self, idx): if idx in [1,2]: self.ipws[idx].SetEnabled(0) self.ipws[idx].SetPicker(None) def get_input(self): return self.ipws[0].GetInput() def get_world_pos(self, image_pos): """Given image coordinates, return the corresponding world position. """ idata = self.get_input() if not idata: return None ispacing = idata.GetSpacing() iorigin = idata.GetOrigin() # calculate real coords world = map(operator.add, iorigin, map(operator.mul, ispacing, image_pos[0:3])) def set_perspective(self): cam = self.renderer.GetActiveCamera() cam.ParallelProjectionOff() def set_parallel(self): cam = self.renderer.GetActiveCamera() cam.ParallelProjectionOn() # nnsmit edit def set_opacity(self,opacity): lut = self.ipws[0].GetLookupTable() lut.SetAlphaRange(opacity, opacity) lut.Build() self.ipws[0].SetLookupTable(lut) # end edit def _handler_mousewheel(self, event): # event.GetWheelRotation() is + or - 120 depending on # direction of turning. if event.ControlDown(): delta = 10 elif event.ShiftDown(): delta = 1 else: # if user is NOT doing shift / control, we pass on to the # default handling which will give control to the VTK # mousewheel handlers. self.rwi.OnMouseWheel(event) return if event.GetWheelRotation() > 0: self._ipw1_delta_slice(+delta) else: self._ipw1_delta_slice(-delta) self.render() self.ipws[0].InvokeEvent('InteractionEvent') def _ipw1_delta_slice(self, delta): """Move to the delta slices fw/bw, IF the IPW is currently aligned with one of the axes. """ ipw = self.ipws[0] if ipw.GetPlaneOrientation() < 3: ci = ipw.GetSliceIndex() ipw.SetSliceIndex(ci + delta) def render(self): self.rwi.GetRenderWindow().Render() # nnsmit edit # synch those overlays: if self.overlay_active == 1: for i, ipw_overlay in enumerate(self.overlay_ipws): self.observer_sync_overlay(self.ipws, i) # end edit def reset_camera(self): self.renderer.ResetCamera() cam = self.renderer.GetActiveCamera() cam.SetViewUp(0,-1,0) def reset_to_default_view(self, view_index): """ @param view_index 2 for XY """ if view_index == 2: cam = self.renderer.GetActiveCamera() # then make sure it's up is the right way cam.SetViewUp(0,-1,0) # just set the X,Y of the camera equal to the X,Y of the # focal point. fp = cam.GetFocalPoint() cp = cam.GetPosition() if cp[2] < fp[2]: z = fp[2] + (fp[2] - cp[2]) else: z = cp[2] cam.SetPosition(fp[0], fp[1], z) # first reset the camera self.renderer.ResetCamera() # nnsmit edit # synch overlays as well: if self.overlay_active == 1: for i, ipw_overlay in enumerate(self.overlay_ipws): ipw_overlay.SetSliceIndex(0) for i, ipw in enumerate(self.ipws): ipw.SetWindowLevel(500,-800,0) self.render() # end edit def set_input(self, input): ipw = self.ipws[0] ipw.DisplayTextOn() if input == ipw.GetInput(): return if input is None: # remove outline actor, else this will cause errors when # we disable the IPWs (they call a render!) self.renderer.RemoveViewProp(self.outline_actor) self.outline_source.SetInput(None) self.dv_orientation_widget.set_input(None) for ipw in self.ipws: # argh, this disable causes a render ipw.SetEnabled(0) ipw.SetInput(None) else: self.outline_source.SetInput(input) self.renderer.AddViewProp(self.outline_actor) orientations = [2, 0, 1] active = [1, 0, 0] for i, ipw in enumerate(self.ipws): ipw.SetInput(input) ipw.SetWindowLevel(500,-800,0) ipw.SetPlaneOrientation(orientations[i]) # axial ipw.SetSliceIndex(0) ipw.SetEnabled(active[i]) self.dv_orientation_widget.set_input(input) # nnsmit-edit # FIXME: Create pretty fix for this codeclone. def set_overlay_input(self, input): self.overlay_active = 1 ipw = self.overlay_ipws[0] if input == ipw.GetInput(): return if input is None: self.overlay_active = 0; for ipw_overlay in self.overlay_ipws: ipw_overlay.SetEnabled(0) ipw_overlay.SetInput(None) else: active = [1, 0, 0] orientations = [2, 0, 1] for i, ipw_overlay in enumerate(self.overlay_ipws): self.observer_sync_overlay(self.ipws, i) ipw_overlay.SetInput(input) ipw_overlay.SetPlaneOrientation(orientations[i]) # axial ipw_overlay.SetEnabled(active[i]) self.render() # end edit
Python
# $Id: pngWRT.py 2401 2006-12-20 20:29:15Z cpbotha $ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils WX_OPEN = 1 WX_SAVE = 2 class isolated_points_check(ScriptedConfigModuleMixin, ModuleBase): def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # ctor for this specific mixin # FilenameViewModuleMixin.__init__(self) self._input_image = None self._foreground_points = None self._background_points = None self._config.filename = '' configList = [ ('Result file name:', 'filename', 'base:str', 'filebrowser', 'Y/N result will be written to this file.', {'fileMode' : WX_SAVE, 'fileMask' : 'All files (*.*)|*.*'})] ScriptedConfigModuleMixin.__init__( self, configList, {'Module (self)' : self}) self.sync_module_logic_with_config() def close(self): # we play it safe... (the graph_editor/module_manager should have # disconnected us by now) for input_idx in range(len(self.get_input_descriptions())): self.set_input(input_idx, None) # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) ModuleBase.close(self) def get_input_descriptions(self): return ('Segmented image', 'Foreground points', 'Background points') def set_input(self, idx, input_stream): if idx == 0: self._input_image = input_stream elif idx == 1: self._foreground_points = input_stream else: self._background_points = input_stream def get_output_descriptions(self): return () def get_output(self, idx): raise Exception def logic_to_config(self): pass def config_to_logic(self): pass def execute_module(self): if not hasattr(self._input_image, 'GetClassName'): raise RuntimeError('Input image has wrong type') if not hasattr(self._foreground_points, 'devideType'): raise RuntimeError('Wrong type foreground points') if not hasattr(self._background_points, 'devideType'): raise RuntimeError('Wrong type background points') if not self._config.filename: raise RuntimeError('Result filename not specified') check = True for j in [i['discrete'] for i in self._foreground_points]: v = self._input_image.GetScalarComponentAsFloat( * list(j + (0,))) if v - 0.0 < 0.0000001: check = False break if check: for j in [i['discrete'] for i in self._background_points]: v = self._input_image.GetScalarComponentAsFloat( * list(j + (0,))) if v - 0.0 > 0.0000001: check = False break check_string = ['n', 'y'][int(check)] rf = file(self._config.filename, 'w') rf.write('%s\n' % (check_string,)) rf.close()
Python
# $Id$ from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtktud class gaussianKernel(ScriptedConfigModuleMixin, ModuleBase): """First test of a gaussian implicit kernel $Revision: 1.1 $ """ def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) # setup config self._config.order = 0 self._config.standardDeviation = 1.0 self._config.support = 3.0 * self._config.standardDeviation # and then our scripted config configList = [ ('Order: ', 'order', 'base:int', 'text', 'The order of the gaussian kernel (0-2).'), ('Standard deviation: ', 'standardDeviation', 'base:float', 'text', 'The standard deviation (width) of the gaussian kernel.'), ('Support: ', 'support', 'base:float', 'text', 'The support of the gaussian kernel.')] # mixin ctor ScriptedConfigModuleMixin.__init__(self, configList) # now create the necessary VTK modules self._gaussianKernel = vtktud.vtkGaussianKernel() # setup progress for the processObject # module_utils.setup_vtk_object_progress(self, self._superquadricSource, # "Synthesizing polydata.") self._createWindow( {'Module (self)' : self, 'vtkGaussianKernel' : self._gaussianKernel}) self.config_to_logic() self.syncViewWithLogic() def close(self): # this will take care of all display thingies ScriptedConfigModuleMixin.close(self) # and the baseclass close ModuleBase.close(self) # remove all bindings del self._gaussianKernel def execute_module(self): return () def get_input_descriptions(self): return () def set_input(self, idx, input_stream): raise Exception def get_output_descriptions(self): return ('vtkSeparableKernel',) def get_output(self, idx): return self._gaussianKernel def config_to_logic(self): # sanity check if self._config.standardDeviation < 0.0: self._config.standardDeviation = 0.0 if self._config.support < 0.0: self._config.support = 0.0 self._gaussianKernel.SetOrder( self._config.order ) self._gaussianKernel.SetStandardDeviation( self._config.standardDeviation ) self._gaussianKernel.SetSupport( self._config.support ) def logic_to_config(self): self._config.order = self._gaussianKernel.GetOrder() self._config.standardDeviation = self._gaussianKernel.GetStandardDeviation() self._config.support = self._gaussianKernel.GetSupport()
Python
from module_mixins import simpleVTKClassModuleBase import vtktud class imageCopyPad(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageCopyPad(), 'Extending image by copying border voxels.', ('vtkImageData',), ('vtkImageData',))
Python
from module_mixins import simpleVTKClassModuleBase import vtktud class imageExtentUnionizer(simpleVTKClassModuleBase): """This is the minimum you need to wrap a single VTK object. This __doc__ string will be replaced by the __doc__ string of the encapsulated VTK object, i.e. vtkStripper in this case. With these few lines, we have error handling, progress reporting, module help and also: the complete state of the underlying VTK object is also pickled, i.e. when you save and restore a network, any changes you've made to the vtkObject will be restored. """ def __init__(self, module_manager): simpleVTKClassModuleBase.__init__( self, module_manager, vtktud.vtkImageExtentUnionizer(), 'Image Extent Unionizer.', ('vtkImageData',), ('vtkImageData',))
Python