# -*- coding: utf-8 -*-
"""
#############################
数据分析工具,用来学习研究用
2013.6
#############################
"""
from operator import itemgetter
import wx, os ,re, time, sys,itertools
from wx.lib.masked import TimeCtrl
import logging
from lxml import etree
import numpy
import dateutil
from scipy.interpolate import interp2d
from numpy.core.fromnumeric import mean
import pylab
from pylab import *
import copy
import datetime
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
from matplotlib.dates import MONDAY, SATURDAY
from matplotlib.finance import quotes_historical_yahoo
from matplotlib.dates import MonthLocator, WeekdayLocator, DateFormatter
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages, FigureCanvasPdf
from mpl_toolkits.mplot3d import Axes3D
import cStringIO
from PIL import Image
import fnmatch
import glob
import zipfile
import operator
import socket
import smtplib
from _bisect import bisect_left, bisect_right
try:
import sympy
from sympy.matrices import Matrix
except:
print "sympy not found!"
import bisect
import difflib
import codecs
import matplotlib.ticker as mticker
#------------------------------------------
# global variables
IcConsMode = 1 #determines if a debug information is printed
EAversion='20151019'
pdf_vector_graphics=False #if False BMP image in pdf, better for printing, if there are a lot of events
EA_IC=''
ax_tc_mode=0
bottomlinestr=u' - FOR INTERNAL USAGE ONLY -\n \xa9 Siemens Healthcare GmbH (2015) - Dr. O.Baruth HC IM AX R&D IC SP - No responsibility is taken for the correctness of the results - \nv.'
send_mail=False # sends a mail if EA runs on server and and error occurs
senderAddress = 'oliver.baruth@siemens.com'
recipientAddress = 'oliver.baruth@siemens.com'
#------------------------------------------
def pydate2wxdate(date):
assert isinstance(date, (datetime.datetime, datetime.date))
tt = date.timetuple()
dmy = (tt[2], tt[1]-1, tt[0])
return wx.DateTimeFromDMY(*dmy)
def wxdate2pydate(date):
assert isinstance(date, wx.DateTime)
if date.IsValid():
ymd = map(int, date.FormatISODate().split('-'))
return datetime.date(*ymd)
else:
return None
#---- return the string with Umlaut replaced
def replaceUmlaut(myString):
if isinstance(myString,(float)): #do not touch floats
result = myString
elif isinstance(myString,(unicode)): # if it is already unicode, just replace the 'funny' characters
myString = re.sub("°", " (degr) ", myString)
myString = re.sub("\xb5", "_", myString)
myString = re.sub("%", " perc", myString)
result = unicodedata.normalize('NFKD', myString).encode('ascii','ignore')
else:
myString = re.sub("°", " (degr) ", myString)
myString = re.sub("\xb5", "_", myString)
myString = re.sub("%", " perc", myString)
try:
myString=myString.decode('utf-8')
except:
myString=unicode(myString,'latin1')
#myString=myString.decode('utf-8')
result=myString
#result = unicode(myString,'latin1') # if it is no unicode (data from life DB may be) convert, then replace
#result = unicodedata.normalize('NFKD', result).encode('ascii', 'ignore')
return result
def get_midpoint(a,v,b,w):
#P=a+l*v
#Q=b+k*w
#(P-Q)*v==0 !
#(P-Q)*w==0 !
#v*v=1
#w*w=1
av=np.dot(a,v.T)
bv=np.dot(b,v.T)
wv=np.dot(w,v.T) #=vw
aw=np.dot(a,w.T)
bw=np.dot(b,w.T)
#av+k-bv-l*wv==0 -> k=l*wv+bv-av
#aw+k*wv-bw-l==0 -> k=(l+bw-aw)/wv
#l*wv^2+bv*wv-av*wv-l-bw+aw=0
#l(wv^2-1)=(av-bv)*wv+bw-aw
if wv!=1:
l=((av-bv)*wv+bw-aw)/(wv*wv-1)
k=l*wv+bv-av
P=a+l*v
Q=b+k*w
mindpoint=(P+Q)/2.
else: #vectors parallel
mindpoint=(a+b)/2.
return mindpoint
#------------------------------------------
def calc_midpoints_from_sample(vdata):
N=len(vdata)
M=min(1000,N)
MP=np.zeros((M,3))
for i in range(M):
perm=np.random.permutation(arange(N))
n=perm[0]
m=perm[1]
MP[i]=get_midpoint(vdata[n][0],vdata[n][1],vdata[m][0],vdata[m][1])
return MP
#-----------------------------------------
def _ncycle(iterable,n):
"""
Method to create a generator from an iterable. It keeps the
current position of the iterable in memory. Each time the
next() method for the iterable is called, it will return the
next item. If there are no more items, it will cycle to the
first item.
"""
for item in itertools.cycle(iterable):
yield item
colors = _ncycle(('r','g','b','c','y','m','k'),1)
markers = _ncycle(('o','s','v','x','^','d','h','+','*','p','8','D'),1)
#------------------------------------------
class XEvent():
def __init__(self):
self.range=100000
#System specific data (read from system.caf.txt)
self.SN=0
self.tubetype=0
self.tubetype_str='n a'
self.numFoken=0
self.FDtype=''
self.SIDfactor=0
self.IR=0 #interventional reference point
self.plane='A'
self.SystemType=''
self.SystemShape=''
self.fr=[60,30,15,10,7.5,6,5,3.75,3,1.87,1,0.5,0.1] #Frequency in [Hz], 0.1=Einzelschuss
self.SW=[] #Software Version (String)
self.numEvents=0
self.PUN_SW='n a'
self.country='n a'
self.city='n a'
self.syngo_system_type='n a'
self.FD_A_name='n a'
self.FD_B_name='n a'
self.pat_time=[] #duration of intervention in [min], number of entries=number of patients
self.pat_out_time=[]
self.pat_in_time=[]
self.pat_idx=[] #number of start event of each study + last event+1
#X-ray event specific data
self.date=numpy.zeros(self.range) #Time of xray event
self.index=numpy.zeros(self.range) #internal number
self.current=numpy.zeros(self.range) #mean current of scene in [mA]
self.voltage=numpy.zeros(self.range) #mean voltage of scene in [kV]
self.time=numpy.zeros(self.range) #mean pulsetime of scene in [ms]
self.mAs=numpy.zeros(self.range) #mAs aus 391
self.filt=numpy.zeros(self.range) #Cu filter in [0.1 mm Cu]
self.SID=numpy.zeros(self.range) #SID at scene end??? in [cm]
self.was=numpy.zeros(self.range) #mean water value in [mm H2O]
self.frames=numpy.zeros(self.range) #number of frames in scene
self.frequency=numpy.zeros(self.range) #pulse rate in [1/s]
self.system_dose=numpy.zeros(self.range) #mean system dose
self.SysDose_with_ZDF=numpy.zeros(self.range) #physical system dose
self.focus=numpy.zeros(self.range)
self.mode=numpy.zeros(self.range)
self.zoom=numpy.zeros(self.range)
self.cran=numpy.zeros(self.range)
self.rao=numpy.zeros(self.range)
self.cran_a=numpy.zeros(self.range)
self.rao_a=numpy.zeros(self.range)
self.sid_a=numpy.zeros(self.range)
self.scu_base_rot =numpy.zeros(self.range)
self.alpha_orb =numpy.zeros(self.range) #tube axis rot
self.alpha_xray =numpy.zeros(self.range)
self.gamma =numpy.zeros(self.range) #Vergroesserungsfaktor
self.scu_carm_rot =numpy.zeros(self.range)
self.scu_carm_orb =numpy.zeros(self.range)
self.scu_table_rot =numpy.zeros(self.range)
self.scu_table_tilt =numpy.zeros(self.range)
self.scu_table_cradle =numpy.zeros(self.range)
self.cran_b=numpy.zeros(self.range)
self.rao_b=numpy.zeros(self.range)
self.sid_b=numpy.zeros(self.range)
self.scu_date_a=numpy.zeros(self.range)
self.scu_date_b=numpy.zeros(self.range)
self.scu_T1=numpy.zeros(self.range) #Table Pos
self.scu_T2=numpy.zeros(self.range) #Table Pos
self.scu_T3=numpy.zeros(self.range) #Table Pos
self.table_height=numpy.zeros(self.range) #zero position (iso centrum) 106cm over floor for all systypes except (ROS and MP) - EAS?
self.SOD=numpy.zeros(self.range)
self.HU=numpy.zeros(self.range)
self.prevHU=numpy.zeros(self.range)
self.FDmode=[]
self.Bsig=numpy.zeros(self.range)
self.Mfield=numpy.zeros(self.range)
self.DAP=numpy.zeros(self.range)
self.skindoserate=numpy.zeros(self.range)
self.skindose=numpy.zeros(self.range)
self.dose_per_mAs=numpy.zeros(self.range)
self.area=numpy.zeros(self.range)
self.maxarea=numpy.zeros(self.range)
self.scenelength=numpy.zeros(self.range)
self.dutycycle=numpy.zeros(self.range)
self.study=numpy.zeros(self.range)
self.offset=numpy.zeros(self.range)
self.wPawMode=numpy.zeros(self.range)
self.biplane=numpy.zeros(self.range) #0 mono, 1=biplane Master A, 2=Biplane Master B
self.BE_F1=numpy.zeros(self.range)
self.BE_F2=numpy.zeros(self.range)
self.BE_FG=numpy.zeros(self.range)
self.BE_total=numpy.zeros(self.range)
self.pat_number=numpy.zeros(self.range) #patient number
self._10Rlimit=numpy.zeros(self.range) #10R Grenze, 34cm vor FD, nur für Fluoro
self.OGP=[] #used OGP
self._3Dmode=[]
self.p1=numpy.zeros(self.range) #program number (from SYC 0056 set program)
self.p2=numpy.zeros(self.range) #program number (from SYC 0056 set program)
self.gridpulse=numpy.zeros(self.range) # if gridpulse is used (VD 10, Gigalix)
self.alt_acq=numpy.zeros(self.range)
self.arc_0x001A=numpy.zeros(self.range)
self.arc_0x001B=numpy.zeros(self.range)
self.arc_0x001C=numpy.zeros(self.range)
self.arc_0x001D=numpy.zeros(self.range)
self.arc_0x001E=numpy.zeros(self.range)
self.arc_0x0018=numpy.zeros(self.range)
self.arc_0x000A=numpy.zeros(self.range)
self.arc_0x000B=numpy.zeros(self.range)
self.arc_0x000C=numpy.zeros(self.range)
self.arc_0x0008=numpy.zeros(self.range)
self.arc_0x0007=numpy.zeros(self.range)
self.arc_0x0006=numpy.zeros(self.range)
self.arc_0x0005=numpy.zeros(self.range)
self.arc_0x0004=numpy.zeros(self.range)
self.arc_0x0003=numpy.zeros(self.range)
self.arc_0x0002=numpy.zeros(self.range)
self.arc_0x0001=numpy.zeros(self.range)
self.arc_0x0000=numpy.zeros(self.range)
self.arc_other=numpy.zeros(self.range)
self.arc_0x001A_frame= []
self.arc_0x001B_frame= []
self.arc_0x001C_frame= []
self.arc_0x001D_frame= []
self.arc_0x001E_frame= []
self.arc_0x0018_frame= []
self.arc_0x000A_frame= []
self.arc_0x000B_frame= []
self.arc_0x000C_frame= []
self.arc_0x0008_frame= []
self.arc_0x0007_frame= []
self.arc_0x0006_frame= []
self.arc_0x0005_frame= []
self.arc_0x0004_frame= []
self.arc_0x0003_frame= []
self.arc_0x0002_frame= []
self.arc_0x0001_frame= []
self.arc_0x0000_frame= []
self.arc_other_frame= []
self.grid_0x000A=numpy.zeros(self.range)
self.grid_0x0009=numpy.zeros(self.range)
self.grid_0x0008=numpy.zeros(self.range)
self.grid_0x0007=numpy.zeros(self.range)
self.grid_0x0006=numpy.zeros(self.range)
self.grid_0x0005=numpy.zeros(self.range)
self.grid_0x0004=numpy.zeros(self.range)
self.grid_0x0003=numpy.zeros(self.range)
self.grid_0x0002=numpy.zeros(self.range)
self.grid_0x0001=numpy.zeros(self.range)
self.grid_0x0000=numpy.zeros(self.range)
self.grid_other=numpy.zeros(self.range)
self.grid_0x000A_frame= []
self.grid_0x0009_frame= []
self.grid_0x0008_frame= []
self.grid_0x0007_frame= []
self.grid_0x0006_frame= []
self.grid_0x0005_frame= []
self.grid_0x0004_frame= []
self.grid_0x0003_frame= []
self.grid_0x0002_frame= []
self.grid_0x0001_frame= []
self.grid_0x0000_frame= []
self.grid_other_frame= []
self.soll_kV =[]
self.soll_ms =[]
self.soll_mA= []
self.soll_WW= []
self.soll_Szenenlaenge = []
self.ist_Szenenlaenge = []
self.soll_fd_dosis = []
self.maxPower_Sollzeit =[]
self.maxPower_Istzeit =[]
self.maxCurrentRev_punchthrough=numpy.zeros(self.range)
self.maxCurrentPrev =[]
self.maxCurrentRev =[]
self.maxPowerdyn=[]
self.heating_current=numpy.zeros(self.range)
self.emitter_temp=numpy.zeros(self.range)
self.tungst_evaporation_rate=numpy.zeros(self.range)
self.tungst_thickness=numpy.zeros(self.range)
self.tube_focal_spot_pos_table=[]
self.pat_skindose=[]
self.pat_dap=[]
self.axis_mode=[]
self.resolution=[]
# end of class XEvent
def get_tube_rot(cran,rao,gantry):
#Funktion wird nicht benutzt, nur zu Testzwecken und Erklaerung
#der Strahlerroationsvektor ergbit sich aus R2*[1,0,0].T= longitudinaler Einbau
#der Strahlerneigungsvektor alpha_orb der berechnet wird, ergibt sich aus
carm_rot=0 #zaehlt entgegen des Uhrzeigersinns den Winkel positiv
carm_orb=90 #zaehlt entgegen des Uhrzeigersinns den Winkel positiv
gantry=90
carm_rot_b=0 #zaehlt entgegen des Uhrzeigersinns den Winkel positiv
carm_orb_b=-90 #zaehlt entgegen des Uhrzeigersinns den Winkel positiv
gantry_rad=gantry*np.pi/180.
carm_rot_rad=carm_rot*np.pi/180.
carm_orb_rad=carm_orb*np.pi/180.
carm_rot_b_rad=carm_rot_b*np.pi/180.
carm_orb_b_rad=carm_orb_b*np.pi/180.
#Achsendefinition:
#x-Achse: Richtung Tisch (Tisch in 0,0,0 Position, aber nicht relativ zum Tisch); Kopfende Richtung Fussende
#y-Achse: senkrecht zur x-Achse in Ebene parallel zum Boden; von rechts nach links wenn man auf dem Tisch liegt
#z-Achse: senkrecht zu den beiden anderen Achsen, nach oben zeigend
#----------------------
#Plane A
#rotation around z-axis (B aus SCU 221), aber nicht benoetigt
R_gantry=np.matrix([[np.cos(gantry_rad),-np.sin(gantry_rad), 0],
[np.sin(gantry_rad), np.cos(gantry_rad), 0],
[0 ,0 , 1]])
#rotation around x-axis (C-arm_rot, aus scu 221)
R_outer=np.matrix([[1 ,0 ,0 ],
[0 ,np.cos(carm_rot_rad) ,np.sin(carm_rot_rad)],
[0 ,-np.sin(carm_rot_rad) ,np.cos(carm_rot_rad)]])
#rotation around y-axis (C-arm orb, aus scu 221)
R_inner=np.matrix([[np.cos(carm_orb_rad) ,0 ,np.sin(carm_orb_rad)],
[0 ,1 ,0 ],
[-np.sin(carm_orb_rad) ,0 ,np.cos(carm_orb_rad)]])
#R_2= R_outer*R_inner
R_2=np.matrix([[np.cos(carm_orb_rad) , 0 ,np.sin(carm_orb_rad) ],
[-np.sin(carm_orb_rad)*np.sin(carm_rot_rad) , np.cos(carm_rot_rad) ,np.cos(carm_orb_rad)*np.sin(carm_rot_rad) ],
[-np.sin(carm_orb_rad)*np.cos(carm_rot_rad) ,-np.sin(carm_rot_rad) ,np.cos(carm_orb_rad)*np.cos(carm_rot_rad) ]])
#tube_xray_rot=R_2*[0,0,1].T #Strahlungsvektor
tube_xray_rot=np.matrix([[ np.sin(carm_orb_rad) ],
[ np.cos(carm_orb_rad)*np.sin(carm_rot_rad)],
[ np.cos(carm_orb_rad)*np.cos(carm_rot_rad)]])
#tube_xray_rot_full=R_gantry*tube_xray_rot
tube_xray_rot_full=np.matrix([[sin(carm_orb_rad)*cos(gantry_rad) + sin(carm_rot_rad)*sin(gantry_rad)*cos(carm_orb_rad)],
[sin(carm_orb_rad)*sin(gantry) + sin(carm_rot_rad)*cos(carm_orb_rad)*cos(gantry_rad) ],
[cos(carm_orb_rad)*cos(carm_rot_rad) ]])
xray_vec_z= np.cos(carm_orb_rad)*np.cos(carm_rot_rad)
#tube_axis_rot=R_2*[1,0,0].T #Anodenachsendrehvektor
tube_axis_rot=np.matrix([[ np.cos(carm_orb_rad) ],
[ -np.sin(carm_orb_rad)*np.sin(carm_rot_rad) ],
[ -np.sin(carm_orb_rad)*np.cos(carm_rot_rad) ]])
#----------------------
#Plane B:
#rotation around z-axis (C-arm_rot, aus scu 222)
R_outer_B=np.matrix([[np.cos(carm_rot_b_rad),-np.sin(carm_rot_b_rad), 0],
[np.sin(carm_rot_b_rad), np.cos(carm_rot_b_rad), 0],
[0 ,0 , 1]])
#rotation around x-axis (C-arm orb, aus scu 222)
R_inner_B=np.matrix([[1 ,0 ,0 ],
[0 ,np.cos(carm_orb_b_rad) ,-np.sin(carm_orb_b_rad)],
[0 ,np.sin(carm_orb_b_rad) ,np.cos(carm_orb_b_rad)]])
#R_2_B= R_outer_B*R_inner_B
R_2_B=np.matrix([[np.cos(carm_rot_b_rad),-np.sin(carm_rot_b_rad)*np.cos(carm_orb_b_rad) ,-np.sin(carm_orb_rad)*np.sin(carm_rot_rad) ],
[np.sin(carm_rot_b_rad), np.cos(carm_rot_b_rad)*np.cos(carm_orb_b_rad) ,-np.cos(carm_rot_b_rad)*np.sin(carm_orb_b_rad) ],
[0 , np.sin(carm_orb_b_rad) , np.cos(carm_orb_b_rad) ]])
#tube_axis_rot_B=R_2_B*[0,1,0].T #Anodenachsendrehvektor
tube_axis_rot_B=np.matrix([[ np.sin(carm_rot_b_rad)*np.cos(carm_orb_b_rad) ],
[-np.cos(carm_rot_b_rad)*np.cos(carm_orb_b_rad) ],
[-np.sin(carm_orb_b_rad) ]])
xray_vec_z_B=np.sin(carm_orb_b_rad)
#tube_xray_rot_B=R_2_B*[0,0,1].T #Strahlungsvektor
tube_xray_rot_B=np.matrix([[ -np.sin(carm_orb_rad)*np.sin(carm_rot_rad) ],
[ -np.cos(carm_rot_b_rad)*np.sin(carm_orb_b_rad) ],
[ np.cos(carm_orb_b_rad) ]])
#Neigungsvektor Strahlerachse: z Komponente ist sinus des Neigungswinkels
alpha_orb_rad=np.arcsin(-np.sin(carm_orb_rad)*np.cos(carm_rot_rad))
alpha_orb_rad_b=np.arcsin(np.sin(carm_orb_b_rad)) #=-carm_orb_b_rad
tube_xray_init=np.array([[0,0,1]])
tube_axis_init=np.array([[1,0,0]]) #Plane A longitudinal
#tube_axis_init=np.array([[0,1,0]]) #Plane A transversal
tube_axis_rot2=R_2*tube_axis_init.T
tube_xray_rot2=R_2*tube_xray_init.T
return alpha_orb_rad/np.pi*180.
#-----Strahlerneigungsvektor und Strahlungsrichtung fuer Roboter, alpha_orb=init=(1,0,0)=0°; alpha_xray_init=(0,0,1)=90°
def get_tube_rot_robi(beta_,T1_,T2_,T3_,T4_,T5_,T6_):
#z-Richtung: nach oben
#y-Richtung: Richtung Tisch
#x-Richtung: senkrecht auf beiden
beta,T1,T2,T3,T4,T5,T6=sympy.symbols('beta,T1,T2,T3,T4,T5,T6')
Ry_6=Matrix([[cos(T6),0,-sin(T6)],[0,1,0],[sin(T6),0,cos(T6)]])
Rx_5=Matrix([[1,0,0],[0,cos(T5),-sin(T5)],[0,sin(T5),cos(T5)]])
Ry_4=Matrix([[cos(T4),0,-sin(T4)],[0,1,0],[sin(T4),0,cos(T4)]])
Rx_3=Matrix([[1,0,0],[0,cos(T3),-sin(T3)],[0,sin(T3),cos(T3)]])
Rx_2=Matrix([[1,0,0],[0,cos(T2),-sin(T2)],[0,sin(T2),cos(T2)]])
Rz_1=Matrix([[cos(T1), sin(T1),0],[sin(T1),cos(T1),0],[0,0,1]])
Ry_beta=Matrix([[cos(beta),0,-sin(beta)],[0,1,0],[sin(beta),0,cos(beta)]])
R_rot=Rz_1*Rx_2*Rx_3*Ry_4*Rx_5*Ry_6*Ry_beta
z=Matrix([[0],[0],[1]]) #Xray Richtung, unrotiert
y=Matrix([[0],[1],[0]]) #Strahlerachsenrichtung, unrotiert
z_rot=R_rot*z
y_rot=R_rot*y
alpha_orb_grad=180./pi*sympy.asin(y_rot[2].subs({beta:beta_,T1:T1_,T2:T2_,T3:T3_,T4:T4_,T5:T5_,T6:T6_}))
alpha_xray_grad=180./pi*sympy.asin(z_rot[2].subs({beta:beta_,T1:T1_,T2:T2_,T3:T3_,T4:T4_,T5:T5_,T6:T6_}))
"""
alpha_orb_grad=180./np.pi*np.arcsin((-np.sin(T2_)*np.sin(T3_) + np.cos(T2_)*np.cos(T3_))*np.sin(T5_)*np.cos(T4_) + (np.sin(T2_)*np.cos(T3_) + np.sin(T3_)*np.cos(T2_))*np.cos(T5_))
alpha_xray_grad=180./np.pi*np.arcsin((-(-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.sin(T4)*np.sin(T6) + ((-np.sin(T2)*np.sin\
(T3) + np.cos(T2)*np.cos(T3))*np.cos(T4)*np.cos(T5) - (np.sin(T2)*np.cos(T3) + np.sin(T3)*np.cos(T2))*sin\
(T5))*np.cos(T6))*np.cos(beta) - ((-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.sin(T4)*np.cos(T6\
) + ((-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.cos(T4)*np.cos(T5) - (np.sin(T2)*np.cos(T3) + sin\
(T3)*np.cos(T2))*np.sin(T5))*np.sin(T6))*np.sin(beta))
"""
return (alpha_orb_grad.evalf(),alpha_xray_grad.evalf())
###########################################################################
class TabPanel_StandardView(wx.Panel): #0
"""
This will be the first notebook tab
"""
#----------------------------------------------------------------------
def __init__(self, parent,prev):
self.prev=prev
self.os_type=sys.platform
wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
sizer = wx.FlexGridSizer(rows=3, cols=3 ,vgap=1, hgap=1)
self.label_1 = wx.StaticText(self, -1, " Source folder: ")
self.label_1.SetToolTip(wx.ToolTip("Choose a directory which contains your eventlogs and the system.caf-file."))
self.label_2 = wx.StaticText(self, -1, " Results folder: ")
self.prev.text_ctrl_1 = wx.TextCtrl(self, -1, self.prev.sourceDir,size=(350,28),style=wx.TE_PROCESS_ENTER) #self.prev .sourceDir
self.Bind(wx.EVT_TEXT_ENTER, self.prev.OnEditSourceDir, self.prev.text_ctrl_1)
self.Bind(wx.EVT_TEXT, self.prev.OnChangeSourceDir, self.prev.text_ctrl_1)
self.bitmap_button_1= wx.Button(self,id=-1,label="Browse",size=wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.prev.OnOpenSourceDir, self.bitmap_button_1)
self.prev.text_ctrl_2 = wx.TextCtrl(self, -1, self.prev.resultsDir,size=(350,28),style=wx.TE_PROCESS_ENTER) #self.resultsDir
self.Bind(wx.EVT_TEXT_ENTER, self.prev.OnEditResultsDir, self.prev.text_ctrl_2)
self.Bind(wx.EVT_TEXT, self.prev.OnChangeResultsDir, self.prev.text_ctrl_2)
self.bitmap_button_2= wx.Button(self,id=-1,label="Browse",size=wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.prev.OnOpenResultsDir, self.bitmap_button_2)
self.prev.RB_plane=wx.RadioBox(self, -1, "Plane", (20, 250), wx.DefaultSize,['A','B', 'both'], 3, wx.RA_SPECIFY_ROWS)
self.prev.RB_plane.SetToolTip(wx.ToolTip("Choose a plane"))
self.prev.earliest = wx.TextCtrl(self, -1, '',size=(350,80),style= wx.TE_MULTILINE )
self.prev.earliest.Disable()
self.prev.earliest.SetToolTip(wx.ToolTip("Earliest eventlog in source directory"))
#self.prev.latest = wx.TextCtrl(self, -1, '',size=(250,28))
#self.prev.latest.SetToolTip(wx.ToolTip("Latest eventlog in source directory"))
#TubeInfo-Button
self.prev.pBgetTubeInfo=wx.Button(self, -1, "Tube Info", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.prev.OnTubeInfo, self.prev.pBgetTubeInfo)
sizer.Add(self.label_1, 0, wx.ALL, 5)
sizer.Add(self.prev.text_ctrl_1, 0, wx.ALL, 5)
sizer.Add(self.bitmap_button_1, 0, wx.ALL, 5)
sizer.Add(self.label_2, 0, wx.ALL, 5)
sizer.Add(self.prev.text_ctrl_2, 0, wx.ALL, 5)
sizer.Add(self.bitmap_button_2, 0, wx.ALL, 5)
sizer.Add(self.prev.RB_plane,1, wx.ALL, 5)
sizer.Add(self.prev.earliest,1, wx.ALL, 5)
sizer.Add(self.prev.pBgetTubeInfo,1, wx.ALL, 5)
self.SetSizer(sizer)
###########################################################################
class TabPanel_TubeTypeView(wx.Panel):
"""
This will be the first notebook tab
"""
#----------------------------------------------------------------------
def __init__(self, parent, prev):
""""""
wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
sizer = wx.GridSizer(rows=2, cols=2 ,vgap=10, hgap=10)
self.cat2F = wx.CheckBox(self, -1, label='Megalix Cat+ 2F',size= wx.DefaultSize)
self.cat3F = wx.CheckBox(self, -1, label='Megalix Cat+ 3F', size= wx.DefaultSize)
self.giga2F = wx.CheckBox(self, -1, label='Gigalix 2F', size= wx.DefaultSize)
self.giga3F = wx.CheckBox(self, -1, label='Gigalix 3F', size= wx.DefaultSize)
sizer.Add(self.cat2F, 0, wx.ALL, 5)
sizer.Add(self.cat3F, 0, wx.ALL, 5)
sizer.Add(self.giga2F, 0, wx.ALL, 5)
sizer.Add(self.giga3F, 0, wx.ALL, 5)
self.SetSizer(sizer)
###########################################################################
class TabPanel_SW_View(wx.Panel): #1
"""
This will be the first notebook tab
"""
#----------------------------------------------------------------------
def __init__(self, parent,prev):
""""""
wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
sizer = wx.GridSizer(rows=2, cols=2 ,vgap=10, hgap=10)
self.Artis_VC14 = wx.CheckBox(self, -1, label='Artis VC14',size= wx.DefaultSize)
self.Artis_VC21 = wx.CheckBox(self, -1, label='Artis VC21', size= wx.DefaultSize)
self.Artis_VD10 = wx.CheckBox(self, -1, label='Artis VD10+', size= wx.DefaultSize)
self.EAS_VA10 = wx.CheckBox(self, -1, label='EAS VA10+', size= wx.DefaultSize)
sizer.Add(self.Artis_VC14, 0, wx.ALL, 5)
sizer.Add(self.Artis_VC21, 0, wx.ALL, 5)
sizer.Add(self.Artis_VD10, 0, wx.ALL, 5)
sizer.Add(self.EAS_VA10, 0, wx.ALL, 5)
self.SetSizer(sizer)
###########################################################################
class TabPanel_SN_View(wx.Panel):
"""
This will be the first notebook tab
"""
#----------------------------------------------------------------------
def __init__(self, parent,prev):
self.prev=prev
self.prev.SNs=[]
wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
sizer = wx.FlexGridSizer(rows=3, cols=3 ,vgap=1, hgap=1)
self.label_3 = wx.StaticText(self, -1, " Results folder: ")
self.prev.text_ctrl_3 = wx.TextCtrl(self, -1, self.prev.resultsDir,size=(370,28),style=wx.TE_PROCESS_ENTER) #self.resultsDir
self.Bind(wx.EVT_TEXT_ENTER, self.OnEditResultsDir, self.prev.text_ctrl_3)
self.Bind(wx.EVT_TEXT, self.OnChangeResultsDir, self.prev.text_ctrl_3)
self.bitmap_button_2= wx.Button(self,id=-1,label="Browse",size=wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.OnOpenResultsDir, self.bitmap_button_2)
self.prev.RB_plane2=wx.RadioBox(self, -1, "Plane", (20, 250), wx.DefaultSize,['A','B','both'], 3, wx.RA_SPECIFY_ROWS)
self.prev.RB_plane2.SetToolTip(wx.ToolTip("Choose plane"))
self.SNlist = wx.TextCtrl(self, -1, '',size=(370,90),style= wx.TE_MULTILINE|wx.TE_PROCESS_ENTER )
self.SNlist.SetToolTip(wx.ToolTip("Add system serials (comma-seperated; wildcards 121*** allowed)"))
self.Bind(wx.EVT_TEXT, self.OnSNListEdit, self.SNlist)
self.Bind(wx.EVT_TEXT_ENTER, self.OnSNListEnter, self.SNlist)
#Check-Button
self.pBcheck = wx.Button(self, -1, "Check", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.OnCheckSNList, self.pBcheck)
self.pBcheck.SetToolTip(wx.ToolTip("Check SN List"))
#System Info-Button
self.pBSysInfo = wx.Button(self, -1, "System Info", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.OnSysInfo, self.pBSysInfo)
self.pBSysInfo.SetToolTip(wx.ToolTip("Information about System Type, City, Country,..."))
#TubeInfo-Button
self.prev.pBgetTubeInfo2=wx.Button(self, -1, "Tube Info", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.prev.OnTubeInfo, self.prev.pBgetTubeInfo2)
#SW-Info-Button
self.pBgetSWInfo=wx.Button(self, -1, "SW Info", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.OnSWInfo, self.pBgetSWInfo)
#GetLogDates-Info-Button
self.pBgetLogDates=wx.Button(self, -1, "Get Log Dates", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.OnGetLogDates, self.pBgetLogDates)
sizer1 = wx.GridSizer(rows=5, cols=1 ,vgap=1, hgap=1)
sizer1.Add(self.pBcheck,1, wx.ALL, 2)
sizer1.Add(self.pBSysInfo,1, wx.ALL, 2)
sizer1.Add(self.prev.pBgetTubeInfo2,1, wx.ALL, 2)
sizer1.Add(self.pBgetSWInfo,1, wx.ALL, 2)
sizer1.Add(self.pBgetLogDates,1, wx.ALL, 2)
sizer.Add(self.label_3, 0, wx.ALL, 5)
sizer.Add(self.prev.text_ctrl_3, 0, wx.ALL, 5)
sizer.Add(self.bitmap_button_2, 0, wx.ALL, 5)
sizer.Add(self.prev.RB_plane2,1, wx.ALL, 5)
sizer.Add(self.SNlist,1, wx.ALL, 5)
sizer.Add(sizer1,1, wx.ALL, 5)
self.SetSizer(sizer)
def OnSNListEdit(self,event):
self.SNlist.SetBackgroundColour('red')
self.SNlist.Refresh()
def OnSysInfo(self,event):
SysInsostr=''
self.prev.myXEvent=XEvent()
self.prev.plane='A'
self.OnCheckSNList(0)
if len(self.prev.SNs)==1:
singleSN=self.prev.SNs[0]
if (singleSN).isdigit():
self.prev.onScan()
if singleSN in self.prev.serialList.keys():
SW_path = self.prev.serialList[singleSN][-1]
zfile_list=glob.glob(os.path.join(SW_path,'XA*LogFiles.zip'))
zfile_list=sorted(zfile_list)
zfile=zfile_list[-1]
zf=zipfile.ZipFile(zfile)
filelist=zf.namelist()
if not IcConsMode:
print "reading "+zfile
for filename in filelist:
#XA123007_2014_01_14_axiom.caf.txt
if filename.find('XA')>-1 and filename.find('_system.caf.txt')>-1:
fp = zf.open(filename)
system_txt = fp.readlines()
fp.close()
self.prev.process_system_caf(system_txt)
SysInsostr+='System Type: '+self.prev.myXEvent.SystemType+'\n'
SysInsostr+='System Shape: '+self.prev.myXEvent.SystemShape+'\n'
SysInsostr+='FD Type plane A: '+self.prev.myXEvent.FD_A_name+'\n'
SysInsostr+='FD Type plane B: '+self.prev.myXEvent.FD_B_name+'\n'
if filename.find('XA')>-1 and filename.find('_axiom.caf.txt')>-1 and filename.find('IVS')>-1:
fp = zf.open(filename)
axiom_txt = fp.readlines()
fp.close()
self.prev.process_axiom_caf(axiom_txt,self.prev.GetFileDateCaf(filename))
SysInsostr+='Syngo System Type: '+self.prev.myXEvent.syngo_system_type.replace('n a','n.a.')+'\n'
SysInsostr+='City: '+self.prev.myXEvent.city.replace('n a','n.a.')+'\n'
SysInsostr+='Country: '+self.prev.myXEvent.country.replace('n a','n.a.')+'\n'
SysInsostr+='Current SW Version: '+self.prev.myXEvent.SW[-1][0]+'\n'
if SysInsostr=='':
wx.MessageBox('No info found\nin selected period!', 'System Info', wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox(SysInsostr, 'System Info', wx.OK | wx.ICON_INFORMATION)
return
else:
wx.MessageBox('Not available for more than one SN!', 'System Info', wx.OK | wx.ICON_INFORMATION)
return
wx.MessageBox('SW Info not possible!', 'System Info', wx.OK | wx.ICON_INFORMATION)
return
def OnSNListEnter(self,event):
txt=''
self.prev.SNs=[]
SNdata=self.SNlist.GetValue().replace('\n',',').split(',')
char_set=[str(i) for i in range(10)]
char_set.append('*')
for dat in SNdata:
d=[c in char_set for c in dat.strip()]
if sum(d)==len(d) and len(d)>4 and len(d)<7:
txt+=dat.strip()+', '
self.prev.SNs.append(dat.strip())
if len(txt)>0:
txt=txt[:-2]
self.SNlist.Clear()
self.SNlist.SetValue(txt)
self.SNlist.SetBackgroundColour('white')
self.SNlist.Refresh()
self.prev.WriteRegData()
return
def OnCheckSNList(self,event):
txt=''
self.prev.SNs=[]
SNdata=self.SNlist.GetValue().replace('\n',',').split(',')
char_set=[str(i) for i in range(10)]
char_set.append('*')
for dat in SNdata:
d=[c in char_set for c in dat.strip()]
if sum(d)==len(d) and len(d)>4 and len(d)<7:
txt+=dat.strip()+', '
self.prev.SNs.append(dat.strip())
if len(txt)>0:
txt=txt[:-2]
self.SNlist.Clear()
self.SNlist.SetValue(txt)
self.SNlist.SetBackgroundColour('white')
self.SNlist.Refresh()
self.prev.WriteRegData()
return
#------------------------------------------
def OnOpenResultsDir(self, event):
dialog = wx.DirDialog(None, "Choose a directory:",self.prev.resultsDir,style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
self.prev.resultsDir=dialog.GetPath()
self.prev.text_ctrl_3.SetValue(self.prev.resultsDir)
dialog.Destroy()
self.prev.WriteRegData()
self.prev.text_ctrl_3.SetBackgroundColour('white')
self.prev.text_ctrl_3.Refresh()
#------------------------------------------
def OnEditResultsDir(self,event):
temp=self.prev.text_ctrl_3.GetValue()
temp.strip()
old_dir=self.prev.resultsDir
if(os.path.isdir(temp)):
self.prev.resultsDir=temp
self.prev.WriteRegData()
else:
self.prev.resultsDir=old_dir
self.prev.text_ctrl_3.SetValue(old_dir)
self.prev.text_ctrl_3.SetBackgroundColour('white')
self.prev.text_ctrl_3.Refresh()
#------------------------------------------
def OnChangeResultsDir(self,event):
self.prev.text_ctrl_3.SetBackgroundColour('red')
self.prev.text_ctrl_3.Refresh()
#------------------------------------------
def OnSWInfo(self,event):
SWinfostr=''
SWs={}
self.OnCheckSNList(0)
if len(self.prev.SNs)==1:
singleSN=self.prev.SNs[0]
if (singleSN).isdigit():
self.prev.onScan()
if singleSN in self.prev.serialList.keys():
for SW_path in self.prev.serialList[singleSN]:
zfile_list=glob.glob(os.path.join(SW_path,'XA*LogFiles.zip'))
zfile_list=sorted(zfile_list)
for zfile in zfile_list:
temp_SW=os.path.split(os.path.split(os.path.split(zfile)[0])[0])[1]
if temp_SW not in SWs.keys():
dates=[]
SWs[temp_SW]=dates
try:
SWs[temp_SW].append(self.prev.GetZipFileDate(zfile))
except:
blubb=1
for key in SWs.keys():
SWs[key]=sorted(SWs[key])
SWinfostr+=key+': First:'+ str(SWs[key][0])[:10]+' Last:'+str(SWs[key][-1])[:10]+'\n'
if SWinfostr=='':
wx.MessageBox('No SW data found\nin selected period!', 'SW Version Info', wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox(SWinfostr, 'SW Version Info', wx.OK | wx.ICON_INFORMATION)
return
else:
wx.MessageBox('Not available for more than one SN!', 'SW Version Info', wx.OK | wx.ICON_INFORMATION)
return
wx.MessageBox('SW Info not possible!', 'SW Version Info', wx.OK | wx.ICON_INFORMATION)
return
#------------------------------------------
def OnGetLogDates(self,event):
dates=[]
self.OnCheckSNList(0)
if len(self.prev.SNs)==1:
singleSN=self.prev.SNs[0]
if (singleSN).isdigit():
self.prev.onScan()
if singleSN in self.prev.serialList.keys():
for SW_path in self.prev.serialList[singleSN]:
zfile_list=glob.glob(os.path.join(SW_path,'XA*LogFiles.zip'))
zfile_list=sorted(zfile_list)
for zfile in zfile_list:
dates.append(self.prev.GetZipFileDate(zfile))
else:
wx.MessageBox('Not available for more than one SN!', 'Log Dates Info', wx.OK | wx.ICON_INFORMATION)
return
if len(dates)!=0:
dates=sorted(dates)
temp1=wx.DateTime()
temp1.Set(dates[0].day,dates[0].month-1,dates[0].year,0,0,0)
self.prev.datepicker_start.SetValue(temp1)
self.prev.datepicker_start.Refresh()
self.prev.timepicker_start.SetValue(temp1)
temp1.Set(dates[-1].day,dates[-1].month-1,dates[-1].year,23,59,59)
self.prev.datepicker_end.SetValue(temp1)
self.prev.datepicker_end.Refresh()
self.prev.timepicker_end.SetValue(temp1)
else:
print "No logs found for selected SN!"
wx.MessageBox('No logs found for selected SN!', 'Info', wx.OK | wx.ICON_INFORMATION)
return
#------------------------------------------
########################################################################
class NotebookDemo(wx.Notebook):
"""
Notebook class
"""
#----------------------------------------------------------------------
def __init__(self, parent,prev):
wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style=
wx.BK_DEFAULT
#wx.BK_TOP
#wx.BK_BOTTOM
#wx.BK_LEFT
#wx.BK_RIGHT
)
self.prev=prev
# Create the first tab and add it to the notebook
self.tabOne = TabPanel_StandardView(self,prev)
self.AddPage(self.tabOne, "Standard")
# Create and add the second tab
self.tabTwo = TabPanel_SW_View(self,prev)
self.AddPage(self.tabTwo, "SW Version")
self.tabThree= TabPanel_TubeTypeView(self,prev)
self.AddPage(self.tabThree, "Tube Type")
# Create and add the second tab
self.tabFour = TabPanel_SN_View(self,prev)
self.AddPage(self.tabFour, "Serial Number")
# Create and add the third tab
#self.AddPage(TabPanel(self), "Info")
self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGING, self.OnPageChanging)
def OnPageChanged(self, event):
old = event.GetOldSelection()
new = event.GetSelection()
sel = self.GetSelection()
self.prev.text_ctrl_3.SetValue(self.prev.resultsDir)
self.prev.text_ctrl_2.SetValue(self.prev.resultsDir)
self.prev.text_ctrl_3.SetBackgroundColour('white')
self.prev.text_ctrl_3.Refresh()
self.prev.text_ctrl_2.SetBackgroundColour('white')
self.prev.text_ctrl_2.Refresh()
#print 'OnPageChanged, old:%d, new:%d, sel:%d\n' % (old, new, sel)
event.Skip()
def OnPageChanging(self, event):
old = event.GetOldSelection()
new = event.GetSelection()
sel = self.GetSelection()
#print 'OnPageChanging, old:%d, new:%d, sel:%d\n' % (old, new, sel)
event.Skip()
class MyFrame(wx.Frame):
global __start__datum
global __ende__datum
global __start__tag
global __start__monat
global __start__jahr
global __ende__jahr
global __ende__monat
global __ende__tag
global DAT
__start__datum = []
__ende__datum = []
__start__tag = []
__start__monat = []
__start__jahr = []
__ende__tag = []
__ende__monat = []
__ende__jahr = []
DAT = []
def __init__(self, parent = None, id = -1, title = "Small Editor",params=None):
wx.Frame.__init__(self, parent, id ,title, size = (600,700), style = wx.SYSTEM_MENU | wx.CLOSE_BOX |wx.CAPTION )
#JN new section
self.os_type=sys.platform
if params==None:
self.enable_gui=True
else:
self.enable_gui=False
if not IcConsMode:
print params
self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE))
self.sourceDir =r"I:\1_AX\03_Projects\30_PLM\42_MAT_FieldLogs_FOR\ProductFiles\Artis"
self.resultsDir =r"D:\temp"
self.panel = wx.Panel(self)
self.notebook = NotebookDemo(self.panel,self)
try:
if self.os_type.find('linux')==-1:
if socket.gethostname()=='FORS14AA' or socket.gethostname()=='FORS18AA' :
self.sourceDirZipsArtis=r'\\fors16za\dfs03_30_44_archiv_for$\10_Artis\40_Field' # location of zipped files
self.sourceDirZipsEAS= r'\\fors16za\dfs03_30_44_archiv_for$\20_EAS\40_Field' # location of zipped files
self.sourceDirZipsSCM= r'\\ww005.siemens.net\meddfsroot\1_AX\03_Projects\30_PLM\A4_QIB\10_SCM\Logfiles'
else:
self.sourceDirZipsArtis=r'I:\1_AX\03_Projects\30_PLM\44_MAT_Archiv_FOR\10_Artis\40_Field' # location of zipped files
self.sourceDirZipsEAS = r'I:\1_AX\03_Projects\30_PLM\44_MAT_Archiv_FOR\20_EAS\40_Field' # location of zipped files
self.sourceDirZipsSCM =r'I:\1_AX\03_Projects\30_PLM\A4_QIB\10_SCM\Logfiles'
self.RegistryData = wx.Config("PyTAX\EventlogAnalyzer", style=wx.CONFIG_USE_GLOBAL_FILE)
self.sourceDir = self.RegistryData.Read("sourceDir")
self.resultsDir = self.RegistryData.Read("resultsDir")
self.notebook.tabFour.SNlist.SetValue(self.RegistryData.Read("SNlist"))
self.notebook.tabFour.OnCheckSNList(0)
if self.sourceDir == "":
self.sourceDir = "I:\\1_AX\\03_Projects\\30_PLM\\42_MAT_FieldLogs_FOR\\ProductFiles\\Artis"
if self.resultsDir == "":
self.resultsDir = "D:\\temp1\\"
self.text_ctrl_1.SetValue(self.sourceDir)
self.text_ctrl_1.SetBackgroundColour('white')
self.text_ctrl_1.Refresh()
self.text_ctrl_2.SetValue(self.resultsDir)
self.text_ctrl_2.SetBackgroundColour('white')
self.text_ctrl_2.Refresh()
else:
self.sourceDirZipsArtis=r"/media/olli/FREECOM HDD/10_Artis/40_Field"
direfilename=os.path.join(os.path.expanduser('~'),'.ea_dirs.dat')
dirfile=open(direfilename,'r')
dir_lines=dirfile.readlines()
self.sourceDir = os.path.normpath(dir_lines[0]).rstrip('\n')
self.resultsDir = os.path.normpath(dir_lines[1]).rstrip('\n')
SNtxt=''
for i in range(2,len(dir_lines)):
SNtxt+=dir_lines[i]
self.notebook.tabFour.SNlist.SetValue(SNtxt)
self.notebook.tabFour.OnCheckSNList(0)
self.text_ctrl_1.SetValue(self.sourceDir)
self.text_ctrl_1.SetBackgroundColour('white')
self.text_ctrl_1.Refresh()
self.text_ctrl_2.SetValue(self.resultsDir)
self.text_ctrl_2.SetBackgroundColour('white')
self.text_ctrl_2.Refresh()
dirfile.close()
except:
print "Error reading Windows Registry"
vsizer2=wx.FlexGridSizer(rows=11, cols=1,vgap=0, hgap=0)
gvsizer0 = wx.GridSizer(rows=10, cols=1,vgap=0, hgap=0)
gvsizer1 = wx.GridSizer(rows=12, cols=1,vgap=0, hgap=0)
gvsizer2 = wx.GridSizer(rows=12, cols=1,vgap=0, hgap=0)
gvsizer3 = wx.GridSizer(rows=13, cols=1,vgap=0, hgap=0)
ghsizer0 = wx.FlexGridSizer(rows=2, cols=3 ,vgap=5, hgap=5)
ghsizer1 = wx.GridSizer(rows=1, cols=4 ,vgap=0, hgap=0)
ghsizer2 = wx.GridSizer(rows=1, cols=3 ,vgap=0, hgap=0)
ghsizer3 = wx.FlexGridSizer(rows=2, cols=3 ,vgap=0, hgap=0)
self.cb0 = wx.CheckBox(self.panel, -1, label='All parts',size= wx.DefaultSize)
self.cb1 = wx.CheckBox(self.panel, -1, label='Part 1', size= wx.DefaultSize)
self.cb2 = wx.CheckBox(self.panel, -1, label='Part 2', size= wx.DefaultSize)
self.cb3 = wx.CheckBox(self.panel, -1, label='Angulations', size= wx.DefaultSize)
self.cb4 = wx.CheckBox(self.panel, -1, label='Part 4', size= wx.DefaultSize)
self.cb5 = wx.CheckBox(self.panel, -1, label='Part 5', size= wx.DefaultSize)
self.cb6 = wx.CheckBox(self.panel, -1, label='Part 6', size= wx.DefaultSize)
self.cb7 = wx.CheckBox(self.panel, -1, label='Part 7', size= wx.DefaultSize)
self.cb8 = wx.CheckBox(self.panel, -1, label='Dose Eff.', size= wx.DefaultSize)
self.cb9 = wx.CheckBox(self.panel, -1, label='Dyn. Offset ', size= wx.DefaultSize)
self.cb10 = wx.CheckBox(self.panel, -1, label='Part 10', size= wx.DefaultSize)
self.cb11 = wx.CheckBox(self.panel, -1, label='Part 11', size= wx.DefaultSize)
self.cb12 = wx.CheckBox(self.panel, -1, label='Part 12', size= wx.DefaultSize)
self.cb13 = wx.CheckBox(self.panel, -1, label='FG Analysis ', size= wx.DefaultSize)
self.cb14 = wx.CheckBox(self.panel, -1, label='Part 14', size= wx.DefaultSize)
self.cb15 = wx.CheckBox(self.panel, -1, label='Part 15', size= wx.DefaultSize)
self.cb16 = wx.CheckBox(self.panel, -1, label='Part 16', size= wx.DefaultSize)
self.cb17 = wx.CheckBox(self.panel, -1, label='Part 17', size= wx.DefaultSize)
self.cb18 = wx.CheckBox(self.panel, -1, label='Part 18 (Arcing)', size= wx.DefaultSize)
self.cb19 = wx.CheckBox(self.panel, -1, label='Part 19', size= wx.DefaultSize)
self.cb20 = wx.CheckBox(self.panel, -1, label='Part 20', size= wx.DefaultSize)
self.cb21 = wx.CheckBox(self.panel, -1, label='Part 21', size= wx.DefaultSize)
self.cb22 = wx.CheckBox(self.panel, -1, label='Part 22', size= wx.DefaultSize)
self.cb23 = wx.CheckBox(self.panel, -1, label='IC Cons', size= wx.DefaultSize)
self.cb24 = wx.CheckBox(self.panel, -1, label='Averaged Power', size= wx.DefaultSize)
self.cb_enh_env = wx.CheckBox(self.panel, -1, label='enhanced EnvLog', size= wx.DefaultSize)
self.cb_png = wx.CheckBox(self.panel, -1, label='png out', size= wx.DefaultSize)
self.cb_CSVstyle = wx.CheckBox(self.panel, -1, label='csv Style', size= wx.DefaultSize)
self.cb_negWV = wx.CheckBox(self.panel, -1, label='neg. WV ', size= wx.DefaultSize)
self.cb_EnvLog = wx.CheckBox(self.panel, -1, label='Env Log ', size= wx.DefaultSize)
self.cb_examsets = wx.CheckBox(self.panel, -1, label='Exam Set ', size= wx.DefaultSize)
self.group2_ctrls = []
self.radio1_SCM = wx.RadioButton( self.panel, -1 , "Field Logs", style = wx.RB_GROUP )
self.radio2_SCM = wx.RadioButton( self.panel, -1 , "SCM logs")
self.group2_ctrls.append(self.radio1_SCM)
self.group2_ctrls.append(self.radio2_SCM)
#Datumauswahl
self.label_startdate = wx.StaticText(self.panel, -1, " Start date: ")
self.datepicker_start = wx.DatePickerCtrl(self.panel,style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
self.timepicker_start=TimeCtrl(self.panel, fmt24hr = True)
self.label_enddate = wx.StaticText(self.panel, -1, " End date: ")
self.datepicker_end = wx.DatePickerCtrl(self.panel,style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
self.timepicker_end=TimeCtrl(self.panel, fmt24hr = True)
#Start-Button
self.pBstart = wx.Button(self.panel, -1, "Analyze", size= wx.DefaultSize)
self.Bind(wx.EVT_BUTTON, self.OnAnalyze, self.pBstart)
self.pBstart.SetToolTip(wx.ToolTip("Start analysis"))
#Copyright Info
#self.label_4 = wx.StaticText(self.panel, -1, u" \xa9 Siemens AG (2014) - Dr. O.Baruth H-IM AX R&&D ICX" )
#self.label_5 = wx.StaticText(self.panel, -1, "--- No responsibility is taken for the correctness of the results --- ")
line0 = wx.StaticLine(self.panel)
line1 = wx.StaticLine(self.panel)
line2 = wx.StaticLine(self.panel)
#Placement
dist=0
#gvsizer0.Add(self.RB_plane,1, wx.ALL|wx.EXPAND, dist)
gvsizer0.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer0.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer0.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb1,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb2,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb3,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb4,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb5,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb6,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb7,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb8,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb9,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb10,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb11,1, wx.ALL|wx.EXPAND, dist)
gvsizer1.Add(self.cb12,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb13,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb14,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb15,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb16,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb17,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb18,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb19,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb20,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb21,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb22,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb23,1, wx.ALL|wx.EXPAND, dist)
gvsizer2.Add(self.cb24,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb0,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.radio1_SCM, 1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.radio2_SCM, 1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(wx.StaticText(self.panel,-1,' '),1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb_enh_env,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb_png,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb_CSVstyle,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb_negWV,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb_EnvLog,1, wx.ALL|wx.EXPAND, dist)
gvsizer3.Add(self.cb_examsets,1, wx.ALL|wx.EXPAND, dist)
ghsizer0.Add(self.label_startdate,1, wx.ALL|wx.EXPAND, dist)
ghsizer0.Add(self.datepicker_start,1, wx.ALL|wx.EXPAND, dist)
ghsizer0.Add(self.timepicker_start,1, wx.ALL|wx.EXPAND, dist)
ghsizer0.Add(self.label_enddate,1, wx.ALL|wx.EXPAND, dist)
ghsizer0.Add(self.datepicker_end,1, wx.ALL|wx.EXPAND, dist)
ghsizer0.Add(self.timepicker_end,1, wx.ALL|wx.EXPAND, dist)
ghsizer1.Add(gvsizer0,1, wx.ALL|wx.EXPAND, dist)
ghsizer1.Add(gvsizer1,1, wx.ALL|wx.EXPAND, dist)
ghsizer1.Add(gvsizer2,1, wx.ALL|wx.EXPAND, dist)
ghsizer1.Add(gvsizer3,1, wx.ALL|wx.EXPAND, dist)
ghsizer2.Add(self.pBgetTubeInfo,1, wx.ALL|wx.EXPAND, dist)
ghsizer2.Add((20,20),1, wx.ALL|wx.EXPAND, dist)
ghsizer2.Add(self.pBstart,1, wx.ALL|wx.EXPAND, dist)
ghsizer3.Add((60,10),1, wx.ALL|wx.EXPAND, dist)
#ghsizer3.Add(self.label_4,1, wx.ALL|wx.EXPAND|wx.CENTER, dist)
#ghsizer3.Add((10,10),1, wx.ALL|wx.EXPAND, dist)
#ghsizer3.Add((60,10),1, wx.ALL|wx.EXPAND, dist)
#ghsizer3.Add(self.label_5,1, wx.ALL|wx.EXPAND|wx.CENTER, dist)
#ghsizer3.Add((10,10),1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add((10,10), wx.ALL|wx.EXPAND|wx.CENTER, dist)
vsizer2.Add(ghsizer0,1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add((10,10), wx.ALL|wx.EXPAND|wx.CENTER, dist)
vsizer2.Add(line0,1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add((10,10), wx.ALL|wx.EXPAND|wx.CENTER, dist)
vsizer2.Add(ghsizer1,1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add(line1,1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add(ghsizer2,1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add(line2,1, wx.ALL|wx.EXPAND, dist)
vsizer2.Add((10,10), wx.ALL|wx.EXPAND|wx.CENTER, dist)
vsizer2.Add(ghsizer3,1, wx.ALL|wx.EXPAND, dist)
sizer = wx.FlexGridSizer(rows=2, cols=0,vgap=0, hgap=0)
sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND)
sizer.Add(vsizer2, 1, wx.ALL|wx.EXPAND)
self.panel.SetSizer(sizer)
self.Layout()
if self.enable_gui:
self.Show()
if IcConsMode:
self.cb23.SetValue(True)
self.cb_CSVstyle.SetValue(True)
self.cb_examsets.SetValue(True)
self.cb3.SetValue(False)
if ax_tc_mode:
self.cb18.SetValue(True)
self.cb_CSVstyle.SetValue(True)
self.cb_EnvLog.SetValue(True)
self.cb_negWV.SetValue(True)
self.cb_png.SetValue(True)
self.cb23.SetValue(True)
self.cb8.SetValue(True)
self.cb9.SetValue(True)
self.RB_plane2.SetSelection(2)
self.cb_enh_env.SetValue(False)
self.cb0.SetToolTip(wx.ToolTip("Select all parts"))
self.cb1.SetToolTip(wx.ToolTip("Histograms (voltage, current, zoom, watervalue, SID)"))
self.cb2.SetToolTip(wx.ToolTip("Histograms (rao, cran, pulse-power, pulse-rate), scatter plots (watervalue - voltage)"))
self.cb3.SetToolTip(wx.ToolTip("Scatter plots (watervalue - current, current - voltage, rao - cran, watervalue - rao, watervalue - cran, watervalue - SID), time/study"))
self.cb6.SetToolTip(wx.ToolTip("Scatter plots (scenelength - pulse-duration, pulse-rate - pulse-duration, scenelength - pulse-rate)"))
self.cb5.SetToolTip(wx.ToolTip("Patient-studytime, BE/day, scatter plots (scenelength - pulse-power, scenelength - mean-power, scenelength - dutycycle)"))
self.cb4.SetToolTip(wx.ToolTip("Histograms (Cu-filter, skindoserate, systemdose, pulse-duration, dutycycle, scenelength)"))
self.cb7.SetToolTip(wx.ToolTip("Histograms (skindose/study, DAP/study, Total BE/day), Textplots, Studyreport"))
self.cb8.SetToolTip(wx.ToolTip("Verlauf Dosisausbeute"))
self.cb9.SetToolTip(wx.ToolTip("Dynamic current offset vs. time"))
self.cb10.SetToolTip(wx.ToolTip("Watervalue - voltage (Acq)"))
self.cb11.SetToolTip(wx.ToolTip("Watervalue - voltage (Fl)"))
self.cb12.SetToolTip(wx.ToolTip("Time series of watervalue / voltage"))
self.cb13.SetToolTip(wx.ToolTip("Verlauf Dosisausbeute"))
self.cb14.SetToolTip(wx.ToolTip("3D-plot (Cu-filter - voltage - Dosisausbeute)"))
self.cb15.SetToolTip(wx.ToolTip("Scatter plot (voltage - current for small/large/micro focus)"))
self.cb16.SetToolTip(wx.ToolTip("Time series of watervalue / BE / X-rays / heat-current"))
self.cb17.SetToolTip(wx.ToolTip("Time series of heat-unit / dynamic-offset"))
self.cb18.SetToolTip(wx.ToolTip("Arcing-events, PUN error-warnings"))
self.cb19.SetToolTip(wx.ToolTip("OGP-entries"))
self.cb20.SetToolTip(wx.ToolTip("Rao - cran - contour-plot"))
self.cb21.SetToolTip(wx.ToolTip("Soll-Szenenlaenge vs. Ist-Szenenlaenge"))
self.cb22.SetToolTip(wx.ToolTip("Soll-FD-Dosis vs. Ist-FD-Dosis"))
self.cb23.SetToolTip(wx.ToolTip("Custom report for IC Cons"))
self.cb24.SetToolTip(wx.ToolTip("Average Power"))
self.cb_CSVstyle.SetToolTip(wx.ToolTip("unchecked: 3.4,7.3 \n checked: 3,4;7,3"))
self.cb_negWV.SetToolTip(wx.ToolTip("Allow negative watervalues"))
self.cb_examsets.SetToolTip(wx.ToolTip("Analyze exam sets"))
self.label_4 = wx.StaticText(self, -1, u" \xa9 Siemens Healthcare GmbH (2015) - Dr. O.Baruth HC IM AX R&&D IC SP", pos=(100,self.GetSize().GetHeight()-65))
self.label_4 = wx.StaticText(self, -1, "--- No responsibility is taken for the correctness of the results --- ", pos=(100,self.GetSize().GetHeight()-50))
self.__set_properties()
self.__do_layout()
self.line_resistance='n a'
self.line_voltage='n a'
#Update (for Source Folder loaded from Reqistry
try:
self.UpdateSourceDir()
except:
print 'Problem with source directory'
self.MatrNr='n.a.'
#Environmental Log
self.envtime3=[]
if(self.cb_EnvLog.GetValue()):
all_Env_files=''
try:
all_Env_files = os.listdir(self.sourceDir + '\\Other_Logs\\EnvironmentLog')
except:
True; #path not valid
envlogs_exists=0
self.all_env_files=[]
for filename in all_Env_files:
if (filename.rfind('EnvironmentLog')>-1 and filename.rfind('.xml')>-1 ):
self.all_env_files.append(filename)
envlogs_exists=1
if self.enable_gui==False:
if params.find('.txt')>-1:
paramlines=''
try:
fp=open(params)
paramlines=fp.readlines()
fp.close()
except:
print 'Problem reading config file! Exiting...'
sys.exit(1)
startdate_ful=''
enddate_full=''
self.radio1_SCM.SetValue(True) #if no SCMlog=True Entry is found, default is "no SCM" Mode
self.radio2_SCM.SetValue(False)
###get SNs
for line in paramlines:
if line.find('SN=')>-1:
try:
txt=''
self.SNs=[]
SNdata=line.replace('\n',',').replace('SN=','').split(',')
char_set=[str(i) for i in range(10)]
char_set.append('*')
for dat in SNdata:
d=[c in char_set for c in dat.strip()]
if sum(d)==len(d) and len(d)>4 and len(d)<7:
txt+=dat.strip()+', '
self.SNs.append(dat.strip())
self.SNs[0]
if len(txt)>0:
txt=txt[:-2]
self.notebook.tabFour.SNlist.Clear()
self.notebook.tabFour.SNlist.SetValue(txt)
except:
print 'Problem with serial numbers from config file! Exiting...'
sys.exit(1)
if line.find('days=')>-1:
####get time to analyze
try:
dat=re.search(r'days=(\d+)',line)
prevdays=int(dat.group(1))
except:
print 'Problem with days from config file! Exiting...'
sys.exit(1)
self.startdate=datetime.date.today()-datetime.timedelta(days=prevdays)
self.starttime=datetime.time(0,0,0)
self.enddate=datetime.date.today()
self.endtime=datetime.time(23,59,59)
startdate_full=self.startdate
enddate_full=self.enddate
#set output folder
if line.find('outputdir=')>-1:
try:
dat=re.search(r'outputdir=(.+)',line)
tempdir=dat.group(1)
os.path.exists(tempdir)
self.resultsDir=tempdir
except:
print 'Problem with path from config file! Exiting...'
sys.exit(1)
if line.find('startdate=')>-1:
####get time to analyze
try:
dat=re.search(r'startdate=(.+)',line)
startdate_full=dateutil.parser.parse(dat.group(1))
self.startdate=startdate_full.date()
self.starttime=startdate_full.time()
except:
print 'Problem with startdate from config file! Exiting...'
sys.exit(1)
if line.find('enddate=')>-1:
try:
dat=re.search(r'enddate=(.+)',line)
enddate_full=dateutil.parser.parse(dat.group(1))
self.enddate=enddate_full.date()
self.endtime=enddate_full.time()
except:
print 'Problem with enddate from config file! Exiting...'
sys.exit(1)
if line.find('SCMlogs=True')>-1:
self.radio1_SCM.SetValue(False)
self.radio2_SCM.SetValue(True)
try:
if startdate_full=='' or enddate_full=='':
print 'Problem with given dates from config file! Exiting...'
sys.exit()
if startdate_full>enddate_full:
print 'Start day is after end date! Exiting...'
sys.exit(1)
except:
print 'Problem with enddate from config file! Exiting...'
sys.exit(1)
self.notebook.SetSelection(3)
try:
self.OnAnalyze(wx.Event)
print 'Exiting...'
sys.exit(0)
except:
sys.exit(1)
else:
try:
dat=re.search(r'([0-9*]{5,6});(\d{4}/\d{2}/\d{2}\s*\d{2}:\d{2});(\d{4}/\d{2}/\d{2}\s*\d{2}:\d{2});(.+)',params)
self.SNs=(dat.group(1).strip())
self.notebook.tabFour.SNlist.Clear()
self.notebook.tabFour.SNlist.SetValue(self.SNs)
startdate_full=dateutil.parser.parse(dat.group(2))
self.startdate=startdate_full.date()
self.starttime=startdate_full.time()
enddate_full=dateutil.parser.parse(dat.group(3))
self.enddate=enddate_full.date()
self.endtime=enddate_full.time()
tempdir=dat.group(4)
if os.path.exists(tempdir):
self.resultsDir=tempdir
else:
print 'Problem results directory! Exiting...'
sys.exit(1)
self.notebook.SetSelection(3)
self.OnAnalyze(wx.Event)
print 'Exiting...'
sys.exit(0)
except Exception as e:
print e
sys.exit(1)
#------------------------------------------
def WriteRegData(self):
try:
if self.os_type.find('linux')==-1:
self.RegistryData = wx.Config("PyTAX\EventlogAnalyzer", style=wx.CONFIG_USE_GLOBAL_FILE)
self.RegistryData.Write("sourceDir", self.sourceDir)
self.RegistryData.Write("resultsDir", self.resultsDir)
self.RegistryData.Write("SNList", self.notebook.tabFour.SNlist.GetValue())
else:
direfilename=os.path.join(os.path.expanduser('~'),'.ea_dirs.dat')
dirfile=open(direfilename,'w')
dirfile.write(self.sourceDir+'\n')
dirfile.write(self.resultsDir+'\n')
dirfile.write(self.notebook.tabFour.SNlist.GetValue())
dirfile.close()
except:
print "Error writing windows registry"
#------------------------------------------
def OnTubeInfo(self,event):
self.get_dates()
self.TubeSerialNumListA=[]
self.TubeSerialNumListB=[]
tab=self.notebook.GetSelection()
tubeinfostrA=''
tubeinfostrB=''
tubeinfostr=''
if tab==1:
print "Nicht verfuegbar!"
return
elif tab==2:
print "Nicht verfuegbar!"
return
elif tab==3: #SNs
if(self.RB_plane2.GetSelection()==0):
planes=['A']
elif(self.RB_plane2.GetSelection()==1):
planes=['B']
else:
planes=['A','B']
self.notebook.tabFour.OnCheckSNList(0)
if len(self.SNs)==1:
singleSN=self.SNs[0]
if (singleSN).isdigit():
self.onScan()
if singleSN in self.serialList.keys():
for SW_path in self.serialList[singleSN]:
zfile_list=glob.glob(os.path.join(SW_path,'XA*LogFiles.zip'))
zfile_list=sorted(zfile_list)
for zfile in zfile_list:
zf = zipfile.ZipFile(zfile) #just take last zip files to extract caf file (Problem: what to do if SW changes?)
filelist=zf.namelist()
if not IcConsMode:
print "reading "+zfile
for plane in planes:
tubeSNdata='n.a.'
for filename in filelist:
#XA121001_2013_12_19_AxTubeInfoAReport.html
str2='_AxTubeInfo'+plane+'Report.html'
if filename.find('XA')>-1 and filename.find(str2)>-1:
filedate=self.GetFileDateTubeDat(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
fp = zf.open(filename)
lines=fp.readlines()
fp.close()
tubeSNdata=self.getSingleTubeSerialNumber(lines)
if plane=='A':
self.TubeSerialNumListA.append(tubeSNdata)
else:
self.TubeSerialNumListB.append(tubeSNdata)
else:
print "SN not found!"
return
else:
print "No valid SN!"
return
else:
wx.MessageBox('Not available for more than one SN!', 'Tube info', wx.OK | wx.ICON_INFORMATION)
return
else:
if(self.RB_plane.GetSelection()==0):
planes=['A']
elif(self.RB_plane.GetSelection()==1):
planes=['B']
else:
planes=['A','B']
tube_data2=glob.glob(os.path.join(self.sourceDir,'Reports','maintenance','*'))
tube_data2=sorted(tube_data2)
for plane in planes:
for filename in tube_data2:
if (filename.rfind('AxTubeInfo'+plane+'Report.html')>-1 ):
filedate=self.GetFileDateTubeDat(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
fp = open(filename)
lines=fp.readlines()
fp.close()
tubeSNdata=self.getSingleTubeSerialNumber(lines)
if plane=='A':
self.TubeSerialNumListA.append(tubeSNdata)
else:
self.TubeSerialNumListB.append(tubeSNdata)
##only Tube SNs changes
tubeinfostrA+='Plane A Tubes:\n'
tubeinfostrB+='Plane B Tubes:\n'
date=''
date_last=''
SN=''
BE=''
#Plane A
if 'A' in planes:
old_SN='n.a.'
old_date='n.a.'
old_BE='n.a'
date='n.a.'
SN='n.a.'
BE='n.a.'
SN_last=0
for i in range(len(self.TubeSerialNumListA)):
(date,SN,BE)=self.TubeSerialNumListA[i]
if i>0:
(date_last,SN_last,BE_last)=self.TubeSerialNumListA[i-1]
else:
SN_last=0
#tubeinfostrA+= 'first date:\t'+date +'\tTube SN: '+SN +'\tBE: '+BE+'\n'
if SN!=SN_last:
if SN_last!=0:
tubeinfostrA+= 'out date:\t'+date_last+'\tTube SN: '+SN_last+'\tBE: '+BE_last+'\n'
tubeinfostrA+= 'in date:\t'+date +'\tTube SN: '+SN +'\tBE: '+BE+'\n'
tubeinfostrA+= 'last date:\t'+date +'\tTube SN: '+SN +'\tBE: '+BE+'\n'
#Plane B
if 'B' in planes:
old_SN='n.a.'
old_date='n.a.'
old_BE='n.a'
date='n.a.'
SN='n.a.'
BE='n.a.'
SN_last=0
for i in range(len(self.TubeSerialNumListB)):
(date,SN,BE)=self.TubeSerialNumListB[i]
if i>0:
(date_last,SN_last,BE_last)=self.TubeSerialNumListB[i-1]
else:
SN_last=0
#tubeinfostrB+= 'first date:\t'+date +'\tTube SN: '+SN +'\tBE: '+BE+'\n'
if SN!=SN_last:
if SN_last!=0:
tubeinfostrB+= 'out date:\t'+date_last+'\tTube SN: '+SN_last+'\tBE: '+BE_last+'\n'
tubeinfostrB+= 'in date:\t'+date +'\tTube SN: '+SN +'\tBE: '+BE+'\n'
tubeinfostrB+= 'last date:\t'+date +'\tTube SN: '+SN +'\tBE: '+BE+'\n'
if planes==['A']:
tubeinfostr=tubeinfostrA
elif planes==['B']:
tubeinfostr=tubeinfostrB
else:
tubeinfostr=tubeinfostrA+'\n'+tubeinfostrB
if len(self.TubeSerialNumListA)==0 and len(self.TubeSerialNumListB)==0:
wx.MessageBox('No tube data found\nin selected period!', 'Tube info', wx.OK | wx.ICON_INFORMATION)
else:
wx.MessageBox(tubeinfostr, 'Tube info', wx.OK | wx.ICON_INFORMATION)
ret_val={'A':tubeinfostrA,'B':tubeinfostrB}
return ret_val
#------------------------------------------
def UpdateSourceDir(self):
DAT=[]
eventlogs_exists=0
try:
all_files=os.listdir(self.sourceDir)
except:
all_files=os.listdir('D:')
try:
all_files += os.listdir(os.path.join(self.sourceDir,'Event_Logs')) #jn1
except:
True
for filename in all_files:
if (filename.rfind('_AppEventLog.txt')>1 ):
DAT.append(filename)
eventlogs_exists=1
if(eventlogs_exists==1):
startdate=datetime.datetime(2525,12,12)
enddate= datetime.datetime(1901,12,12)
for filename in DAT:
temp =self.GetFileDate(filename)
if startdate>temp:
startdate=temp
if enddate<temp:
enddate=temp
temp1=wx.DateTime()
temp1.Set(startdate.day,startdate.month-1,startdate.year,0,0,0)
self.datepicker_start.SetValue(temp1)
self.datepicker_start.Refresh()
self.timepicker_start.SetValue(temp1)
temp1.Set(enddate.day,enddate.month-1,enddate.year,23,59,59)
self.datepicker_end.SetValue(temp1)
self.datepicker_end.Refresh()
self.timepicker_end.SetValue(temp1)
txt="Logs found!\n"
txt+="earliest: {0}\n".format(DAT[0])
txt+="latest: {0}".format(DAT[len(DAT)-1])
self.earliest.WriteText(txt)
else:
self.earliest.WriteText("No logs found!")
startdate=datetime.date.today()-datetime.timedelta(days=7)
enddate= datetime.date.today()
temp1=wx.DateTime()
temp1.Set(startdate.day,startdate.month-1,startdate.year,0,0,0)
self.datepicker_start.SetValue(temp1)
self.datepicker_start.Refresh()
self.timepicker_start.SetValue(temp1)
temp1.Set(enddate.day,enddate.month-1,enddate.year,23,59,59)
self.datepicker_end.SetValue(temp1)
self.datepicker_end.Refresh()
self.timepicker_end.SetValue(temp1)
#------------------------------------------
def OnOpenSourceDir(self, event):
dialog = wx.DirDialog(None, "Choose a directory:", self.sourceDir,style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
self.sourceDir=dialog.GetPath()
self.text_ctrl_1.SetValue(self.sourceDir)
#logging.info(self.sourceDir)
dialog.Destroy()
self.text_ctrl_1.SetBackgroundColour('white')
self.text_ctrl_1.Refresh()
self.WriteRegData()
DAT=[]
eventlogs_exists=0
all_files=os.listdir(self.sourceDir)
try:
all_files += os.listdir(os.path.join(self.sourceDir,'Event_Logs')) #jn1
except:
True
for filename in all_files:
if (filename.rfind('_AppEventLog.txt')>1 ):
DAT.append(filename)
eventlogs_exists=1
if(eventlogs_exists==1):
startdate=datetime.datetime(2525,12,12)
enddate= datetime.datetime(1901,12,12)
for filename in DAT:
temp =self.GetFileDate(filename)
if startdate>temp:
startdate=temp
if enddate<temp:
enddate=temp
temp1=wx.DateTime()
temp1.Set(startdate.day,startdate.month-1,startdate.year,0,0,0)
self.datepicker_start.SetValue(temp1)
self.datepicker_start.Refresh()
self.timepicker_start.SetValue(temp1)
temp1.Set(enddate.day,enddate.month-1,enddate.year,23,59,59)
self.datepicker_end.SetValue(temp1)
self.datepicker_end.Refresh()
self.timepicker_end.SetValue(temp1)
self.earliest.Clear()
txt="Logs found!\n"
txt+="earliest: {0}\n".format(DAT[0])
txt+="latest: {0}".format(DAT[len(DAT)-1])
self.earliest.WriteText(txt)
else:
self.earliest.Clear()
self.earliest.WriteText("No logs found!")
#------------------------------------------
def OnEditSourceDir(self,event):
temp=self.text_ctrl_1.GetValue()
old_dir=self.sourceDir
if(os.path.isdir(temp)):
self.sourceDir=temp
self.WriteRegData()
DAT=[]
eventlogs_exists=0
all_files=os.listdir(self.sourceDir)
try:
all_files += os.listdir(os.path.join(self.sourceDir,'Event_Logs')) #jn1
except:
True
for filename in all_files:
if (filename.rfind('_AppEventLog.txt')>1 ):
DAT.append(filename)
eventlogs_exists=1
if(eventlogs_exists==1):
startdate=datetime.datetime(2525,12,12)
enddate= datetime.datetime(1901,12,12)
for filename in DAT:
temp =self.GetFileDate(filename)
if startdate>temp:
startdate=temp
if enddate<temp:
enddate=temp
temp1=wx.DateTime()
temp1.Set(startdate.day,startdate.month-1,startdate.year,0,0,0)
self.datepicker_start.SetValue(temp1)
self.datepicker_start.Refresh()
self.timepicker_start.SetValue(temp1)
temp1.Set(enddate.day,enddate.month-1,enddate.year,23,59,59)
self.datepicker_end.SetValue(temp1)
self.datepicker_end.Refresh()
self.timepicker_end.SetValue(temp1)
self.earliest.Clear()
txt="Logs found!\n"
txt+="earliest: {0}\n".format(DAT[0])
txt+="latest: {0}".format(DAT[len(DAT)-1])
self.earliest.WriteText(txt)
self.WriteRegData()
else:
self.earliest.SetLabel("no logs found")
else:
self.sourceDir=old_dir
self.text_ctrl_1.SetValue(old_dir)
self.text_ctrl_1.SetBackgroundColour('white')
self.text_ctrl_1.Refresh()
#------------------------------------------
def OnChangeSourceDir(self,event):
self.text_ctrl_1.SetBackgroundColour('red')
self.text_ctrl_1.Refresh()
#------------------------------------------
def OnOpenResultsDir(self, event):
dialog = wx.DirDialog(None, "Choose a directory:",self.resultsDir,style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
self.resultsDir=dialog.GetPath()
self.text_ctrl_2.SetValue(self.resultsDir)
#logging.info(self.resultsDir)
dialog.Destroy()
self.WriteRegData()
self.text_ctrl_2.SetBackgroundColour('white')
self.text_ctrl_2.Refresh()
#------------------------------------------
def OnEditResultsDir(self,event):
temp=self.text_ctrl_2.GetValue()
temp.strip()
old_dir=self.resultsDir
if(os.path.isdir(temp)):
self.resultsDir=temp
self.WriteRegData()
else:
self.resultsDir=old_dir
self.text_ctrl_2.SetValue(old_dir)
self.text_ctrl_2.SetBackgroundColour('white')
self.text_ctrl_2.Refresh()
#------------------------------------------
def OnChangeResultsDir(self,event):
self.text_ctrl_2.SetBackgroundColour('red')
self.text_ctrl_2.Refresh()
#------------------------------------------
def __set_properties(self):
global EAversion
self.SetTitle("Eventlog Analyzer_v"+EAversion)
#self.bitmap_button_1.SetSize(self.bitmap_button_1.GetBestSize())
#self.bitmap_button_2.SetSize(self.bitmap_button_2.GetBestSize())
#------------------------------------------
def __do_layout(self):
#sizer_1 = wx.FlexGridSizer(3, 3, 0, 0)
#sizer_1.Add(self.label_1, 0, wx.ALIGN_LEFT)
#sizer_1.Add(self.text_ctrl_1, 0, wx.EXPAND)
#sizer_1.Add(self.bitmap_button_1, 0, wx.ALIGN_RIGHT)
#sizer_1.Add(self.label_2, 0, wx.ALIGN_LEFT)
#sizer_1.Add(self.text_ctrl_2, 0, wx.EXPAND)
#sizer_1.Add(self.bitmap_button_2, 0, wx.ALIGN_RIGHT)
#self.SetSizer(sizer_1)
#self.Layout()
return
#------------------------------------------
def GetFileDate(self,filename):
#XA146000_2012_01_31_AppEventLog.txt
dat33=re.search(r'.*XA\d+_(\d+)_(\d+)_(\d+)_AppEventLog.+txt',filename)
if dat33!=None:
mydate=datetime.datetime(int(dat33.group(1)),int(dat33.group(2)),int(dat33.group(3)),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
#------------------------------------------
def GetFileDateCaf(self,filename):
#XA146000_2012_01_31_AppEventLog.txt
dat33=re.search(r'.*XA\d+_(\d+)_(\d+)_(\d+).*\.caf\.txt',filename)
if dat33!=None:
mydate=datetime.datetime(int(dat33.group(1)),int(dat33.group(2)),int(dat33.group(3)),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
#------------------------------------------
def GetExamsetDate(self,filename):
#XA123007_2014_05_08_ExamSets.txt.xlt
dat33=re.search(r'.*XA\d+_(\d+)_(\d+)_(\d+)_ExamSets.txt.xlt',filename)
if dat33!=None:
mydate=datetime.datetime(int(dat33.group(1)),int(dat33.group(2)),int(dat33.group(3)),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
#------------------------------------------
def GetZipFileDate(self,filename):
#XA121001_2013_12_26_LogFiles.zip (-?\d+|NIL)
if not IcConsMode:
print filename
dat33=re.search(r'.*XA\d+_(\d{4})_(\d{2})_(\d{2})_(Mon|Short|)LogFiles.zip',filename)
if dat33!=None:
mydate=datetime.datetime(int(dat33.group(1)),int(dat33.group(2)),int(dat33.group(3)),0,0,0)
return mydate
else:
dat33=re.search(r'.*XA\d+_(\d{2})_(\d{2})_(\d{4})_(Mon|Short|)LogFiles.zip',filename) #Jahr und Tag vertauscht im Zip-Fileanamen
if dat33!=None:
mydate=datetime.datetime(int(dat33.group(3)),int(dat33.group(2)),int(dat33.group(1)),0,0,0)
return mydate
else:
mydate=datetime.datetime(2525,1,1,0,0,0) #error
return mydate
#------------------------------------------
def GetFileDateEnv(self,filename):
#XA157436_20120207_EnvironmentLog.xml
dat33=re.search(r'.+XA\d+_(\d+)_EnvironmentLog.+xml',filename)
if dat33.group(0)!=None:
mydate=datetime.datetime(int(dat33.group(1)[0:4]),int(dat33.group(1)[4:6]),int(dat33.group(1)[6:8]),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
#------------------------------------------
def GetFileDateErr(self,filename):
#XA109024_2015_04_08_AXIS_ERR.LOG
dat33=re.search(r'.*XA\d+_(\d{4})_(\d{2})_(\d{2})_AXIS_ERR.LOG',filename)
if dat33.group(0)!=None:
mydate=datetime.datetime(int(dat33.group(1)),int(dat33.group(2)),int(dat33.group(3)),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
#------------------------------------------
def GetFileDateTubeDat(self,filename):
#XA157436_20120207_EnvironmentLog.xml
if filename.find('AXTubeUsage')>-1:
dat33=re.search(r'.+AXTubeUsage[AB].(\d+)',filename)
if dat33.group(0)!=None:
mydate=datetime.datetime(int(dat33.group(1)[0:4]),int(dat33.group(1)[4:6]),int(dat33.group(1)[6:8]),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
else: #XA153988_2012_01_13_AxTubeInfoAReport.html
dat33=re.search(r'.*XA\d+_(\d+)_(\d+)_(\d*)_AxTubeInfo.+',filename)
if dat33.group(0)!=None:
mydate=datetime.datetime(int(dat33.group(1)),int(dat33.group(2)),int(dat33.group(3)),0,0,0)
return mydate
else:
mydate=datetime.datetime(0,0,0,0,0,0) #error
return mydate
#------------------------------------------
def Analyze_AXISerrorlog(self):
tab=self.notebook.GetSelection()
for act_file in self.Auswahl_axiserr:
if not IcConsMode:
print act_file
if tab==2:
blubb=2
elif tab==3 or tab==1: #SNs or SW version
try:
zf = zipfile.ZipFile(self.Auswahl_axiserr_dict[act_file,'zipfile'])
fp = zf.open(self.Auswahl_axiserr_dict[(act_file,'fullname')])
axerr_lines=fp.readlines()
fp.close()
except:
print 'error opening '+act_file
axerr_lines=''
else:
axerr_lines=''
#for line in axerr_lines:
#print line
#------------------------------------------
def Analyze_EnvironmetalLogs(self):
tab=self.notebook.GetSelection()
self.envtime=[]
self.envtime2=[]
self.envtime3=[]
self.driv_tube_freq=[]
self.act_tube_freq=[]
self.t0_time=[]
self.t0_temp=[]
self.driv_current=[]
if self.cb_enh_env.GetValue():
self.env_params={}
self.env_params['temperature Inv2','ANG-plane']='deg C'
self.env_params['temperature Inv1','ANG-plane']='deg C'
self.env_params['RTC Temp1','CSF-plane']='deg C'
self.env_params['RTC Temp2','CSF-plane']='deg C'
self.env_params['FDOwnTemp', 'ACU-plane']='deg C'
self.env_params['FDCoolWaterTemp', 'ACU-plane']='deg C'
self.env_params['CPU0_TEMP','IVS']='deg C'
self.env_params['CPU1_TEMP','IVS']='deg C'
self.env_params['CPU0_TEMP','IAS-plane']='deg C'
self.env_params['P0_VRD_TEMP','IVS']='deg C'
self.env_params['P0_VRD_TEMP','IAS-plane']='deg C'
self.env_params['PRI_RD890_TEMP','IAS-plane']='deg C'
self.env_params['SAS_TEMP','IAS-plane']='deg C'
self.env_params['AXIS Container','IVS']='deg C'
self.env_params['System Cabinet Temp1','CSF-plane']='deg C'
self.env_params['System Cabinet Temp2','CSF-plane']='deg C'
self.env_params['REAR_FAN1','IVS']='rpm'
self.env_params['REAR_FAN1','IAS-plane']='rpm'
self.env_params['FRONT_FAN3','IVS']='rpm'
self.env_params['FRONT_FAN3','IAS-plane']='rpm'
self.env_params['CPU0 FAN','IVS']='rpm'
self.env_params['CPU0 FAN','IAS-plane']='rpm'
self.env_params['VABT','IVS']='V'
self.env_params['RTC Voltages:3.3V','CSF-plane']='V'
self.env_params['RTC Voltages:Vcc','CSF-plane']='V'
self.env_params['RTC Voltages:12V','CSF-plane']='V'
self.env_params['RTC Voltages:-12V','CSF-plane']='V'
self.env_timestamp={}
self.env_val={}
for key in self.env_params.keys():
self.env_timestamp[key]=[]
self.env_val[key]=[]
setplane=self.plane
plane=0
for act_file in self.AuswahlEnvLogs:
if not IcConsMode:
print act_file
if tab==2:
blubb=2
elif tab==3 or tab==1: #SNs or SW version
try:
zf = zipfile.ZipFile(self.AuswahlEnvLogs_dict[act_file,'zipfile'])
fp = zf.open(self.AuswahlEnvLogs_dict[(act_file,'fullname')])
handler=fp.read()
fp.close()
except:
print 'error opening '+act_file
handler=''
else:
handler=open(act_file).read()
try:
#VX...
#<DataGroup Group_Name= "ANG-A" DateTime="2013-11-13 00:05:00"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="actual tube anode frequency" Variable_Unit=" "><DoubleVariable Low_Specification="2.22507385851e-308" High_Specification="1.79769313486e+308" Double_Value="206."/></DataEntry></DataElement></DataPackage></DataGroup>
#<DataGroup Group_Name= "ACU-A" DateTime="2013-11-13 00:43:40"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="FDCoolWaterTemp" Variable_Unit=" deg. C">
#<DataGroup Group_Name= "IVS" DateTime="2013-11-13 00:43:32"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="PRI_RD890_TEMP" Variable_Unit=" deg. C">
#<DataGroup Group_Name= "CSF-A" DateTime="2013-11-13 00:41:19"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="RTC Voltages:3.3V" Variable_Unit=" V">
#<DataGroup Group_Name= "ANG-B" DateTime="2013-11-13 00:42:08"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="temperature H1" Variable_Unit=" deg. C">
#<DataGroup Group_Name= "ANG-B" DateTime="2013-11-13 00:44:08"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="temperature Inv2" Variable_Unit=" deg. C">
#EAS
#<DataGroup Group_Name= "ANG-A" DateTime="2014-06-17 00:03:49"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="actual tube anode frequency" Variable_Unit=" Hz"><DoubleVariable Low_Specification="2.22507385851e-308" High_Specification="1.79769313486e+308" Double_Value="156."/></DataEntry></DataElement></DataPackage></DataGroup>
#<DataGroup Group_Name= "ANG-A" DateTime="2014-06-17 00:03:49"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="driving tube anode frequency" Variable_Unit=" Hz"><DoubleVariable Low_Specification="2.22507385851e-308" High_Specification="1.79769313486e+308" Double_Value="168."/></DataEntry></DataElement></DataPackage></DataGroup>
#<DataGroup Group_Name= "ANG-A" DateTime="2014-06-17 00:08:49"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="driving tube anode current" Variable_Unit=" mA"><DoubleVariable Low_Specification="2.22507385851e-308" High_Specification="1.79769313486e+308" Double_Value="2866."/></DataEntry></DataElement></DataPackage></DataGroup>
#<DataGroup Group_Name= "ACU-B" DateTime="2015-09-28 00:01:16"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="FDCoolWaterTemp" Variable_Unit="...
#plane='A'
#groups: CSF-B, ANG-A, ANG-B, IAS-A,IAS-B,IVS
search_str1='<DataGroup Group_Name= "ANG-'+self.plane+'" DateTime="\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"><DataPackage Package_Name= "Output"><DataElement Element_Name= "Output"><DataEntry Variable_Name="'
search_str2='" Variable_Unit="[ deg\.C| Hz| mA| V]+"><DoubleVariable Low_Specification="2\.22507385851e-308" High_Specification="1\.79769313486e\+308" Double_Value="[\d\.]+"'
data_str1='actual tube anode frequency'
data_str2='driving tube anode frequency'
data_str3='temperature signal T0'
data_str4='driving tube anode current'
data_str5='temperature H1'
p_act_tube_frq =re.compile(search_str1+data_str1+search_str2)
p_driv_tube_frq=re.compile(search_str1+data_str2+search_str2)
p_temp_T0 =re.compile(search_str1+data_str3+search_str2)
p_driv_current =re.compile(search_str1+data_str4+search_str2)
p_temp_H1 =re.compile(search_str1+data_str5+search_str2)
hits_act_tube_frq=p_act_tube_frq.findall(handler)
hits_drv_tube_frq=p_driv_tube_frq.findall(handler)
hits_driv_current=p_driv_current.findall(handler)
hits_temp_T0=p_temp_T0.findall(handler)
hits_temp_H1=p_temp_H1.findall(handler)
for hit in hits_act_tube_frq:
dat2=re.search('(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).+Double_Value="([\d\.]+)',hit)
self.envtime2.append(dat2.group(1))
self.act_tube_freq.append(float(dat2.group(2)))
for hit in hits_drv_tube_frq:
dat2=re.search('(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).+Double_Value="([\d\.]+)',hit)
self.envtime.append(dat2.group(1))
self.driv_tube_freq.append(float(dat2.group(2)))
for hit in hits_driv_current:
dat2=re.search('(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).+Double_Value="([\d\.]+)',hit)
self.envtime3.append(dat2.group(1))
self.driv_current.append(float(dat2.group(2)))
for hit in hits_temp_T0:
dat2=re.search('(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).+Double_Value="([\d\.]+)',hit)
self.t0_time.append(dat2.group(1))
self.t0_temp.append(float(dat2.group(2)))
for hit in hits_temp_H1:
dat2=re.search('(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).+Double_Value="([\d\.]+)',hit)
self.H1_time.append(dat2.group(1))
self.H1_temp.append(float(dat2.group(2)))
if self.cb_enh_env.GetValue():
for key in self.env_params.keys():
searchstr =re.compile(search_str1.replace('ANG-'+self.plane,key[1]).replace('plane',self.plane)+key[0]+search_str2)
hits=searchstr.findall(handler)
for hit in hits:
dat2=re.search('(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).+Double_Value="([\d\.]+).',hit)
self.env_timestamp[key].append(dateutil.parser.parse(dat2.group(1)))
self.env_val[key].append(float(dat2.group(2)))
except:
print "Problem with Environmentallog file! Skipping file: "+act_file
#output to file
if len(self.driv_current)==0:
self.driv_current=[0 for z in self.act_tube_freq]
num_ele=min(len(self.envtime),len(self.envtime2))
else:
num_ele=min(len(self.envtime),len(self.envtime2),len(self.envtime3))
if len(self.envtime)>0:
txt='Date_time,drive_tube_freq,act_tube_freq,drive_current\n'
for i in xrange(num_ele):
act_tube_frq=self.act_tube_freq[i]
if act_tube_frq==65535:
act_tube_frq=-1
datastring = self.envtime[i] + ',' + str(self.driv_tube_freq[i]) + ',' + str(act_tube_frq)+','+str(self.driv_current[i])+'\n'
#print datastring
txt=txt+datastring
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
txt=txt.replace(',',';').replace('.',',')
try:
fromDate=self.envtime[0][0:10]
toDate=self.envtime[-1][0:10]
except:
fromDate=''
toDate=''
outputfile = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '_to_' + toDate +'_plane_' + str(self.plane) + '_tube_driving.csv')
fw = open(outputfile, "w")
fw.write(txt)
fw.close()
if len(self.t0_temp)>0:
txt='Date_time,Temp/[grad C]\n'
for i in xrange(len(self.t0_time)):
datastring= self.t0_time[i] + ',' + str(self.t0_temp[i])+'\n'
txt=txt+datastring
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
txt=txt.replace(',',';').replace('.',',')
try:
fromDate=self.t0_time[0][0:10]
toDate=self.t0_time[-1][0:10]
except:
fromDate=''
toDate=''
outputfile = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '_to_' + toDate +'_plane_' + str(self.plane) + '_temperature_T0.csv')
fw = open(outputfile, "w")
fw.write(txt)
fw.close()
else:
print 'No data for selected plane found in environmental log!'
#------------------------------------------------------------------
def getTubeSerialNumber(self):
SN='n.a.'
TubeSNlist=[]
tab=self.notebook.GetSelection()
try:
if self.AuswahlTubeData.__len__()>0:
for latestTubeDataFile in self.AuswahlTubeData:
if tab==2:
blubb=2
elif tab==3 or tab==1: #SNs
zf = zipfile.ZipFile(self.AuswahlTubeData_dict[latestTubeDataFile,'zipfile'])
#print "lese file " + self.Auswahl_dict[latestTubeDataFile,'fullname']
fp = zf.open(self.AuswahlTubeData_dict[latestTubeDataFile,'fullname'])
lines=fp.readlines()
fp.close()
else: #Standard
fp = open(latestTubeDataFile,'r')
lines=fp.readlines()
fp.close()
for i,line in enumerate(lines): #find line with tube exchange date <TD>01/13/12</TD>, SN is in next line
dat44=re.search(r'<TD>(\d+)/(\d+)/(\d+)</TD>',line)
if dat44!=None:
MatNrline=lines[i+1]
SNline=lines[i+2]
BEline=lines[i+3]
self.MatrNr=re.search(r'<TD>(.*)</TD>',MatNrline).group(1)
datSN=re.search(r'<TD>(.*)</TD>',SNline)
datBE=re.search(r'<TD>(.*)</TD>',BEline)
if datSN!=None and datBE!=None:
if datSN.group(1)!='':
SN=datSN.group(1)
if datBE.group(1)!='':
BE=datBE.group(1)
datestr=dat44.group(2)+'.'+dat44.group(1)+'.'+dat44.group(3)
TubeSNlist.append((datestr,SN,BE))
except:
True
if TubeSNlist==[]:
TubeSNlist.append(('n.a.','n.a.','n.a.'))
return TubeSNlist
#------------------------------------------------------------------
def getSingleTubeSerialNumber(self,lines):
SN='n.a.'
for i,line in enumerate(lines): #find line with tube exchange date <TD>01/13/12</TD>, SN is in next line
dat44=re.search(r'<TD>(\d+)/(\d+)/(\d+)</TD>',line)
if dat44!=None:
MatNrline=lines[i+1]
SNline=lines[i+2]
BEline=lines[i+3]
self.MatrNr=re.search(r'<TD>(.*)</TD>',MatNrline).group(1)
datSN=re.search(r'<TD>(.*)</TD>',SNline)
datBE=re.search(r'<TD>(.*)</TD>',BEline)
if datSN!=None and datBE!=None:
if datSN.group(1)!='':
SN=datSN.group(1)
else:
SN='n.a.'
if datBE.group(1)!='':
BE=datBE.group(1)
else:
BE='n.a.'
datestr=dat44.group(2)+'.'+dat44.group(1)+'.'+dat44.group(3)
Tube_data=(datestr,SN,BE)
return Tube_data #(datestr,SN,BE)
#------------------------------------------------------------------
def onScan(self):
if self.radio1_SCM.GetValue()==True:
folderList = glob.glob(self.sourceDirZipsArtis + '/V*/[0-9]*')
try:
folderList = folderList + glob.glob(self.sourceDirZipsEAS + '/V*/[0-9]*')
except:
True
else:
try:
folderList = glob.glob(self.sourceDirZipsSCM + '/[0-9]*')
except Exception, e:
print e
self.serialList = {}
for currentFolder in folderList:
temp=os.path.basename(currentFolder)
if temp.isdigit():
currentSerial = temp
if currentSerial not in self.serialList.keys():
self.serialList[currentSerial]=[]
self.serialList[currentSerial].append(currentFolder)
try:
for key in self.serialList.keys():
self.serialList[key]=sorted(self.serialList[key])
except:
True
#print serialList
#------------------------------------------------------------------
def onScanSW(self,SWlist):
if self.radio1_SCM.GetValue()==True:
folderList = glob.glob(self.sourceDirZipsArtis + '/V*/[0-9]*')
try:
folderList = folderList + glob.glob(self.sourceDirZipsEAS + '/V*/[0-9]*')
except:
True
else:
try:
folderList = glob.glob(self.sourceDirZipsSCM + '/[0-9]*')
except Exception, e:
print e
self.serialList = {}
for currentFolder in folderList:
currentSW=currentFolder.split(os.sep)[-2][0:4]
if currentSW in SWlist:
currentSerial = os.path.basename(currentFolder)
if currentSerial not in self.serialList.keys():
self.serialList[currentSerial]=[]
self.serialList[currentSerial].append(currentFolder)
try:
for key in self.serialList.keys():
self.serialList[key]=sorted(self.serialList[key])
except:
True
return self.serialList
#------------------------------------------------------------------
def OnAnalyze(self, event):
self.today=str(datetime.datetime.now()).replace(' ','_').replace(':','-')
self.logfilename=os.path.join(self.resultsDir, 'EA-errorlog_'+self.today+'.txt')
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(message)s',
filename=self.logfilename
)
self.init_analysis=True
self.init_analysis_mk=True
if self.enable_gui:
self.get_dates()
else:
self.start__datum=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,self.starttime.hour,self.starttime.minute,self.starttime.second)
self.ende__datum=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,self.endtime.hour,self.endtime.minute,self.endtime.second)
self.datastr=[]
if(self.RB_plane2.GetSelection()==0):
self.planes=['A']
elif (self.RB_plane2.GetSelection()==1):
self.planes=['B']
else:
self.planes=['A','B']
self.SN=0
self.resultsDirSN=self.resultsDir
tab=self.notebook.GetSelection()
if tab==1: # SW View
self.SW_list=[]
if self.notebook.tabTwo.Artis_VC14.Value==True:
self.SW_list.append('VC14')
if self.notebook.tabTwo.Artis_VC21.Value==True:
self.SW_list.append('VC21')
if self.notebook.tabTwo.Artis_VD10.Value==True:
self.SW_list.append('VD10')
if self.notebook.tabTwo.EAS_VA10.Value==True:
self.SW_list.append('VA10')
self.SWList=self.onScanSW(self.SW_list)
self.serialList={}
for currentFolder in self.SWList.values():
temp=os.path.basename(currentFolder[0])
if temp.isdigit():
currentSerial = temp
currentSW=currentFolder[0].split(os.sep)[-2][0:4]
if currentSW in self.SW_list:
if currentSerial not in self.serialList.keys():
self.serialList[currentSerial]=[]
self.serialList[currentSerial].append(currentFolder[0])
self.SNzips={}
counter=0
numSNs=len(self.serialList.keys())
for SN_key in sorted(self.serialList.keys()):
counter+=1
print SN_key+ ' ('+str(counter)+' of '+str(numSNs)+')'
for SN_path in self.serialList[SN_key]:
if SN_key not in self.SNzips.keys():
self.SNzips[SN_key]=glob.glob(os.path.join(SN_path,'XA*LogFiles.zip'))
else:
self.SNzips[SN_key]+glob.glob(os.path.join(SN_path,'XA*LogFiles.zip'))
for SN in sorted(self.SNzips.keys()):
self.SNzips[SN]=sorted(self.SNzips[SN])
self.SN=SN
self.resultsDirSN=os.path.join(self.resultsDir,self.SN)
try:
if not os.path.exists(self.resultsDirSN):
os.mkdir(self.resultsDirSN)
except:
print "Problem! Could not create output folder " +self.resultsDirSN
return
for self.plane in self.planes:
logging.info('Start analyzing '+str(SN)+' plane '+self.plane)
try:
self.OnAnalyzeSN_View(SN)
except Exception as err:
logging.info('Problem during analyis of SN '+str(SN) +' plane '+self.plane)
logging.error("Error during analysis data: %s", err)
logging.info('Continue with next system')
#self.today
elif tab==2: #Tube Type View
blubb=2
elif tab==3: #SNs
self.notebook.tabFour.OnEditResultsDir(wx.Event)
self.notebook.tabFour.OnCheckSNList(wx.Event)
self.onScan() #sets self.serialList
self.SNzips={}
for SN_sel in self.SNs:
for SN_key in sorted(self.serialList.keys()):
searchstr=SN_sel.replace('*','\d')
dat1=re.search(r'('+searchstr+')',SN_key)
if dat1!=None:
for SN_path in self.serialList[SN_key]:
print 'SN: '+str(SN_key)
for root, dirnames, filenames in os.walk(SN_path):
for filename in fnmatch.filter(filenames, 'XA*LogFiles.zip'):
if not IcConsMode:
print filename
if SN_key not in self.SNzips.keys():
zipdat=[]
self.SNzips[SN_key]=zipdat
self.SNzips[SN_key].append(os.path.join(root, filename))
SN=SN_key
if SN not in self.SNzips.keys(): #skip empty folders
continue
self.SNzips[SN]=sorted(self.SNzips[SN])
self.SN=SN
self.resultsDirSN=os.path.join(self.resultsDir,self.SN)
try:
if not os.path.exists(self.resultsDirSN):
os.mkdir(self.resultsDirSN)
except:
print "Problem! Could not create output folder " +self.resultsDirSN
return
self.no_plane_B_found=0
for self.plane in self.planes:
logging.info('Start analyzing '+str(SN)+' plane '+self.plane)
try:
self.OnAnalyzeSN_View(SN)
except Exception as err:
logging.exception('Problem during analyis of SN '+str(SN) +' plane '+self.plane)
#logging.error("Error during analysis data: %s", err)
logging.info('Continuing with next system...')
else: #0 ==> Standard
#self.OnEditResultsDir(wx.Event)
#self.OnEditSourceDir(wx.Event)
self.resultsDirSN=self.resultsDir
self.OnAnalyzeStandard()
if not IcConsMode and self.enable_gui:
wx.MessageBox("Done!")
print 'Done!'
logging.info('Done')
if send_mail==True and (socket.gethostname()=='FORS14AA' or socket.gethostname()=='FORS18AA' or socket.gethostname()=='MD1F5GCC'):
global senderAddress
global recipientAddress
subject = 'Errorlog from EA'
text = open(self.logfilename).read()
if text.find('ERROR')>-1:
######### do not edit below this line #########
server = 'medmailbalance.erlm.siemens.de'
headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (senderAddress, recipientAddress, subject)
message = headers + text
try:
mailServer = smtplib.SMTP(server)
mailServer.sendmail(senderAddress, recipientAddress, message)
mailServer.quit()
except Exception as err:
logging.exception('Problem during sending mail!')
return
#-----------------------------------------------------------------------------------------------
def OnAnalyzeStandard(self):
self.envtime=[]
self.driv_tube_freq=[]
self.act_tube_freq=[]
self.t0_time=[]
self.t0_temp=[]
self.driv_current=[]
self.H1_time=[]
self.H1_temp=[]
try:
del self.myXEvent
except:
True; #ok war nicht existent
self.myXEvent=XEvent()
self.events=0
global Dateien
Dateien = []
self.eventlog_files = []
self.system_caf = []
self.axiom_caf = []
self.env_logs = []
self.examsets = []
self.tube_data = []
self.Auswahl = []
self.AuswahlEnvLogs = []
self.AuswahlTubeData= []
self.AuswahlZips = []
self.AuswahlExamSet= []
if(self.RB_plane.GetSelection()==0):
self.plane='A'
else:
self.plane='B'
# look in one directory only (old, need to copy files into same directory)
try:
all_filenames = os.listdir(self.sourceDir)
#Eventlog-Files
for filename in all_filenames:
if (filename.rfind('_AppEventLog.txt')>1 ):
Dateien.append(filename)
filename=os.path.join(self.sourceDir,filename)
if( os.path.isfile(filename) ):
self.eventlog_files.append(filename)
#system.caf
for filename in all_filenames:
if (filename.rfind('system.caf.txt')>1 ):
filename=os.path.join(self.sourceDir,filename)
if( os.path.isfile(filename) ):
self.system_caf.append(filename)
#axiom.caf
for filename in all_filenames:
if (filename.rfind('axiom.caf.txt')>1 ):
filename=os.path.join(self.sourceDir,filename)
if( os.path.isfile(filename) ):
self.axiom_caf.append(filename)
except:
True
if (self.system_caf.__len__()==0):
# look in correct subdirectories ...(jn)
print "found input files in subdirectory..."
try:
all_logfiles = os.listdir(os.path.join(self.sourceDir,'Event_Logs'))
all_caffiles = os.listdir(os.path.join(self.sourceDir,'Reports','ConfigData','system_rpt'))
all_axiomcaffiles = os.listdir(os.path.join(self.sourceDir,'Reports','ConfigData','IVS_rpt'))
try:
all_envionment_logs = os.listdir(os.path.join(self.sourceDir,'Other_Logs','EnvironmentLog'))
except:
all_envionment_logs =''
try:
all_tube_data = os.listdir(os.path.join(self.sourceDir,'Reports','SDC','TubeData'))
except:
all_tube_data=''
if all_tube_data=='':
try:
all_tube_data2 = os.listdir(os.path.join(self.sourceDir,'Reports','maintenance'))
except:
all_tube_data2=''
#XA123007_2014_05_07_ExamSets.txt.xlt
try:
all_examsets=os.listdir(os.path.join(self.sourceDir,'Reports','ExamSets'))
except:
all_examsets=''
#Eventlog-Files
for filename in all_logfiles:
if (filename.rfind('_AppEventLog')>-1 and filename.rfind('.txt')>-1 ):
Dateien.append('Event_Logs\\' + filename)
filename=os.path.join(self.sourceDir,'Event_Logs', filename)
if( os.path.isfile(filename) ):
self.eventlog_files.append(filename)
#system.caf
for filename in all_caffiles:
if (filename.rfind('system.caf.txt')>-1 ):
filename=os.path.join(self.sourceDir,'Reports','ConfigData','system_rpt',filename)
if( os.path.isfile(filename) ):
self.system_caf.append(filename)
#axiom.caf
for filename in all_axiomcaffiles:
if (filename.rfind('axiom.caf.txt')>-1 ):
filename=os.path.join(self.sourceDir,'Reports','ConfigData','IVS_rpt',filename)
if( os.path.isfile(filename) ):
self.axiom_caf.append(filename)
#exam_sets
for filename in all_examsets:
if (filename.rfind('_ExamSets.txt.xlt')>-1 ):
filename=os.path.join(self.sourceDir,'Reports','ExamSets',filename)
if( os.path.isfile(filename) ):
self.examsets.append(filename)
#Environment Log
for filename in all_envionment_logs:
if (filename.rfind('_EnvironmentLog')>-1 and filename.rfind('xml')>-1 ):
filename=os.path.join(self.sourceDir,'Other_Logs','EnvironmentLog',filename)
if( os.path.isfile(filename) ):
self.env_logs.append(filename)
#Tube usage (for Tube SN)
if all_tube_data!='':
for filename in all_tube_data:
if (filename.rfind('AXTubeUsage'+self.plane)>-1 ):
filename=os.path.join(self.sourceDir,'Reports','SDC','TubeData',filename)
if( os.path.isfile(filename) ):
self.tube_data.append(filename)
else:
if all_tube_data2!='':
for filename in all_tube_data2:
if (filename.rfind('AxTubeInfo'+self.plane+'Report.html')>-1 ):
filename=os.path.join(self.sourceDir,'Reports','maintenance',filename)
if( os.path.isfile(filename) ):
self.tube_data.append(filename)
except:
True
if (self.system_caf.__len__()==0):
wx.MessageBox("No system.caf.txt file have been found in subfolder of specified source path!")
return
if (self.axiom_caf.__len__()==0):
wx.MessageBox("No axiom.caf.txt file have been found in subfolder of specified source path!")
return
if (self.eventlog_files.__len__()==0):
wx.MessageBox("No eventlog files have been found in specified source path!")
return
if (self.env_logs.__len__()==0 and self.cb_EnvLog.GetValue()):
wx.MessageBox("No environment log files have been found in subfolder of specified source path!")
if (self.tube_data.__len__()==0 ):
#wx.MessageBox("No tube data log files have been found in subfolder of specified source path!")
print "No tube data log files have been found in subfolder of specified source path!"
if (self.examsets.__len__()==0 ):
#wx.MessageBox("No tube data log files have been found in subfolder of specified source path!")
print "No exam sets have been found in subfolder of specified source path!"
self.eventlog_files.sort()
if(self.env_logs.__len__()!=0 and self.cb_EnvLog.GetValue()):
self.env_logs.sort()
self.tube_data.sort()
self.events=0
fp=open(self.system_caf[-1],'r') #Open latest file
caf_lines=fp.readlines()
fp.close()
self.process_system_caf(caf_lines)
for filename in self.axiom_caf:
fp=open(filename,'r')
caf_lines=fp.readlines()
fp.close()
self.process_axiom_caf(caf_lines,self.GetFileDateCaf(filename))
########################
#### Hier werden die Tage zwischen Startdatum und Enddatum in "Auswahl" gespeichert ###########
########################
for filename in self.eventlog_files:
filedate=self.GetFileDate(filename)
if not IcConsMode:
print filedate
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
self.Auswahl.append(filename)
self.env_logs=sorted(self.env_logs)
for filename in self.env_logs:
filedate=self.GetFileDateEnv(filename)
if not IcConsMode:
print filedate
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
self.AuswahlEnvLogs.append(filename)
for filename in self.tube_data:
filedate=self.GetFileDateTubeDat(filename)
if not IcConsMode:
print filedate
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
self.AuswahlTubeData.append(filename) #alle Tube_SN im Auswertezeitraum suchen
if self.AuswahlTubeData==[]: #wenn dort keine vorhanden ist, letze vorhandene nehmen
tempFN=[]
for filename in self.tube_data:
filedate=self.GetFileDateTubeDat(filename)
if filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
tempFN.append(filename)
if tempFN!=[]:
self.AuswahlTubeData.append(tempFN[-1])
if self.AuswahlExamSet==[]: #wenn dort keine vorhanden ist, letze vorhandene nehmen
for filename in self.examsets:
filedate=self.GetExamsetDate(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
self.AuswahlExamSet.append(filename)
#########################
if len(self.AuswahlEnvLogs)>0 and self.cb_EnvLog.GetValue():
self.Analyze_EnvironmetalLogs()
self.TubeSerialNumList=self.getTubeSerialNumber()
try:
self.TubeSerialNum= (self.TubeSerialNumList[-1])[1]
except:
self.TubeSerialNum='n.a.'
self.read_data()
self.calc_derived_measurements()
self.calc_power_vs_prom()
self.save_data()
self.show_data()
#------------------------------------------------------------------
def get_dates(self):
self.startdate =wxdate2pydate(self.datepicker_start.GetValue())
self.starttime =self.timepicker_start.GetValue(as_wxDateTime=True)
self.start__datum=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,self.starttime.Hour,self.starttime.Minute,self.starttime.Second)
self.enddate= wxdate2pydate(self.datepicker_end.GetValue())
self.endtime =self.timepicker_end.GetValue(as_wxDateTime=True)
self.ende__datum=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,self.endtime.Hour,self.endtime.Minute,self.endtime.Second)
#------------------------------------------------------------------
def OnAnalyzeSN_View(self,SN):
self.envtime=[]
self.driv_tube_freq=[]
self.act_tube_freq=[]
self.t0_time=[]
self.t0_temp=[]
self.driv_current=[]
self.H1_time=[]
self.H1_temp=[]
old_axiom_caf=''
try:
del self.myXEvent
except:
True; #ok war nicht existent
self.myXEvent=XEvent()
self.events=0
global Dateien
Dateien = []
self.eventlog_files = []
self.system_caf = []
self.axiom_caf = []
self.env_logs = []
self.examsets = []
self.tube_data = []
self.Auswahl = []
self.AuswahlEnvLogs = []
self.AuswahlTubeData= []
self.AuswahlZips = []
########################
#### Hier werden die Tage zwischen Startdatum und Enddatum in "Auswahl" gespeichert ###########
########################
#problem: Logfiles im zip sind oft vom Vortag -> datetime.timedelta(day=1)) was ist wenn die Maschine erst 3 Tage spaeter wieder gestartet wird
for filename in self.SNzips[SN]:
filedate=self.GetZipFileDate(filename)
if not IcConsMode:
print filedate
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=(datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59)+datetime.timedelta(days=3)):
self.AuswahlZips.append(filename)
self.AuswahlZips=sort(self.AuswahlZips)
if len(self.AuswahlZips)>0:
if 1:
try:
if self.plane=='A' or (self.plane=='B' and self.no_plane_B_found==0):
#XA123007_2014_01_14_system.caf.txt
zf = zipfile.ZipFile(self.AuswahlZips[-1]) #just take last zip files to extract caf file (Problem: what to do if SW changes?)
filelist=zf.namelist()
caf_file=''
caf_found=0
for filename in filelist:
if filename.find('XA')>-1 and filename.find('_system.caf.txt')>-1:
caf_file=filename
break
if caf_file !='':
fp = zf.open(caf_file)
caf_txt = fp.readlines()
fp.close()
self.process_system_caf(caf_txt)
caf_found=1
else:
print "No caf file found! Skipping evaluation!"
else:
print "No plane B found! Skipping evaluation!"
except:
"Error! Extracting caf files from zip failed!"
self.Auswahl_dict={}
self.Auswahl=[]
self.AuswahlEnvLogs_dict={}
self.AuswahlEnvLogs=[]
self.AuswahlTubeData_dict={}
self.AuswahlTubeData=[]
self.AuswahlExamSet_dict={}
self.AuswahlExamSet=[]
self.AuswahlIVS_Systemlog_dict={}
self.AuswahlIVS_Systemlog=[]
self.Auswahl_ang_fluoro_aaf_dict={}
self.Auswahl_ang_fluoro_aaf=[]
self.Auswahl_scu_caf_dict={}
self.Auswahl_scu_caf=[]
self.Auswahl_axiserr_dict={}
self.Auswahl_axiserr=[]
for zfile in self.AuswahlZips:
try:
zf = zipfile.ZipFile(zfile)
filelist=zf.namelist()
if not IcConsMode:
print "reading "+zfile
for filename in filelist:
#XA123007_2014_01_14_axiom.caf.txt
if filename.find('XA')>-1 and filename.find('_axiom.caf.txt')>-1 and os.path.basename(filename)!=old_axiom_caf and filename.find('IVS')>-1:
fp = zf.open(filename)
axiom_txt = fp.readlines()
fp.close()
self.process_axiom_caf(axiom_txt,self.GetFileDateCaf(filename))
old_axiom_caf=os.path.basename(filename)
#XA123007_2014_01_28_AppEventLog.txt
if filename.find('XA')>-1 and filename.find('_AppEventLog.txt')>-1:
filedate=self.GetFileDate(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
logname=os.path.basename(filename)
if self.Auswahl_dict.has_key((logname,'fullname')):
if zf.getinfo(filename).file_size>self.Auswahl_dict[logname,'size']:
self.Auswahl_dict[logname,'date']=zf.getinfo(filename).date_time
self.Auswahl_dict[logname,'size']=zf.getinfo(filename).file_size
self.Auswahl_dict[logname,'fullname']=filename
self.Auswahl_dict[logname,'zipfile']=zfile
else:
self.Auswahl_dict[logname,'date']=zf.getinfo(filename).date_time
self.Auswahl_dict[logname,'size']=zf.getinfo(filename).file_size
self.Auswahl_dict[logname,'fullname']=filename
self.Auswahl_dict[logname,'zipfile']=zfile
self.Auswahl.append(logname)
#XA123007_20140305_EnvironmentLog.xml
if filename.find('XA')>-1 and filename.find('_EnvironmentLog.xml')>-1 and self.cb_EnvLog.GetValue():
filedate=self.GetFileDateEnv(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
envlogname=os.path.basename(filename)
if self.AuswahlEnvLogs_dict.has_key((envlogname,'fullname')):
if zf.getinfo(filename).file_size>self.AuswahlEnvLogs_dict[envlogname,'size']:
self.AuswahlEnvLogs_dict[envlogname,'fullname']=filename
self.AuswahlEnvLogs_dict[envlogname,'date']=zf.getinfo(filename).date_time
self.AuswahlEnvLogs_dict[envlogname,'size']=zf.getinfo(filename).file_size
self.AuswahlEnvLogs_dict[envlogname,'zipfile']=zfile
else:
self.AuswahlEnvLogs_dict[envlogname,'fullname']=filename
self.AuswahlEnvLogs_dict[envlogname,'date']=zf.getinfo(filename).date_time
self.AuswahlEnvLogs_dict[envlogname,'size']=zf.getinfo(filename).file_size
self.AuswahlEnvLogs_dict[envlogname,'zipfile']=zfile
self.AuswahlEnvLogs.append(envlogname)
#..\109024\VD10E_140321-2\Other_Logs\ivs\XA109024_2015_04_08_AXIS_ERR.LOG
if filename.find('XA')>-1 and filename.find('_AXIS_ERR.LOG')>-1 and False and filename.find('ivs')>-1:
filedate=self.GetFileDateErr(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
errlogname=os.path.basename(filename)
if self.Auswahl_axiserr_dict.has_key((errlogname,'fullname')):
if zf.getinfo(filename).file_size>self.Auswahl_axiserr_dict[errlogname,'size']:
self.Auswahl_axiserr_dict[errlogname,'fullname']=filename
self.Auswahl_axiserr_dict[errlogname,'date']=zf.getinfo(filename).date_time
self.Auswahl_axiserr_dict[errlogname,'size']=zf.getinfo(filename).file_size
self.Auswahl_axiserr_dict[errlogname,'zipfile']=zfile
else:
self.Auswahl_axiserr_dict[errlogname,'fullname']=filename
self.Auswahl_axiserr_dict[errlogname,'date']=zf.getinfo(filename).date_time
self.Auswahl_axiserr_dict[errlogname,'size']=zf.getinfo(filename).file_size
self.Auswahl_axiserr_dict[errlogname,'zipfile']=zfile
self.Auswahl_axiserr.append(errlogname)
#XA123007_2014_05_09_ExamSets.txt.xlt
if filename.find('XA')>-1 and filename.find('_ExamSets.txt.xlt')>-1 and self.cb_examsets.GetValue():
filedate=self.GetExamsetDate(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
examsetname=os.path.basename(filename)
if self.AuswahlExamSet_dict.has_key((examsetname,'fullname')):
if zf.getinfo(filename).file_size>self.AuswahlEnvLogs_dict[envlogname,'size']:
self.AuswahlExamSet_dict[examsetname,'fullname']=filename
self.AuswahlExamSet_dict[examsetname,'date']=zf.getinfo(filename).date_time
self.AuswahlExamSet_dict[examsetname,'size']=zf.getinfo(filename).file_size
self.AuswahlExamSet_dict[examsetname,'zipfile']=zfile
else:
self.AuswahlExamSet_dict[examsetname,'fullname']=filename
self.AuswahlExamSet_dict[examsetname,'date']=zf.getinfo(filename).date_time
self.AuswahlExamSet_dict[examsetname,'size']=zf.getinfo(filename).file_size
self.AuswahlExamSet_dict[examsetname,'zipfile']=zfile
self.AuswahlExamSet.append(examsetname)
#XA153979_2014_08_06_07_33_14_AxSystemData.log
str2='_AxSystemData.log'
if filename.find('XA')>-1 and filename.find(str2)>-1:
#filedate=self.GetFileDateTubeDat(filename)
if filename.find('ivs')>-1:
ivs_system_data=os.path.basename(filename)
if self.AuswahlIVS_Systemlog_dict.has_key((ivs_system_data,'fullname')):
if zf.getinfo(filename).file_size>self.AuswahlTubeData_dict[ivs_system_data,'size']:
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'date']=zf.getinfo(filename).date_time
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'size']=zf.getinfo(filename).file_size
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'zipfile']=zfile
else:
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'fullname']=filename
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'date']=zf.getinfo(filename).date_time
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'size']=zf.getinfo(filename).file_size
self.AuswahlIVS_Systemlog_dict[ivs_system_data,'zipfile']=zfile
self.AuswahlIVS_Systemlog.append(ivs_system_data)
"""
if filename.find('ang_fluoro')>-1 and filename.find('aaf')>-1: #stores Plane A and B and grid ang_fluoro.aaf files
file_ang_fluoro=os.path.basename(filename)
if self.Auswahl_ang_fluoro_aaf_dict.has_key((file_ang_fluoro,'fullname')):
if zf.getinfo(filename).file_size>self.Auswahl_ang_fluoro_aaf_dict[file_ang_fluoro,'size']:
self.Auswahl_ang_fluoro_aaf_dict[file_ang_fluoro,'date']=zf.getinfo(filename).date_time
self.Auswahl_ang_fluoro_aaf_dict[file_ang_fluoro,'size']=zf.getinfo(filename).file_size
self.Auswahl_ang_fluoro_aaf_dict[file_ang_fluoro,'zipfile']=zfile
else:
self.Auswahl_ang_fluoro_aaf_dict[ivs_system_data,'fullname']=filename
self.Auswahl_ang_fluoro_aaf_dict[ivs_system_data,'date']=zf.getinfo(filename).date_time
self.Auswahl_ang_fluoro_aaf_dict[ivs_system_data,'size']=zf.getinfo(filename).file_size
self.Auswahl_ang_fluoro_aaf_dict[ivs_system_data,'zipfile']=zfile
self.Auswahl_ang_fluoro_aaf.append(file_ang_fluoro)
"""
#XA123007_2013_10_07_scu.caf.txt
if filename.find('_scu.caf.txt')>-1: #stores Plane A and B and grid ang_fluoro.aaf files
file_scu_caf=os.path.basename(filename)
if self.Auswahl_scu_caf_dict.has_key((file_scu_caf,'fullname')):
if zf.getinfo(filename).file_size>self.Auswahl_scu_caf_dict[file_scu_caf,'size']:
self.Auswahl_scu_caf_dict[file_scu_caf,'date']=zf.getinfo(filename).date_time
self.Auswahl_scu_caf_dict[file_scu_caf,'size']=zf.getinfo(filename).file_size
self.Auswahl_scu_caf_dict[file_scu_caf,'zipfile']=zfile
else:
self.Auswahl_scu_caf_dict[file_scu_caf,'fullname']=filename
self.Auswahl_scu_caf_dict[file_scu_caf,'date']=zf.getinfo(filename).date_time
self.Auswahl_scu_caf_dict[file_scu_caf,'size']=zf.getinfo(filename).file_size
self.Auswahl_scu_caf_dict[file_scu_caf,'zipfile']=zfile
self.Auswahl_scu_caf.append(file_scu_caf)
#XA123010_2014_02_28_AxTubeInfoBReport.html
str2='_AxTubeInfo'+self.plane+'Report.html'
if filename.find('XA')>-1 and filename.find(str2)>-1:
filedate=self.GetFileDateTubeDat(filename)
if filedate>=datetime.datetime(self.startdate.year,self.startdate.month,self.startdate.day,0,0,0) and filedate<=datetime.datetime(self.enddate.year,self.enddate.month,self.enddate.day,23,59,59):
tubeinfoname=os.path.basename(filename)
if self.AuswahlTubeData_dict.has_key((tubeinfoname,'fullname')):
if zf.getinfo(filename).file_size>self.AuswahlTubeData_dict[tubeinfoname,'size']:
self.AuswahlTubeData_dict[tubeinfoname,'fullname']=filename
self.AuswahlTubeData_dict[tubeinfoname,'date']=zf.getinfo(filename).date_time
self.AuswahlTubeData_dict[tubeinfoname,'size']=zf.getinfo(filename).file_size
self.AuswahlTubeData_dict[tubeinfoname,'zipfile']=zfile
else:
self.AuswahlTubeData_dict[tubeinfoname,'fullname']=filename
self.AuswahlTubeData_dict[tubeinfoname,'date']=zf.getinfo(filename).date_time
self.AuswahlTubeData_dict[tubeinfoname,'size']=zf.getinfo(filename).file_size
self.AuswahlTubeData_dict[tubeinfoname,'zipfile']=zfile
self.AuswahlTubeData.append(tubeinfoname)
except:
print "Error extracing eventlog from zip!"
self.Auswahl=sorted(self.Auswahl)
self.AuswahlEnvLogs=sorted(self.AuswahlEnvLogs)
self.AuswahlTubeData=sorted(self.AuswahlTubeData)
self.AuswahlExamSet=sorted(self.AuswahlExamSet)
self.AuswahlIVS_Systemlog=sorted(self.AuswahlIVS_Systemlog)
self.Auswahl_scu_caf=sorted(self.Auswahl_scu_caf)
self.Auswahl_axiserr=sorted(self.Auswahl_axiserr)
if (self.plane=='A' or (self.plane=='B' and self.no_plane_B_found==0)) and caf_found:
#Start Auswertung
self.TubeSerialNumList=self.getTubeSerialNumber()
try:
self.TubeSerialNum= (self.TubeSerialNumList[-1])[1]
except:
self.TubeSerialNum='n.a.'
####
try:
datastr=''
old_SN='n.a.'
SN_txt=[]
old_BE=0
old_date=''
for i, (date,SN,BE) in enumerate(self.TubeSerialNumList):
if i==0:
old_SN=SN
old_BE=BE
old_date=date
if SN!=old_SN:
SN_txt.append((old_date,old_SN,old_BE))
old_SN=SN
old_BE=BE
old_date=date
if i==len(self.TubeSerialNumList)-1:
SN_txt.append((date,SN,BE))
datastr+=','+str(SN_txt).replace(',',' ')
except:
datastr+=',na'
########
if self.cb_EnvLog.GetValue():
if self.AuswahlEnvLogs!=[]:
self.Analyze_EnvironmetalLogs()
if False:
if self.Auswahl_axiserr!=[]:
self.Analyze_AXISerrorlog()
self.read_data()
self.calc_derived_measurements()
self.calc_power_vs_prom()
self.save_data()
self.show_data()
else:
print "No caf file found!"
else:
print "No zip files for SN " +str(SN) +' in period '+ str(self.startdate)+ ' to '+str(self.enddate)+ ' found!'
#------------------------------------------------------------------
def process_axiom_caf(self,caf_lines,date):
for line in caf_lines:
#SW Version (will also try to get SW version fom logfile)
dat22=re.search(r'SYSTEM_VERSION.+\"(.+)\"',line)
if(dat22!=None):
self.myXEvent.SW.append((dat22.group(1).replace(' ','_'),date))
#syngo system type
dat22=re.search(r'syngo_system_type.+:\s(.+)',line)
if(dat22!=None):
self.myXEvent.syngo_system_type=dat22.group(1).strip()
#country
dat22=re.search(r'COUNTRY.+\"(.+)\"',line)
if(dat22!=None):
self.myXEvent.country=dat22.group(1).strip().replace('.',' ').replace(';',' ').replace(',',' ')
#city
dat22=re.search(r'CITY.+\"(.+)\"',line)
if(dat22!=None):
self.myXEvent.city=dat22.group(1).strip().replace('.',' ').replace(';',' ').replace(',',' ')
#------------------------------------------------------------------
def process_system_caf(self,caf_lines):
self.key_status={}
self.key_str=[]
self.key_str.append('High Speed 30 fps Module')
self.key_str.append('Card Acquisition Module')
self.key_str.append('Pediatric Card Acq. Module')
self.key_str.append('DSA Acquisition Module')
self.key_str.append('Card Sub Acquisition Module')
self.key_str.append('CLEARstent')
self.key_str.append('CLEARstent Live')
self.key_str.append('DR Acquisition Module')
self.key_str.append('Perivision')
self.key_str.append('DR Stepping')
self.key_str.append('Dynavision')
self.key_str.append('3D Acquisition')
self.key_str.append('3D CARD Acquisition')
self.key_str.append('3D HeartSweep Acquisition')
self.key_str.append('syngo DynaCT 360')
self.key_str.append('syngo DynaCT 100/s')
self.key_str.append('DynaCT Micro')
self.key_str.append('DR Dynavision')
self.key_str.append('Fluoro Loop Module')
self.key_str.append('Automap Module')
self.key_str.append('Digital Acq. Zoom Module')
self.key_str.append('IVUSmap')
self.key_str.append('Quant QCA')
self.key_str.append('Quant QCA2D with bifurcation')
self.key_str.append('Quant QCA3D')
self.key_str.append('Quant QVA')
self.key_str.append('Left Ventricel Analysis')
self.key_str.append('LVA Biplane (key)')
self.key_str.append('CD-R Archive Module')
self.key_str.append('DICOM Storage')
self.key_str.append('DICOM Query')
self.key_str.append('ECG-System')
self.key_str.append('ECG-Recording Module')
self.key_str.append('ECG-gated Fluoro Module')
self.key_str.append('MPPS')
self.key_str.append('Full Pixel Resolution')
self.key_str.append('Patient Data Anonymization')
self.key_str.append('Dynamic Reference')
self.key_str.append('Scene Recorder')
self.key_str.append('Image Quality Setting')
done_licences=False
for line in caf_lines:
if line.find('GROUP Parameters for Preprocessing')>-1:
done_licences=True
#system shape
if (line.find('System Shape')>-1 )and (line.find('Factory')==-1 ):
dat0=re.search(r'.+System Shape\s*:\s*(.+)',line)
self.myXEvent.SystemShape=dat0.group(1).strip()
#Tube
if (line.rfind('X-Ray Tube')>0 ):
if (line.rfind('Megalix 125/15/40/80')>-1 ):
self.myXEvent.numFoken=3 #Megalix Cat 3F
self.myXEvent.tubetype=0
self.myXEvent.tubetype_str='MegalixCat3F'
if (line.rfind('Megalix 125/35/80')>-1 ):
self.myXEvent.numFoken=2 #Megalix Cat 2F
self.myXEvent.tubetype=0
self.myXEvent.tubetype_str='MegalixCat2F'
if (line.rfind('Megalix 125/20/40/80')>-1 ):
self.myXEvent.numFoken=3 #Megalix Cat+ 3F
self.myXEvent.tubetype=1
self.myXEvent.tubetype_str='MegalixCat+3F'
if (line.rfind('Megalix 125/40/90')>-1 ):
self.myXEvent.numFoken=2 #Megalix Cat+ 2F
self.myXEvent.tubetype=1
self.myXEvent.tubetype_str='MegalixCat+2F'
if (line.rfind('GIGALIX 125/40/90-G')>-1 ):
self.myXEvent.numFoken=2 #´´Gialix 2F
self.myXEvent.tubetype=2
self.myXEvent.tubetype_str='Gigalix2F'
if (line.rfind('GIGALIX 125/30/40/90-G')>-1 ):
self.myXEvent.numFoken=3 #Gigalix 3F
self.myXEvent.tubetype=2
self.myXEvent.tubetype_str='Gigalix3F'
#---------FD-----------
#FD Type : Midsize Type 2b Detector
#FD Type Plane B : Midsize Type 2b Detector
tt=re.search(r'FD Type\s*:(.+)',line)
if tt!=None:
self.myXEvent.FD_A_name=tt.group(1).strip()
tt=re.search(r'FD Type Plane B\s*:(.+)',line)
if tt!=None:
self.myXEvent.FD_B_name=tt.group(1).strip()
if (line.rfind('FD Type')>-1 or line.rfind('ii_type')>-1):
if(self.plane=='A'):
if(line.rfind('Plane B')==-1):
if(line.rfind('Midsize Type 2a Detector')>-1):
self.myXEvent.FDtype='Midsize Type 2a Detector'
elif(line.rfind('Midsize Type 2b Detector')>-1):
self.myXEvent.FDtype='Midsize Type 2b Detector'
elif (line.rfind('Midsize Trixell Detector')>-1):
self.myXEvent.FDtype='Midsize Trixell Detector'
else:
dat0=re.search(r'.+(\d{4}).+',line)
if dat0!=None:
self.myXEvent.FDtype=dat0.group(1)
else:
if line.rfind('fd_a1_rot')>-1:
self.myXEvent.FDtype='4700' #'4700'=large FD=fd_a1_rot ; '4800'=small FD; 'Pixium 3040 CV'=large FD
elif line.rfind('fd_c2_rot')>-1:
self.myXEvent.FDtype='4800' #'4700'=large FD=fd_a1_rot ; '4800'=small FD; 'Pixium 3040 CV'=large FD
else:
self.myXEvent.FDtype='n.a.'
else: #plane B
self.no_plane_B_found=1
if (line.rfind('FD Type Plane B')>-1 or line.rfind('ii_type_b')>-1):
if(self.plane=='B'):
if(line.rfind('Midsize Type 2a Detector')>-1):
self.myXEvent.FDtype='Midsize Type 2a Detector'
elif(line.rfind('Midsize Type 2b Detector')>-1):
self.myXEvent.FDtype='Midsize Type 2b Detector'
else:
dat0=re.search(r'.+(\d{4}).+',line)
if dat0!=None:
self.myXEvent.FDtype=dat0.group(1)
else:
if line.rfind('fd_a1_rot')>-1:
self.myXEvent.FDtype='4700' #'4700'=large FD=fd_a1_rot ; '4800'=small FD; 'Pixium 3040 CV'=large FD
elif line.rfind('fd_c2')>-1:
self.myXEvent.FDtype='4800' #'4700'=large FD=fd_a1_rot ; '4800'=small FD; 'Pixium 3040 CV'=large FD
else:
self.myXEvent.FDtype='n.a.'
self.no_plane_B_found=0;
#Stand Type
if (line.find('System Type')>-1 )and (line.find('Factory')==-1 ):
dat0=re.search(r'.+System Type\s*:\s*([Ceiling Mounted,Floor Mounted,Biplane,Robot Stand,Multipurpose,EAS Floor Mounted]+).*',line)
self.myXEvent.SystemType=dat0.group(1)
if (line.find('systype')>-1 )and (line.find('Factory')==-1 ):
dat0=re.search(r'.systype\s*:\s*([masceilingmounted,masfloormounted,masbiplane,masrobot,masmultipurpose,EAS Floor Mounted]+).*',line)
if dat0!=None:
tmp_systype=dat0.group(1)
if tmp_systype=='masbiplane':
self.myXEvent.SystemType='Biplane'
elif tmp_systype=='masceilingmounted':
self.myXEvent.SystemType='Ceiling Mounted'
elif tmp_systype=='masfloormounted':
self.myXEvent.SystemType='Floor Mounted'
elif tmp_systype=='masrobot':
self.myXEvent.SystemType='Robot Stand'
elif tmp_systype=='masmultipurpose':
self.myXEvent.SystemType='Multipurpose'
else:
self.myXEvent.SystemType='n.a.'
#System SN
if (line.find('system ident')>-1 or line.find('syngo_system_ident')>-1):
dat0=re.search(r'.+:\s*(\d+).*',line)
self.myXEvent.SN=int(dat0.group(1))
#------SID Factor & Interventional Reference Point---------
if(self.myXEvent.SystemType=='Ceiling Mounted'):
self.myXEvent.SID_factor=63.5*63.5/100.0/100.0;
self.myXEvent.IR=63.5; #Interventional reference point
if(self.myXEvent.SystemType=='Floor Mounted'):
self.myXEvent.SID_factor=60.*60./100.0/100.0;
self.myXEvent.IR=60.0; #Interventional reference point
if(self.myXEvent.SystemType=='Robot Stand'):
self.myXEvent.SID_factor=63.5*63.5/100.0/100.0;
self.myXEvent.IR=63.5; #Interventional reference point
if(self.myXEvent.SystemType=='Multipurpose'):
self.myXEvent.SID_factor=63.5*63.5/100.0/100.0;
self.myXEvent.IR=63.5; #Interventional reference point
if(self.myXEvent.SystemType=='EAS Floor Mounted'):
self.myXEvent.SID_factor=63.5*63.5/100.0/100.0;
self.myXEvent.IR=63.5; #Interventional reference point
if(self.myXEvent.SystemType=='Biplane'): #nur in Ebene B; A identisch zu Floor Stand
if(self.plane=='A'):
self.myXEvent.IR=60.0
self.myXEvent.SID_factor=60.0*60.0/100.0/100.0
else: #plane=='B'
self.myXEvent.IR=60.0; #default
self.myXEvent.SID_factor=60.0*60.0/100.0/100.0
#Line resistance
if line.find('Line Resistance ')>-1:
dat0=re.search(r'.+:\s*(\d+).*',line)
self.line_resistance=dat0.group(1)
#Line voltage
if line.find('Line Voltage ')>-1 and line.find('Present ')==-1:
dat0=re.search(r'.+:\s*(\d+).*',line)
self.line_voltage=dat0.group(1)
if done_licences==False:
for key in self.key_str :
if line.find(key)>-1:
self.key_status[key]=line.split(':')[-1].strip()
if self.myXEvent.SystemType!='Biplane':
self.no_plane_B_found=1
return
#------------------------------------------------------------------
def get_dose_efficiency_nominal(self): #dient zur Datum-Auswahl
#Sollwerte Dosisausbeute
if self.myXEvent.tubetype == 0: #Megalix Cat
if self.myXEvent.numFoken == 2:
soll=110
else:
soll=127
if self.myXEvent.tubetype == 1: #Megalix Cat+
if self.myXEvent.numFoken == 2:
soll=121
else:
soll=141
if self.myXEvent.tubetype == 2: #Gigalix
if self.myXEvent.numFoken == 2:
soll=126
else:
soll=136
return soll
#------------------------------------------------------------------
#------------------------------------------------------------------
def read_data(self): #VC14 Todo: other SW Versions
self.myXEvent.BE_F1[0]=0;
self.myXEvent.BE_F2[0]=0;
self.myXEvent.BE_FG[0]=0;
patient_number=0
new_pat=1 #Annahme, dass Log immer mit neuem Patienten anfaengt
new_day=0
old_time=0
self.usedSWs=[]
self.ACQ_set={}
self.FL_set={}
self.RM_set={}
self.ALT_set={}
self.ACQ_ogps=set([])
self.FL_ogps=set([])
self.RM_ogps=set([])
self.ALT_ogps=set([])
self.acq_params=[]
self.fl_params=[]
self.rm_params=[]
self.alt_params=[]
self.ogp_diff={}
self.ogp_new={}
self.ogp_del={}
self.ogp_change={}
self.Leo=set([])
self.Leo_SW=set([])
self.pat_position=[]
try: #test id envlog data is available and convert string to datetime objeckt list
envtime2d= [dateutil.parser.parse(x) for x in self.envtime2]
except:
envtime2d=[]
global total_events
global Datum_array
global Startzeit
global Time
global Tag
global Jahr
global Monat
global Sekunden
global Minuten
global Stunden
global alternative_acquisition
global TIME
global event_dates
total_events = []
alternative_acquisition = []
Datum_array = []
Startzeit = []
Time = []
Stunden = []
Minuten = []
Sekunden = []
Tag = []
Monat = []
Jahr = []
TIME = []
event_dates =[]
global preview_cran #preview-Werte
global preview_rao
global preview_SID
global preview_review #vergleicht preview und review-Werte von cran/rao/SID; Wert=0 falls preview und review bei allen drei identisch, ansonsten Wert=1
global prev_table_pos
global rev_table_pos
global review_SID #review-Werte
global review_rao
global review_cran
global scu_rao
global scu_cran
global scu_sid
global scu_time
global scu_gantry_rot
global scu_base_rot
global scu_gantry_long
global scu_camera_rot
global scu_collim_rot
global scu_table_tilt
global scu_table_rot
global scu_table_cradle
global scu_T1
global scu_T2
global scu_T3
global scu_carm_rot
global scu_carm_orb
global alpha_orb
global xray_vec_z
global alpha_orb_rob
global alpha_xray_robot
global scu_224_time
global scu_224_robot_angles
global time_between_xray
global vertical_tube_time
global all_HU #count HU also during service x-ray (Review and Preview)
global all_HU_time
prev_table_pos=np.array([0,0,0])
rev_table_pos=np.array([0,0,0])
preview_cran = []
preview_rao = []
preview_SID = []
preview_review = []
review_SID = []
review_cran = []
review_rao = []
all_HU =[]
all_HU_time=[]
scu_rao=[]
scu_cran=[]
scu_camera_rot=[]
scu_collim_rot=[]
scu_sid=[]
scu_time=[]
scu_table_tilt=[]
scu_table_rot=[]
scu_table_cradle=[]
scu_gantry_rot=[]
scu_base_rot=[]
scu_gantry_long=[]
scu_T1=[]
scu_T2=[]
scu_T3=[]
scu_carm_rot=[]
scu_carm_orb=[]
alpha_orb=[]
xray_vec_z=[]
alpha_orb_rob=[]
alpha_xray_robot=[] #for debug
scu_224_time=[]
scu_224_robot_angles=[]
time_between_xray=[]
vertical_tube_time=0
#Arcing
global arcing_time
global num_arcing
global num_arcing_tot
global arcing_time_global
global arcing_type_global
global arcing_kV_global
global arcing_mA_global
global arcing_ms_global
global arcing_foc_global
global arcing_frame_global
global arcing_ogp_global
global arcing_HU_global
global arcing_idx_global
global num_T1_arcing
global T1_arcing_time
global T1_arcing_time_global
global num_grid
global grid_time_global
global num_grid_tot
global transfer_dynamics
arcing_time = []
arcing_type = []
arcing_frame = []
num_arcing = []
num_arcing_tot = 0 #all arcings, even if event is dropped due to format errors
arcing_time_global = []
arcing_type_global = []
arcing_kV_global = []
arcing_mA_global = []
arcing_ms_global = []
arcing_foc_global = []
arcing_frame_global =[]
arcing_ogp_global =[]
arcing_HU_global =[]
arcing_idx_global =[]
num_T1_arcing = []
T1_arcing_time = []
T1_arcing_time_global = []
transfer_dynamics=[]
grid_time = []
grid_type = []
grid_frame = []
num_grid = []
num_grid_tot = 0 #all arcings, even if event is dropped due to format errors
grid_time_global = []
grid_type_global = []
#Statische Lernparameter
global L1
global L2
global S1
global S2
global M1
global M2
global L3
global M3
global S3
global Lernparameter_datum
L1 = []
L2 = []
S1 = []
S2 = []
M1 = []
M2 = []
M3 = []
S3 = []
L3 = []
Lernparameter_datum = []
#Errors & Warnings
global rac_op
global power_on
global power_off
global cooling_state
global cooling_time
global cooling_ontime
global service_start
global service_stop
global fingerfilter_in
global filter_reset
global TUBE_ADJUST
global NO_XRAY
global TUBE_CONDITIONING
global LESS_FRAMES
global PUN_ERR
global MMT_warning #possible wrong cabeling of MMT at Gigalix (coincidence of Warn_5112_WARNING_OVERLOAD and Info_5113_INFO_ITACT_SHUNT
global bypass_fl
global generator_type
global generator
global FPGA_F2_Err
PUN_ERR={}
#remark: arcing (Warn_5016_SCAN_WARNING 0x5016) wird auch separat behandelt
PUN_ERR['Info_9192_MICRO_FOCUS_NOT_FUNCTIONAL']=[]
PUN_ERR['Info_9191_SMALL_FOCUS_NOT_FUNCTIONAL']=[]
PUN_ERR['Info_9190_LARGE_FOCUS_NOT_FUNCTIONAL']=[]
PUN_ERR['Info_9188_GRID_NOT_FUNCTIONAL']=[]
PUN_ERR['Info_5113_INFO_ITACT_SHUNT']=[]
PUN_ERR['Warn_9170_IT_TOLERANZ_WARNING']=[]
PUN_ERR['Warn_5081_FIL_WARNING']=[]
PUN_ERR['Warn_5112_WARNING_OVERLOAD']=[]
PUN_ERR['Warn_5115_TUBE_READJUST']=[]
PUN_ERR['Warn_9131_TUBE_TEMPERATURE']=[]
PUN_ERR['Warn_9132_TUBE_TEMPERATURE_2']=[]
PUN_ERR['Warn_9170_IT_TOLERANZ_WARNING']=[]
PUN_ERR['Warn_5150_ANODE_FREQ_WARNING']=[]
PUN_ERR['Warn_5061_TEMPERATURE_WARNING_RAC']=[]
PUN_ERR['Warn_5016_SCAN_WARNING']=[]
PUN_ERR['Err_5000_P_kV']=[]
PUN_ERR['Err_5001_N_kV']=[]
PUN_ERR['Err_5002_DELTA_KV']=[]
PUN_ERR['Err_5003_ILOAD']=[]
PUN_ERR['Err_5004_HVT_PREASURE']=[]
PUN_ERR['Err_5005_POWER']=[]
PUN_ERR['Err_5008_D600']=[]
PUN_ERR['Err_5009_D601_DL']=[]
PUN_ERR['Err_5010_IMAX_INVERTER_1']=[]
PUN_ERR['Err_5011_IMAX_INVERTER_2']=[]
PUN_ERR['Err_5012_UBMAX_INVERTER_1']=[]
PUN_ERR['Err_5013_UBMAX_INVERTER_2']=[]
PUN_ERR['Err_5014_TEMPERATURE_HVT']=[]
PUN_ERR['Err_5015_XRAY_ON']=[]
PUN_ERR['Err_5017_UT_TOLERANZ']=[]
PUN_ERR['Err_5018_IT_TOLERANZ']=[]
PUN_ERR['Err_5019_OPERATOR']=[]
PUN_ERR['Err_5020_K1']=[]
PUN_ERR['Err_5021_K2']=[]
PUN_ERR['Err_5022_UDC']=[]
PUN_ERR['Err_5023_RAC_OP']=[]
PUN_ERR['Err_5024_XC_INIT']=[]
PUN_ERR['Err_5025_XC_INCONSISTENT']=[]
PUN_ERR['Err_5027_TUBE_LEARN']=[]
PUN_ERR['Err_5030_TEMP_INVERTER_1']=[]
PUN_ERR['Err_5031_TEMPERATURE_INVERTER_2']=[]
PUN_ERR['Err_5032_TEMPERATURE_WARNING_INVERTER_1']=[]
PUN_ERR['Err_5033_TEMPERATURE_WARNING_INVERTER_2']=[]
PUN_ERR['Err_5034_TEMPERATURE_WARNING_HVT']=[]
PUN_ERR['Err_5035_DOOR']=[]
PUN_ERR['Err_5036_D601']=[]
PUN_ERR['Err_5037_INVERTER_1']=[]
PUN_ERR['Err_5038_INVERTER_2']=[]
PUN_ERR['Err_5041_POWER_INVERTER_1']=[]
PUN_ERR['Err_5042_POWER_INVERTER_2']=[]
PUN_ERR['Err_5043_LIFE_CHECK_RAC']=[]
PUN_ERR['Err_5044_LIFE_CHECK_FIL']=[]
PUN_ERR['Err_5047_IMAX']=[]
PUN_ERR['Err_5048_INV']=[]
PUN_ERR['Err_5056_D600_S5']=[]
PUN_ERR['Err_5059_TEMPERATURE_AMB']=[]
PUN_ERR['Err_5062_ERROR_TEMPERATURE_RAC']=[]
PUN_ERR['Err_5063_UDC_WARNING']=[]
PUN_ERR['Err_5064_UDC_WARNING_EX']=[]
PUN_ERR['Err_5065_STOP']=[]
PUN_ERR['Err_5066_T_DELTA_INVERTER']=[]
PUN_ERR['Err_5067_T_DELTA_L']=[]
PUN_ERR['Err_5070_GEN_D601_HW_RAC']=[]
PUN_ERR['Err_5071_D470_LARGE_FOCUS_MISSING']=[]
PUN_ERR['Err_5072_D470_SMALL_FOCUS_MISSING']=[]
PUN_ERR['Err_5073_D470_MICRO_FOCUS_MISSING']=[]
PUN_ERR['Err_5074_D470_LARGE']=[]
PUN_ERR['Err_5075_D470_SMALL']=[]
PUN_ERR['Err_5076_D470_MICRO']=[]
PUN_ERR['Err_5077_D601_FIL_UDC']=[]
PUN_ERR['Err_5079_D601_FIL_XRAY_ON']=[]
PUN_ERR['Err_5080_FIL_D601_D600']=[]
PUN_ERR['Err_5082_D470_EX_LARGE']=[]
PUN_ERR['Err_5083_D470_EX_SMALL']=[]
PUN_ERR['Err_5084_D470_EX_MICRO']=[]
PUN_ERR['Err_5085_RTC_FIL']=[]
PUN_ERR['Err_5089_HS']=[]
PUN_ERR['Err_5094_D115']=[]
PUN_ERR['Err_5097_GRID_HW_NOT_PLUGGED_IN']=[]
PUN_ERR['Err_5098_GIGALIX_LEAKAGE_CURRENT']=[]
PUN_ERR['Err_5099_GRID_NOT_READY']=[]
PUN_ERR['Err_509B_GRID_HV']=[]
PUN_ERR['Err_509C_GRID_OPEN_HV']=[]
PUN_ERR['Err_509D_GRID_SHORT_HV']=[]
PUN_ERR['Err_509E_GRID_BROKEN_HV']=[]
PUN_ERR['Err_509F_GRID_NOT_READY_ARC_RECOVER']=[]
PUN_ERR['Err_50A0_GRID_NO_HV']=[]
PUN_ERR['Err_50A1_GRID_OPEN_NO_HV']=[]
PUN_ERR['Err_50A2_GRID_SHORT_NO_HV']=[]
PUN_ERR['Err_50A3_GRID_BROKEN_NO_HV']=[]
PUN_ERR['Err_50A4_GRID_ISR_CHECK']=[]
PUN_ERR['Err_50AF_CAN_GUARDING']=[]
PUN_ERR['Err_50B8_CAN_GUARDING']=[]
PUN_ERR['Err_50B9_CAN_GUARDING']=[]
PUN_ERR['Err_5101_VCC']=[]
PUN_ERR['Err_5103_D601_RAC_UDC']=[]
PUN_ERR['Err_5104_D601_24V']=[]
PUN_ERR['Err_5114_HVT']=[]
PUN_ERR['Err_5117_GEN_D601_HW_FIL']=[]
PUN_ERR['Err_5120_UT_MAX_FPGA']=[]
PUN_ERR['Err_5124_IT_OFFSET_NOT_JUST']=[]
PUN_ERR['Err_5170_SERLINK']=[]
PUN_ERR['Err_6028_GENERATOR_NOT_ADJUSTED']=[]
PUN_ERR['Err_6029_DUMMY_RAC']=[]
PUN_ERR['Err_6045_RAC_NOT_STARTED']=[]
PUN_ERR['Err_6046_FIL_NOT_STARTED']=[]
PUN_ERR['Err_6050_TIM_FW']=[]
PUN_ERR['Err_6051_HW_FW']=[]
PUN_ERR['Err_6052_DUMMY_FW']=[]
PUN_ERR['Err_6053_GEN_FW']=[]
PUN_ERR['Err_6057_D601_RAC_CPU_CRC']=[]
PUN_ERR['Err_6058_D601_FIL_CPU_CRC']=[]
PUN_ERR['Err_6069_GEN_D601_FW_FIL']=[]
PUN_ERR['Err_6086_D601_FIL_CRC_WARN']=[]
PUN_ERR['Err_6096_UNK_ERROR_DUMMY']=[]
PUN_ERR['Err_6097_UNK_ERROR_GEN']=[]
PUN_ERR['Err_6098_UNK_ERROR_HW']=[]
PUN_ERR['Err_6099_UNK_ERROR_TIM']=[]
PUN_ERR['Err_6100_GEN_D601_FW_RAC']=[]
PUN_ERR['Err_6105_D601_RAC_CRC_WARN']=[]
PUN_ERR['Err_6111']=[] # FIRMWARE (A100) Unknown user driver layer error code </i> <sup>CSA</sup>
PUN_ERR['Err_6200_CRC_ERROR_USERFW']=[]
PUN_ERR['Err_7110_CAN_DATA_(A100)_normal_limits']=[]
PUN_ERR['Err_7111_CAN_DATA_(A100)_reduced_limits']=[]
PUN_ERR['Err_8113_CAN_DATA']=[]
PUN_ERR['Err_8115_CAN_DATA']=[]
PUN_ERR['Err_8117_CAN_DATA']=[]
PUN_ERR['Err_8118_CAN_NOT_ALLOWED']=[]
PUN_ERR['Err_811A_CAN_DATA']=[]
PUN_ERR['Err_811B_CAN_NOT_ALLOWED']=[]
PUN_ERR['Err_811C_CAN_NOT_ALLOWED']=[]
PUN_ERR['Err_9110_DOORSWITCH_OPEN']=[]
PUN_ERR['Err_9121_TUBE']=[]
PUN_ERR['Err_9122_TUBE_2_OIL_PRESSURE_SWITCH']=[]
PUN_ERR['Err_9142_GIGALIX_S3']=[]
PUN_ERR['Err_9148_GIGALIX_DELTA_TEMP']=[]
PUN_ERR['Err_9162_GIGALIX_CABLE']=[]
PUN_ERR['Err_9180_RAC_NOT_FUNCTIONAL']=[]
PUN_ERR['Err_9191_SMALL_FOCUS_NOT_FUNCTIONAL']=[]
PUN_ERR['Err_9198_LARGE_FOCUS_BLOCKED']=[]
PUN_ERR['Err_9199_SMALL_FOCUS_BLOCKED']=[]
PUN_ERR['Err_919A_MICRO_FOCUS_BLOCKED']=[]
PUN_ERR['Err_920F_CAN_NOT_ALLOWED']=[]
MMT_warning=[]
generator_type=[]
generator=[]
#Info_9192_MICRO_FOCUS_NOT_FUNCTIONAL (A100) CSA
#Info_9191_SMALL_FOCUS_NOT_FUNCTIONAL (A100) CSA
#Info_9190_LARGE_FOCUS_NOT_FUNCTIONAL (A100) CSA
#Info_9188_GRID_NOT_FUNCTIONAL (A100) CSA
#Info_5113_INFO_ITACT_SHUNT CSA
#Info_9180_RAC_NOT_FUNCTIONAL (A100) Too many errors occurred in the rotating anode mode CSA
#Warn_9170_IT_TOLERANZ_WARNING (A100) Tube current tolerance warning RELEVANT
#Warn_5081_FIL_WARNING (A100) Warning from D601 filament control
#Warn_5112_WARNING_OVERLOAD TUBE (A100) RELEVANT
#Warn_5115_TUBE_READJUST (A100) Tube adjustment necessary RELEVANT
#Warn_9131_TUBE_TEMPERATURE (A100) Temperature switch of the X-ray tube unit signals over-temperature RELEVANT
#Warn_9132_TUBE_TEMPERATURE_2 (A100) Temperature switch of the X-ray tube signals over-temperature RELEVANT
#Warn_5150_ANODE_FREQ_WARNING (A100) Actual anode frequency below threshold CSA
#Warn_9170_IT_TOLERANZ_WARNING (A100) Tube current tolerance warning RELEVANT
#Warn_5061_TEMPERATURE_WARNING_RAC (A100) D115 warning temperature monitoring has responded CSA
#Err_5000_P_kV (A100) +KVmax </i> <sup>RELEVANT</sup>
#Err_5001_N_kV (A100) -KVmax </i> <sup>RELEVANT</sup>
#Err_5002_DELTA_KV (A100) +KV < > -KV </i> <sup>RELEVANT</sup>
#Err_5003_ILOAD (A100) Over current D510 </i> <sup>RELEVANT</sup>
#Err_5004_HVT_PREASURE (A100) Overpressure in the High Voltage Transformer </i> <sup>RELEVANT</sup>
#Err_5005_POWER (A100) Power Supply Volatge out of tolerance </i> <sup>RELEVANT</sup>
#Err_5008_D600 (A100) Hardware error D600 </i> <sup>RELEVANT</sup>
#Err_5009_D601_DL (A100) Download error D601 </i> <sup>RELEVANT</sup>
#Err_5010_IMAX_INVERTER_1 (A100) Imax was detected on D510_1 </i> <sup>RELEVANT</sup>
#Err_5011_IMAX_INVERTER_2 (A100) Imax was detected on D510_2 </i> <sup>RELEVANT</sup>
#Err_5012_UBMAX_INVERTER_1 (A100) Overvoltage (IGBTs) Inverter D510_1 </i> <sup>RELEVANT</sup>
#Err_5013_UBMAX_INVERTER_2 (A100) Overvoltage (IGBTs) Inverter D510_2 </i> <sup>RELEVANT</sup>
#Err_5014_TEMPERATURE_HVT (A100) Temperature switch High Voltage Transformer active </i> <sup>RELEVANT</sup>
#Err_5015_XRAY_ON (A100) No High Voltage </i> <sup>RELEVANT</sup>
#Err_5017_UT_TOLERANZ (A100) High Voltage tolerance error </i> <sup>RELEVANT</sup>
#Err_5018_IT_TOLERANZ (A100) Tube current tolerance error </i> <sup>RELEVANT</sup>
#Err_5019_OPERATOR (A100) Adjustment interrupted by the operator </i> <sup>CSA</sup>
#Err_5020_K1 (A100) Problem with the K1 main contactor </i> <sup>RELEVANT</sup>
#Err_5021_K2 (A100) Problem with the K2 Charge contactor </i> <sup>RELEVANT</sup>
#Err_5022_UDC (A100) Intermediate Circuit Voltage error </i> <sup>RELEVANT</sup>
#Err_5023_RAC_OP (A100) Rotating Anode Circuit error </i> <sup>RELEVANT</sup>
#Err_5024_XC_INIT Hardware radiation request during initialization </i> <sup>RELEVANT</sup>
#Err_5025_XC_INCONSISTENT SWR Radiation request not equal to CAN request </i> <sup>RELEVANT</sup>
#Err_5027_TUBE_LEARN (A100) Tube Adjustment error </i> <sup>RELEVANT</sup>
#Err_5030_TEMP_INVERTER_1 (A100) Temperature switch Inverter D510_1 active </i> <sup>RELEVANT</sup>
#Err_5031_TEMPERATURE_INVERTER_2 (A100) Temperature switch Inverter D510_2 active </i> <sup>RELEVANT</sup>
#Err_5032_TEMPERATURE_WARNING_INVERTER_1 (A100) D510_1 temperature monitoring has responded </i> <sup>CSA</sup>
#Err_5033_TEMPERATURE_WARNING_INVERTER_2 (A100) D510_2 temperature monitoring has responded </i> <sup>CSA</sup>
#Err_5034_TEMPERATURE_WARNING_HVT (A100) High Voltage Transformer </i> <sup>CSA</sup>
#Err_5035_DOOR (A100) Door signal active </i> <sup>RELEVANT</sup>
#Err_5036_D601 (A100) Error on D601 </i> <sup>RELEVANT</sup>
#Err_5037_INVERTER_1 (A100) Error on D510_1 </i> <sup>RELEVANT</sup>
#Err_5038_INVERTER_2 (A100) Error on D510_2 </i> <sup>RELEVANT</sup>
#Err_5041_POWER_INVERTER_1 (A100) Power supply voltage error +15V on D510_1 </i> <sup>RELEVANT</sup>
#Err_5042_POWER_INVERTER_2 (A100) Power supply voltage error +15V on D510_2 </i> <sup>RELEVANT</sup>
#Err_5043_LIFE_CHECK_RAC (A100) Live check between D600 and D601 RAC CPU failed </i> <sup>RELEVANT</sup>
#Err_5044_LIFE_CHECK_FIL (A100) Live check between D600 and D601 FIL CPU failed </i> <sup>RELEVANT</sup>
#Err_5047_IMAX (A100) Over current D510 </i> <sup>RELEVANT</sup>
#Err_5048_INV (A100) Error on D510_1 or D510_2 </i> <sup>RELEVANT</sup>
#Err_5056_D600_S5 (A100) Switch D600.S5 set incorrectly </i> <sup>RELEVANT</sup>
#Err_5059_TEMPERATURE_AMB (A100) D600 max. temperature monitoring has responded </i> <sup>RELEVANT</sup>
#Err_5062_ERROR_TEMPERATURE_RAC (A100) D115 max. temperature monitoring has responded </i> <sup>RELEVANT</sup>
#Err_5063_UDC_WARNING (A100) Intermediate circuit voltage out of range during standby </i> <sup>CSA</sup>
#Err_5064_UDC_WARNING_EX (A100) Intermediate circuit voltage out of range during exposure </i> <sup>CSA</sup>
#Err_5065_STOP (A100) D601 stop signal is active </i> <sup>RELEVANT</sup>
#Err_5066_T_DELTA_INVERTER_ (A100) Temperature difference between Inverter D510_1 and D510_2 </i> <sup>RELEVANT</sup>
#Err_5067_T_DELTA_L (A100) Temperature difference between Coil L1 and L2 </i> <sup>RELEVANT</sup>
#Err_5070_GEN_D601_HW_RAC (A100) Hardware error on D601 detected in anode control </i> <sup>RELEVANT</sup>
#Err_5071_D470_LARGE_FOCUS_MISSING (A100) Control of the D470_2 (large focus) defective </i> <sup>RELEVANT</sup>
#Err_5072_D470_SMALL_FOCUS_MISSING (A100) Control of the D470_1 (small focus) defective </i> <sup>RELEVANT</sup>
#Err_5073_D470_MICRO_FOCUS_MISSING (A100) Control of the D470_3 (micro focus) defective </i> <sup>RELEVANT</sup>
#Err_5074_D470_LARGE (A100) D470_2 Large focus defective </i> <sup>RELEVANT</sup>
#Err_5075_D470_SMALL (A100) D470_1 Small focus defective </i> <sup>RELEVANT</sup>
#Err_5076_D470_MICRO (A100) D470_3 Micro focus defective </i> <sup>RELEVANT</sup>
#Err_5077_D601_FIL_UDC (A100) Intermediate circuit voltage error detected on D601 </i> <sup>RELEVANT</sup>
#Err_5079_D601_FIL_XRAY_ON (A100) D601 detected an active radiation signal outside of the exposure cycle </i> <sup>RELEVANT</sup>
#Err_5080_FIL_D601_D600 (A100) D601 FIL CPU has detected an invalid signal from the D600 </i> <sup>RELEVANT</sup>
#Err_5082_D470_EX_LARGE (A100) D470_2 Large Focus signaled an error during operation </i> <sup>RELEVANT</sup>
#Err_5083_D470_EX_SMALL (A100) D470_1 Small focus signaled an error during operation </i> <sup>RELEVANT</sup>
#Err_5084_D470_EX_MICRO (A100) D470_3 The micro focus signaled an error during operation </i> <sup>RELEVANT</sup>
#Err_5085_RTC_FIL (A100) The radiation request signal was active during initialization </i> <sup>RELEVANT</sup>
#Err_5089_HS (A100) High voltage error </i> <sup>RELEVANT</sup>
#Err_5094_D115 (A100) Error was detected on the D115 </i> <sup>RELEVANT</sup>
#Err_5097_GRID_HW_NOT_PLUGGED_IN (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_5098_GIGALIX_LEAKAGE_CURRENT (A100G) Tube current between XRAY pulses too high </i> <sup>RELEVANT</sup>
#Err_5099_GRID_NOT_READY (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_509B_GRID_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_509C_GRID_OPEN_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_509D_GRID_SHORT_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_509E_GRID_BROKEN_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_509F_GRID_NOT_READY_ARC_RECOVER (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_50A0_GRID_NO_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_50A1_GRID_OPEN_NO_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_50A2_GRID_SHORT_NO_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_50A3_GRID_BROKEN_NO_HV (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_50A4_GRID_ISR_CHECK (A100G) Error within grid control </i> <sup>RELEVANT</sup>
#Err_50AF_CAN_GUARDING (A100) Problems with CAN Guarding in the standby mode </i> <sup>CSA</sup>
#Err_50B8 CAN_GUARDING (A100) Problems with CAN Guarding during exposure </i> <sup>RELEVANT</sup>
#Err_50B9_CAN_GUARDING (A100) CAN communication dropped out during exposure / fluoroscopy </i> <sup>RELEVANT</sup>
#Err_5101_VCC Power supply voltage error on the D601 and D600 (A100 Plus/A100G only) </i> <sup>RELEVANT</sup>
#Err_5103_D601_RAC_UDC (A100) Intermediate circuit voltage error detected on D601 </i> <sup>RELEVANT</sup>
#Err_5104_D601_24V (A100) 24V Power supply voltage error on the D601 </i> <sup>RELEVANT</sup>
#Err_5114_HVT (A100) High Voltage Transformer error </i> <sup>RELEVANT</sup>
#Err_5117_GEN_D601_HW_FIL (A100) Hardware error on D601 detected in filament control </i> <sup>RELEVANT</sup>
#Err_5120_UT_MAX_FPGA (A100G/Plus) FPGA detects tube voltage too high </i> <sup>RELEVANT</sup>
#Err_5124_IT_OFFSET_NOT_JUST (A100G/A100 Plus) Error during auto adjust of IT-actual </i> <sup>RELEVANT</sup>
#Err_5170_SERLINK (A100G/Plus) SLINK Communication Error between D600 and D601 </i> <sup>RELEVANT</sup>
#Err_6028_GENERATOR_NOT_ADJUSTED (A100) Inverter Adjustment missing </i> <sup>RELEVANT</sup>
#Err_6029_DUMMY_RAC (A100) Configuration Error on D600 </i> <sup>RELEVANT</sup>
#Err_6045_RAC_NOT_STARTED (A100) RAC CPU did not start </i> <sup>RELEVANT</sup>
#Err_6046_FIL_NOT_STARTED (A100) The FIL CPU did not start </i> <sup>RELEVANT</sup>
#Err_6050_TIM_FW (A100) Internal firmware error of the timer machine </i> <sup>RELEVANT</sup>
#Err_6051_HW_FW (A100) Internal firmware error of the driver layer hardware </i> <sup>RELEVANT</sup>
#Err_6052_DUMMY_FW (A100) Internal firmware error of the dummy driver </i> <sup>RELEVANT</sup>
#Err_6053_GEN_FW (A100) Internal firmware error of the generator machine </i> <sup>RELEVANT</sup>
#Err_6057_D601_RAC_CPU_CRC (A100) Checksum error of the RAC CPU D601 </i> <sup>CSA</sup>
#Err_6058_D601_FIL_CPU_CRC (A100) Checksum error of the FIL CPU D601 </i> <sup>CSA</sup>
#Err_6069_GEN_D601_FW_FIL (A100) D601 FIL CPU firmware error </i> <sup>RELEVANT</sup>
#Err_6086_D601_FIL_CRC_WARN (A100) FIL CPU Firmware checksum error </i> <sup>CSA</sup>
#Err_6096_UNK_ERROR_DUMMY (A100) </i> <sup>RELEVANT</sup>
#Err_6097_UNK_ERROR_GEN (A100) Unknown generator driver layer firmware error code </i> <sup>RELEVANT</sup>
#Err_6098_UNK_ERROR_HW (A100) Unknown hardware driver layer error code </i> <sup>RELEVANT</sup>
#Err_6099_UNK_ERROR_TIM (A100) Unknown machine timer code error </i> <sup>RELEVANT</sup>
#Err_6100_GEN_D601_FW_RAC (A100) Firmware error of the D601 RAC CPU </i> <sup>RELEVANT</sup>
#Err_6105_D601_RAC_CRC_WARN (A100) RAC CPU Firmware checksum error </i> <sup>RELEVANT</sup>
#Err_6111 FIRMWARE (A100) Unknown user driver layer error code </i> <sup>CSA</sup>
#Err_6200_CRC_ERROR_USERFW (A100) Boot firmware error message, no user software available </i> <sup>RELEVANT</sup>
#Err_7110 CAN_DATA (A100) Generator signals normal limit values </I>
#Err_7111 CAN_DATA (A100) Generator signals reduced limit values </I>
#Err_8113 CAN_DATA (A100) Required focus does not exist for the X-ray tube </i> <sup>RELEVANT</sup>
#Err_8118 CAN_NOT_ALLOWED (A100) An attempt was made to trigger an exposure without a preceding data telegram (kV / mA) </i> <sup>RELEVANT</sup>
#Err_811A CAN_DATA (A100) The tube data table is invalid </i> <sup>RELEVANT</sup>
#Err_811B_CAN_NOT_ALLOWED (A100) The transferred line voltage is greater than 480V </i> <sup>RELEVANT</sup>
#Err_811C CAN_NOT_ALLOWED (A100) The transferred internal line resistance is greater than 260 mOhm </i> <sup>RELEVANT</sup>
#Err_9110 DOORSWITCH_OPEN (A100) Generator detects an open door contact </i> <sup>RELEVANT</sup>
#Err_9121_TUBE (A100) Oil pressure switch of X-Ray tube active </i> <sup>RELEVANT</sup>
#Err_9122_TUBE_2 (A100) Oil pressure switch of X-Ray tube active </i> <sup>RELEVANT</sup>
#Err_9138_RAC_OP (A100) Error during RAC operation with OPTITOP </i> <sup>RELEVANT</sup>
#Err_9142_GIGALIX_S3 (A100G) Temperature switch S3 of Gigalix tube active </i> <sup>RELEVANT</sup>
#Err_9148_GIGALIX_DELTA_TEMP (A100G) Temperature difference of Gigalix tube T0 and T1 too high </i> <sup>RELEVANT</sup>
#Err_9162_GIGALIX_CABLE (A100G) Cable error of Gigalix tube </i> <sup>RELEVANT</sup>
#Err_9198 LARGE_FOCUS_BLOCKED (A100) </i> <sup>RELEVANT</sup>
#Err_9199 SMALL_FOCUS_BLOCKED (A100) </i> <sup>RELEVANT</sup>
#Err_919A MICRO_FOCUS_BLOCKED (A100) </i> <sup>RELEVANT</sup>
#Err_920F CAN_NOT_ALLOWED (A100) An adjustment was initiated in the normal mode </i> <sup>CSA</sup>
###-----AX_ANG-Erros and Warnings------
global ANG_ERR
ANG_ERR={}
ANG_ERR['\t4\tAX_ANG']=[]
ANG_ERR['\t21\tAX_ANG']=[]
ANG_ERR['\t51\tAX_ANG']=[]
ANG_ERR['\t50\tAX_ANG']=[]
ANG_ERR['\t53\tAX_ANG']=[]
ANG_ERR['\t60\tAX_ANG']=[]
ANG_ERR['212\tAX_ANG']=[]
#ANG_ERR['255\tAX_ANG']=[]
ANG_ERR['251\tAX_ANG']=[]
ANG_ERR['290\tAX_ANG']=[]
ANG_ERR['292\tAX_ANG']=[]
ANG_ERR['293\tAX_ANG']=[]
ANG_ERR['298\tAX_ANG']=[]
ANG_ERR['302\tAX_ANG']=[]
ANG_ERR['449\tAX_ANG']=[]
ANG_ERR['451\tAX_ANG']=[]
ANG_ERR['452\tAX_ANG']=[]
ANG_ERR['461\tAX_ANG']=[]
ANG_ERR['463\tAX_ANG']=[]
ANG_ERR['598\tAX_ANG']=[]
ANG_ERR['599\tAX_ANG']=[]
ANG_ERR['609\tAX_ANG']=[]
ANG_ERR['620\tAX_ANG']=[]
ANG_ERR['622\tAX_ANG']=[]
ANG_ERR['623\tAX_ANG']=[]
ANG_ERR['625\tAX_ANG']=[]
ANG_ERR['626\tAX_ANG']=[]
ANG_ERR['627\tAX_ANG']=[]
ANG_ERR['635\tAX_ANG']=[]
ANG_ERR['640\tAX_ANG']=[]
ANG_ERR['\t645\tAX_ANG']=[]
ANG_ERR['654\tAX_ANG']=[]
ANG_ERR['662\tAX_ANG']=[]
ANG_ERR['665\tAX_ANG']=[]
ANG_ERR['682\tAX_ANG']=[]
#AX_ANG: 4 : Diamentor dont stops at scene end
#AX_ANG: 21 : No CAN communication to PUN (SET)
#AX_ANG: 50 : High voltage active after pulse end
#AX_ANG: 51 : Problem of ANG, XRAY Signal
#AX_ANG: 53 : NO XRAY: try again 230
#AX_ANG: 60 : Timing problem of ANG
#AX_ANG: 212: XRAY aborted: Dose less than 5%
#AX_ANG: 213: Possibly wrong dose, CU Prefilter
#AX_ANG: 251: NEW VALUES REJECTED: call SC
#AX_ANG: 290: UNEXPECTED DATA, call SC
#AX_ANG: 292: UNEXPECTED DATA, call SC
#AX_ANG: 293: NEW VALUES REJECTED: call SC
#AX_ANG: 298: UNEXPECTED DATA: call SC
#AX_ANG: 302: DOOR OPEN? XRAY disabled
#AX_ANG: 449: TOO MUCH POWER CONSUMPTION - F12
#AX_ANG: 450: POWER SUPPLY VOLTAGE out of range
#AX_ANG: 451: FAN OF RTC out of order - Check RTC fan
#AX_ANG: 452: OVERTEMPERATURE in RTC
#AX_ANG: 461: NO XRAY, recovering - Fatal Error of the PUN
#AX_ANG: 463: NO XRAY: try again
#AX_ANG: 598: No skindose calculation possible
#AX_ANG: 599: NO XRAY, please wait
#AX_ANG: 609: Skindose adj. pulsed FL needed, SC
#AX_ANG: 620: Possibly wrong dose, call SC
#AX_ANG: 622: Skindose adj. cont FL needed, SC
#AX_ANG: 623: NO XRAY, Bypass Fluoro not possible
#AX_ANG: 625: Problem with DC, call Service
#AX_ANG: 626: NO XRAY, please wait
#AX_ANG: 627: No Xray, Shut down required
#AX_ANG: 635: PUN stays on reduced limits
#AX_ANG: 640: Improve FL-Image Quality by using High Contrast Fluoro
#AX_ANG: 645: wrong xray interrupt sequence
#AX_ANG: 654: Diamentor adjustm. needed, SC
#AX_ANG: 662: PUN cannot be configured by Angiomatic
#AX_ANG: 665: OVERTEMPERATURE in RTC, sensor 2
#AX_ANG: 682: Actual current higher than nominal current
#AX_ANG: 695: Tube temperature out of range, SC
global ANG_CUR_DEV
ANG_CUR_DEV=[]
#W 05-Mar-14 09:48:13 255 AX_ANG <I>ANG diagnostic info </I>
#Time: 5.3.2014, 09:48:13, Process: C:\AXIOM\Service\bin\Rep.exe_2020,
#Text: (05.03.2014 09:48:12) ANG-A SET: [00001]4.Pulse: Current:210.98mA, Nominal:249.46mA, allwd. deviation:15%
#--------------------------------------
TUBE_ADJUST=[]
NO_XRAY=[]
TUBE_CONDITIONING= []
LESS_FRAMES=[] #less frames than forecast (3D abortion?)
global FPGA_Error
FPGA_Error=[]
power_on=[]
power_off=[]
cooling_state=[]
cooling_time=[]
cooling_ontime=[]
service_start=[]
service_stop=[]
fingerfilter_in=[]
filter_reset=[]
bypass_fl=[]
#Program Numbers (-1 means 'not defined')
prog1F=-1
prog2F=-1
prog1A=-1
prog2A=-1
exist_p453=0
exist_453=0
exist_p391=0
exist_391=0
acu_exist=0
data_391=''
data_391p=''
rac_op=[]
acu_frames=0
frames_391=0
dap453=0
dose453=0
scenetime453=0
current453=0
old_index=''
max_iter_reached=False
actual_OGP='None'
actual_kV =0
actual_mA =0
actual_ms =0
actual_HU =0
actual_idx =0
actual_foc ='none'
actual_biplane=0
new_pat_position=0
temp_pat_skindose=0
temp_pat_dap=0
act_axis_mode={}
act_axis_resolution={}
for logfile in self.Auswahl:#eventlog_files:
if max_iter_reached==False:
tab=self.notebook.GetSelection()
if tab==2:
blubb=1
elif tab==3 or tab==1: #SNs
zf = zipfile.ZipFile(self.Auswahl_dict[logfile,'zipfile'])
print "lese file " + self.Auswahl_dict[logfile,'fullname']
try:
fp = zf.open(self.Auswahl_dict[logfile,'fullname'])
lines=fp.readlines()
fp.close()
except:
print 'error opening '+ self.Auswahl_dict[logfile,'fullname']
lines=''
else: #Standard
print "lese file " + logfile #jn#
f = open(logfile,'r')
lines=f.readlines()
for i in numpy.uint32(xrange(1,numpy.uint32(len(lines)))):
if(i==1) and logfile==self.Auswahl[0]:
new_day=1
print '.'
###################
#AX_REP (Get SW version:)
#e.g. VB11: 'W 18-Aug-09 06:27:18 6 AX_REP 0 AXIOM-Artis SW VB11M 060529 started as masbiplane from 12314019 '
#e.g. EAS W 28-Jan-13 08:49:18 6 AX_REP EAS SW VA10A 121116 started as not_applicable from XA161985
#dat22=re.search(r'.+(EAS|)\s*SW\s*V([A-Z0-9]+).* started as',lines[i])
#if(dat22!=None):
# tempSW=dat22.group(1)+'V'+dat22.group(2)
#
# if(self.myXEvent.SW==''): #erstes Logfile
# self.myXEvent.SW=tempSW
# else:
# if(tempSW!=self.myXEvent.SW):
# if not IcConsMode:
# print 'Error: change of SW in chosen eventlogs'
try:
current_SW=os.path.split(os.path.split(self.Auswahl_dict[logfile,'fullname'])[0])[0] #backup from folder name
except:
current_SW='n.a.'
filedate=self.GetFileDate(logfile)
for j in range(len(self.myXEvent.SW)): #get real SW version from axiom.caf
if filedate>=self.myXEvent.SW[j][1] :
current_SW=self.myXEvent.SW[j][0]
if current_SW not in self.usedSWs:
self.usedSWs.append(current_SW)
current_SW_short=current_SW.split('_')[0][0:-1]
if current_SW_short == 'VC14' or current_SW_short == 'VC20' or current_SW_short == 'VC21' or current_SW_short[:-1]=='VD1' or current_SW_short=='VA10' : #durch Abschneiden des letzten Buchstabens funkionieren alle VC14/(bisherigen)VC20 Versionen(VC14A, VC14B,...)
#Find '45 AX_SYC' (new patient) or 'new emergency patient'/'Syc creates Emergency Patient'
if(lines[i].rfind('Internal information')>-1 ):
line=lines[i+2]
i=i+2
if(lines[i].rfind('new patient')>-1 or lines[i].rfind('new emergency patient')>-1 or lines[i].rfind('Syc creates Emergency Patient')>-1):
new_pat=1
#Text: (19.08.2009 07:55:50) SYC SET: [00056] from SYC valid, new patient (PatPos 1, Exam 0)
dat2=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) SYC SET: \[0005.+PatPos\s*(\d)',line)
try:
thetimestr=dat2.group(4)+':'+dat2.group(5)+':'+dat2.group(6)+' '+dat2.group(1)+'.'+dat2.group(2)+'.'+dat2.group(3)
thetime=time.strptime(thetimestr,"%H:%M:%S %d.%m.%Y")
new_pat_time=time.mktime(thetime)
new_pat_position=dat2.group(7)
except:
dat2=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) SYC SET: \[0005',line)
thetimestr=dat2.group(4)+':'+dat2.group(5)+':'+dat2.group(6)+' '+dat2.group(1)+'.'+dat2.group(2)+'.'+dat2.group(3)
thetime=time.strptime(thetimestr,"%H:%M:%S %d.%m.%Y")
new_pat_time=time.mktime(thetime)
new_pat_position=0 #0 means unclear
if (lines[i].rfind('[0x9225]')>-1):
mat_PUNSW=re.search(r'.+[0x9225].+\((SW:.+HW:.{5})\)',lines[i])
if mat_PUNSW!=None:
#PUN SW
self.myXEvent.PUN_SW=mat_PUNSW.group(1)
else:
self.myXEvent.PUN_SW='n.a'
#SYC SET: [00056]: Find Program Number Dublets (p1,p2)
if(lines[i].rfind('SYC SET: [00056] from ECC_1 valid')>-1 ):
mat4=re.search(r'.+ select program, \(([0-9a-f]+),\s*([0-9a-f]+)',lines[i]);
if(mat4!=None):
if(int(mat4.group(1),16)>=20): #Fluoro
prog1F=int(mat4.group(1),16)
prog2F=int(mat4.group(2),16)
else:
prog1A=int(mat4.group(1),16)
prog2A=int(mat4.group(2),16)
#Search power on time stamps
#W 05-Nov-13 07:51:56 6 AX_REP Artis SW VD10C 130402 started as Artis_Q_Ceiling from XA109005
#Time: 13.9.2010, 05:02:48, Process: C:\AXIOM\service\bin\Rep.exe_1664
if lines[i].find('started as')>-1 and lines[i].find('AX_REP')>-1:
mat11=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
if mat11!=None:
power_on_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
if not IcConsMode:
print "power on: "+power_on_time
try:
dateutil.parser.parse(power_on_time)
power_on.append(power_on_time)
except:
print 'skipping event! Irregular date'
actual_OGP='None'
#Search power off time stamps
#W 21-May-13 03:22:02 13 AX_IVS POWER OFF ACTIVATED
#Time: 21.5.2013, 03:22:02, Process: C:\AXIOM\Service\bin\Rep.exe_1188,
#Text: (21.05.2013 03:22:02) IVS SET: CShutdownController::RequestLabShutdown
if lines[i].find('POWER OFF ACTIVATED')>-1 and lines[i].find('AX_IVS')>-1:
mat11=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
if mat11!=None:
power_off_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
if not IcConsMode:
print "power off: "+power_off_time
try:
dateutil.parser.parse(power_off_time)
power_off.append(power_off_time)
cooling_time_str=str(dateutil.parser.parse(power_off_time)+datetime.timedelta(minutes=20))
if len(cooling_state)>0:
if cooling_state[-1]==1:
idx1=bisect.bisect_left(envtime2d,dateutil.parser.parse(power_off_time) )
idx2=bisect.bisect_left(envtime2d,dateutil.parser.parse(cooling_time[-1]) )
cool_duration=idx1-idx2
cooling_ontime.append(cool_duration*60.) #in seconds
cooling_time.append(cooling_time_str)
cooling_state.append(-1)
if not IcConsMode:
print 'cooling plane '+self.plane+' off:'+cooling_time_str
except:
print 'skipping event! Irregular date'
#deviation:15%
if (lines[i].find('deviation:15%')>-1 and lines[i].find('ANG-'+self.plane)>-1):
uuu=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\)' ,lines[i])
if uuu!=None:
dev_time=datetime.datetime(int(uuu.group(3)),int(uuu.group(2)),int(uuu.group(1)),int(uuu.group(4)),int(uuu.group(5)),int(uuu.group(6)) )
ANG_CUR_DEV.append(dev_time)
#Search 'cooling on/off' time stamps (only Gigalix, >=VD10)
#W 13-Oct-14 09:08:37 37202 AX_PUD <I>Info_9152_GIGALIX_S0 (A100G) Cooling Unit S0 of Gigalix tube active </I>
#Time: 13.10.2014, 09:08:37, Process: C:\AXIOM\Service\bin\Rep.exe_1156,
#Text: Backlog (01.01.2010 01:01:41) ANG-A RESET: [0x9152]PL A100G (SW:VG03Q; HW:VG01C)
if lines[i].find('Info_9152_GIGALIX_S0')>-1:
mat11=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
if mat11!=None:
cool_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
if lines[i+2].find('ANG-'+self.plane+' RESET: [0x9152]')>-1:
if not IcConsMode:
print 'cooling plane '+self.plane+' off:'+cool_time
try:
dateutil.parser.parse(cool_time)
if len(cooling_state)>0:
if cooling_state[-1]==1:
idx1a=bisect.bisect_left(envtime2d,dateutil.parser.parse(cool_time) )
if idx1a==len(envtime2d):
idx1a-=1
idx1b=bisect.bisect_right(envtime2d,dateutil.parser.parse(cool_time) )
if idx1b==len(envtime2d):
idx1b-=1
if envtime2d[idx1a]-dateutil.parser.parse(cool_time)<envtime2d[idx1b]-dateutil.parser.parse(cool_time):
idx1=idx1a
else:
idx1=idx1b
idx2a=bisect.bisect_left(envtime2d,dateutil.parser.parse(cooling_time[-1]) )
if idx2a==len(envtime2d):
idx2a-=1
idx2b=bisect.bisect_right(envtime2d,dateutil.parser.parse(cooling_time[-1]) )
if idx2b==len(envtime2d):
idx2b-=1
if envtime2d[idx2a]-dateutil.parser.parse(cool_time)<envtime2d[idx2b]-dateutil.parser.parse(cool_time):
idx2=idx2a
else:
idx2=idx2b
cool_duration=idx1-idx2
cooling_ontime.append(cool_duration*60.) #in seconds
cooling_time.append(cool_time)
cooling_state.append(0)
except:
True
#print 'skipping cooling off event! Irregular date'
elif lines[i+2].find('ANG-'+self.plane+' SET: [0x9152]')>-1:
if not IcConsMode:
print 'cooling plane '+self.plane+' on:'+cool_time
try:
dateutil.parser.parse(cool_time)
cooling_time.append(cool_time)
cooling_state.append(1)
except:
True
#print 'skipping cooling on event! Irregular date'
else:
True #wrong plane
#Search service start/stop time stamps
#W 01-Oct-13 15:05:55 24 AX_REP Local Service Session started
if (lines[i].rfind('AX_REP')>-1 and lines[i].rfind('Local Service Session started')>-1):
mat11=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
if mat11!=None:
service_start_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
#print "service start: "+service_start_time
service_start.append(service_start_time)
#W 01-Oct-13 15:05:58 26 AX_REP Local Service Session stopped
if (lines[i].rfind('AX_REP')>-1 and lines[i].rfind('Local Service Session stopped')>-1):
mat11=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
if mat11!=None:
service_stop_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
#print "service stop: "+service_stop_time
service_stop.append(service_stop_time)
#fingerfilter (unclear A or B, for finger or for heart contour)
#Text: (21.02.2014 14:41:21) UAL SET: [00015]UserInput: 0x2ba,Data: 0x0400000000000000 (CanTelegramHandler,82)
if (lines[i].find('[00015]UserInput:')>-1 and lines[i].find('0x0400000000000000')>-1 and lines[i].find('0x412,Data:')>-1 and lines[i].find('(CanTelegramHandler,82)')>-1 ):
mat11=re.search(r'(\d+)\.(\d+)\.(\d+)\s* (\d+):(\d+):(\d+)',lines[i])
if mat11!=None:
fingerfilter_in_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
fingerfilter_in.append(fingerfilter_in_time)
#filter_reset
#Text: (21.02.2014 14:44:35) UAL SET: [00015]UserInput: 0x2ba,Data: 0x0002000000000000 (CanTelegramHandler,82)
if (lines[i].find('[00015]UserInput:')>-1 and lines[i].find('0x0200000000000000')>-1 and lines[i].find('0x412,Data:')>-1 and lines[i].find('(CanTelegramHandler,82)')>-1 ):
mat11=re.search(r'(\d+)\.(\d+)\.(\d+)\s*(\d+):(\d+):(\d+)',lines[i])
if mat11!=None:
filter_reset_time = mat11.group(3)+'-'+mat11.group(2)+'-'+mat11.group(1)+' '+mat11.group(4)+':'+mat11.group(5)+':'+mat11.group(6)
filter_reset.append(filter_reset_time)
#SCU 221
#-----
#W 07-Jul-10 07:58:31 221 AX_SCU <I>LOG: cran_a -0.1, rao_a 0.0, sid_a 120.05 </I>
#Time: 7.7.2010, 07:58:31, Process: C:\AXIOM\service\bin\Rep.exe_1816,
#Text: (07.07.2010 07:58:31) SCU SET: [00221]-1,-2 C3244,3240 B-11014 G9277 T7790,3315,-597 R1510 T6 S|0,no src
#Text: (18.02.2011 10:13:19) SCU SET: [00221]30,-25 C-6,0 B16 G-5 T9471,4396,-5 R0 T11 C-5 |0,no src
#Text: (17.11.2009 15:18:35) SCU SET: [00221]-8989,3024 C18013,19 B-9019 G0,-26051,5077,15032 T7932,9964,-72 R3023 T2 #zeego VC14
# (31.12.1997 19:01:15) SCU SET: [00221]-1,-19 C-7793,1222 B-7723 G6500 T7941,8894,-1744 R0|0,no src
#Text: (27.02.2013 17:29:15) SCU SET: [00221]-241,-6986 C9217,217 B-8986 GNIL,22424 T10600,-500,0 R0 T0 C0 S 11977|0,n
"""
#Floor VC13
W 11-Mar-14 13:45:25 221 AX_SCU <I>LOG: cran_a 0.3, rao_a 0.0, sid_a 111.2 </I>
Time: 11.3.2014, 13:45:25, Process: C:\AXIOM\service\bin\Rep.exe_1100,
Text: SCU SET: [00221]11,13 C-5510,3505 B-21490 G18016 T11041,437,-46 R16 T-11|0,no src
#Ceiling VC21B
W 19-Dec-14 13:19:25 221 AX_SCU <I>LOG: cran_a -0.2, rao_a -0.1, sid_a 114.44 </I>
Time: 19.12.2014, 13:19:25, Process: C:\AXIOM\Service\bin\Rep.exe_1820,
Text: (19.12.2014 13:19:26) SCU SET: [00221]-16,-14 C9023,20 B-9025 GNIL,7 T7697,11286,-95 R0 S 11444|0,no src
#Robot VC21B
W 23-Jun-14 08:04:37 221 AX_SCU <I>LOG: cran_a -1.5, rao_a 1.7, sid_a 120.00 </I>
Time: 23.6.2014, 08:04:37, Process: C:\AXIOM\Service\bin\Rep.exe_2136,
Text: (23.06.2014 08:03:41) SCU SET: [00221]168,-147 C3971,3971 B-3971 G0,-16966,10941,15584 T8211,-2103,-531 R1508 T
#EAS
W 02-Apr-15 06:28:05 221 AX_SCU <I>LOG: cran_a 0.0, rao_a 0.0, sid_a 120.00 </I>
Time: 2.4.2015, 06:28:05, Process: C:\Axiom\Service\bin\Rep.exe_2280,
Text: (02.04.2015 06:28:04) SCU SET: [00221]0,0 C-3501,-3500 B3500 GNIL,-19130,10540,13102 T7833,6039,-21 R4 12000|0,no src
Floor Stand (additional text example):
0,0 C0,-1 B-3000 G90 T8000,5000,700 R0 T20 C15
CArmRot, CArmOrb [C] CameraRot, CollimRot
[B] BaseRot [G] GantryRot
[T] TableLift, TableLong, TableTrans
[R] TableRot [T] TableTilt [C] TableCradle
MP (additional text example): #not supported
0,0 C0 GLo-9000 GLi-9000 GT-9000 T-9000,-9000,-9000 M-9000
CArmRot, CArmOrb [C] CameraRot
[GLo] GantryLong [GLi] GantryLift [GT] GantryTilt
[T] TableLift, TableLong, TableTrans [M] Monitor
Ceiling Stand (additional text example):
0,0 C9,-9 B0 GNIL,-9000 T-9000,-9000,-9000 R-9000 T-9000 C-9000
CArmRot, CArmOrb [C] CameraRot, CollimRot
[B] Gantry(Base)Rot [G]NIL, GantryLong
[T] TableLift, TableLong, TableTrans
[R] TableRot [T] TableTilt [C] TableCradle
Robotic stand (additional text example):
1,-9 C6030,-2942 B-6029 G0,-9803,11006,3 T9364,5937,-203 R0 T0 C0
TCPRao, TCPCran [C] CameraRot, CollimRot
[B] TCPBeamRot [G]GantryRot, TCPLong, TCPLift, TCPTrans
[T] TableLift, TableLong, TableTrans
[R] TableRot [T] TableTilt [C] TableCradle
Artis one stand (additional text example):
1,-9 C6030,-2942 B-6029 G0,-9803,11006,3 T9364,5937,-203 R0 T0 C0
TCPRao, TCPCran [C] CameraRot, CollimRot
[B] TCPBeamRot [G]GantryRot, TCPLong, TCPLift, TCPTrans
[T] TableLift, TableLong, TableTrans
[R] TableRot [T] TableTilt [C] TableCradle
"""
#221
if( (lines[i].rfind('221'))>-1 and (lines[i].rfind('cran_a')>-1) and (lines[i+2].rfind('Backlog')==-1) and self.plane=='A'):
mat4=re.search(r'.+cran_a (-?\d+\.?\d*).+rao_a (-?\d+\.?\d*).+sid_a (-?\d+\.?\d*)',lines[i])
mat5=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) SCU SET: \[00221\](-?\d+),(-?\d+)\s*C(-?\d+),(-?\d+).+B(-?\d+).+G(-?\d+|NIL),?(|-?\d+),?(|-?\d+),?(|-?\d+)\s*T(-?\d+|NIL),(-?\d+|NIL),(-?\d+|NIL)+.(R-?\d+|)\s*(T-?\d+|)\s*(C-?\d+|C|)',lines[i+2])
#print'----'
#print lines[i+2]
if (mat4!=None and mat5!=None):
#print mat5.group(0)
if mat5.group(16)!='NIL':
try:
scu_T1.append(float(mat5.group(16))/100.) #x
except:
scu_T1.append(88888)
else:
scu_T1.append(88888)
if mat5.group(17)!='NIL':
try:
scu_T2.append(float(mat5.group(17))/100.) #y
except:
scu_T2.append(88888)
else:
scu_T2.append(88888)
if mat5.group(18)!='NIL':
try:
scu_T3.append(float(mat5.group(18))/100.) #z
except:
scu_T3.append(88888)
else:
scu_T3.append(88888)
if len(mat5.group(19))>0:
try:
scu_table_rot.append(float(mat5.group(19)[1:])/100.)
except:
scu_table_rot.append(888.)
else:
scu_table_rot.append(888.)
if len(mat5.group(20))>0:
try:
scu_table_tilt.append(float(mat5.group(20)[1:])/100.)
except:
scu_table_tilt.append(888.)
else:
scu_table_tilt.append(888.)
if len(mat5.group(21))>0:
try:
scu_table_cradle.append(float(mat5.group(21)[1:])/100.)
except:
scu_table_cradle.append(888.)
else:
scu_table_cradle.append(888.)
if self.plane=='A':
scu_cran.append(float(mat4.group(1)))
scu_rao.append(float(mat4.group(2)))
scu_sid.append(float(mat4.group(3)))
scu_carm_rot.append(float(mat5.group(7))/100.)
scu_carm_orb.append(float(mat5.group(8))/100.)
scu_camera_rot.append(float(mat5.group(9))/100.)
scu_collim_rot.append(float(mat5.group(10))/100.)
scu_time.append(mat5.group(3)+'-'+mat5.group(2)+'-'+mat5.group(1)+' '+mat5.group(4)+':'+mat5.group(5)+':'+mat5.group(6))
scu_base_rot.append(float(mat5.group(11))/100.) #base rot
if mat5.group(12)!='NIL': #gantry rot
scu_gantry_rot.append(float(mat5.group(12))/100.)
else:
scu_gantry_rot.append(88888)
try:
scu_gantry_long.append(float(mat5.group(15))/100.) #gantry long only ceiling in plane A
except:
scu_gantry_long.append('na')
#Tube Rotation
scu_carm_rot_rad=scu_carm_rot[-1]*np.pi/180.
scu_carm_orb_rad=scu_carm_orb[-1]*np.pi/180.
alpha_orb.append(180./np.pi*np.arcsin(-np.sin(scu_carm_orb_rad)*np.cos(scu_carm_rot_rad)))
xray_vec_z.append(np.cos(scu_carm_orb_rad)*np.cos(scu_carm_rot_rad)) #z-Komponente Xray Einheitsvektor
if self.myXEvent.SystemType!='Robot Stand' and len(alpha_orb)>1:
if alpha_orb[-1]<-89.0 and alpha_orb[-2]<-89.0:
idx1=bisect.bisect_left(envtime2d,dateutil.parser.parse(scu_time[-1]) )
idx2=bisect.bisect_left(envtime2d,dateutil.parser.parse(scu_time[-2]) )
vertical_tube_time+=(idx1-idx2)
else:
print 'error in scu 221: '+lines[i+2].lstrip()
#scu_cran.append(8888.)
#scu_rao.append(8888.)
#scu_sid.append(8888.)
#scu_time.append(8888.)
#scu_gantry.append(8888.)
#scu_T1.append(8888.)
#scu_T2.append(8888.)
#scu_T3.append(8888.)
#scu_carm_rot.append(8888.)
#scu_carm_orb.append(8888.)
#alpha_orb.append(8888.)
#222
#W 12-Nov-13 05:21:54 222 AX_SCU <I>LOG: cran_b -0.1, rao_b -90.1, sid_b 121.69 </I>
#Time: 12.11.2013, 05:21:54, Process: C:\AXIOM\Service\bin\Rep.exe_1108,
#Text: (12.11.2013 05:21:47) SCU SET: [00222]Rot7 Orb-9006 GantryLong-23317 C9002,9002 R12169 S|0,no src
if( (lines[i].rfind('222'))>-1 and (lines[i].rfind('cran_b')>-1) and (lines[i+2].rfind('Backlog')==-1) and self.plane=='B' ):
mat4=re.search(r'.+cran_b (-?\d+\.?\d*).+rao_b (-?\d+\.?\d*).+sid_b (-?\d+\.?\d*)',lines[i])
mat5=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) SCU SET: \[00222\]Rot(-?\d+)\s*Orb(-?\d+)\s*GantryLong(-?\d+)\s*C(-?\d+),(-?\d+)',lines[i+2])
if (mat4!=None and mat5!=None):
if self.plane=='B':
scu_cran.append(float(mat4.group(1)))
scu_rao.append(float(mat4.group(2)))
scu_sid.append(float(mat4.group(3)))
scu_time.append(mat5.group(3)+'-'+mat5.group(2)+'-'+mat5.group(1)+' '+mat5.group(4)+':'+mat5.group(5)+':'+mat5.group(6))
scu_carm_rot.append(float(mat5.group(7))/100.)
scu_carm_orb.append(float(mat5.group(8))/100.)
scu_gantry_long.append(int16(mat5.group(9))/100.) #Plane B position in mm (~ -23000 is parking position)
scu_camera_rot.append(float(mat5.group(10))/100.)
scu_collim_rot.append(float(mat5.group(11))/100.)
#Tube Rotation
scu_carm_rot_rad=scu_carm_rot[-1]*np.pi/180.
scu_carm_orb_rad=scu_carm_orb[-1]*np.pi/180.
alpha_orb.append(scu_carm_orb[-1])
xray_vec_z.append(-np.sin(scu_carm_orb[-1])) #z-Komponente Xray Einheitsvektor
if len(alpha_orb)>1:
if alpha_orb[-1]<-89.0 and alpha_orb[-2]<-89.0:
idx1=bisect.bisect_left(envtime2d,dateutil.parser.parse(scu_time[-1]) )
idx2=bisect.bisect_left(envtime2d,dateutil.parser.parse(scu_time[-2]) )
vertical_tube_time+=(idx1-idx2)
else:
if self.plane=='B':
print 'error in SCU 222'+lines[i+2]
#scu_gantry.append(88888.)
#scu_carm_rot.append(8888.)
#scu_carm_orb.append(8888.)
#alpha_orb.append(8888.)
#224 (Robot only and EAS only)
#W 05-Dec-2013 10:35:57 224 AX_SCU 0 LOG: origin tbl, A -90.01, B -0.05, C 0.10
# Time: 5.12.2013, 10:35:57, Process: C:\AXIOM\Service\bin\Rep.exe_1948,
# Text: (05.12.2013 10:35:53) SCU SET: [00224]A12,-6662,10438,108097,-3843,-117066 INC33,5,0 S|0,no src
#EAS
#Text: (22.05.2014 09:33:58) SCU SET: [00224]A23061,-23070,136,0,0,54 INCNIL,NIL,NIL |0,no src
if( lines[i].rfind('224')>-1 and lines[i].rfind('AX_SCU')>-1 and lines[i+2].rfind('Backlog')==-1 ) and (self.myXEvent.SystemType=="Robot Stand" or self.myXEvent.SystemType=="EAS Floor Mounted"):
mat6=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) SCU SET: \[00224\]A(-?\d+),(-?\d+),(-?\d+),(-?\d+),(-?\d+),(-?\d+) INC',lines[i+2])
if mat6!=None:
scu_224_time.append(mat6.group(3)+'-'+mat6.group(2)+'-'+mat6.group(1)+' '+mat6.group(4)+':'+mat6.group(5)+':'+mat6.group(6))
scu_224_robot_angles.append((mat6.group(7),mat6.group(8),mat6.group(9),mat6.group(10),mat6.group(11),mat6.group(12)))
beta=-np.pi/2 #(fix)
T1=np.pi/180*float(np.mod(int(mat6.group(7)),36000)) /100.
T2=np.pi/180*float(np.mod(int(mat6.group(8)),36000)) /100.*-1.
T3=np.pi/180*float(np.mod(int(mat6.group(9)),36000)) /100.*-1
T4=np.pi/180*float(np.mod(int(mat6.group(10)),36000))/100.*-1.
T5=np.pi/180*float(np.mod(int(mat6.group(11)),36000))/100.*-1
T6=np.pi/180*float(np.mod(int(mat6.group(12)),36000))/100.*-1.
#test data
#T1=12/100.*np.pi/180
#T2=-6662/100.*-1.*np.pi/180
#T3=10438/100.*-1.*np.pi/180
#T4=np.mod(108097/100,360)*-1.*np.pi/180
#T5=-3843/100.*-1.*np.pi/180
#T6=np.mod(-117066/100,360)*-1.*np.pi/180
#beta=-np.pi/2 #(fix)
#T1_grad=11/100.*np.pi/180
#T2_grad=-6661/100.*-1.*np.pi/180
#T3_grad=10439/100.*-1*np.pi/180
#T4_grad=np.mod(108088/100,360)*-1.*np.pi/180
#T5_grad=-3847/100.*-1*np.pi/180
#T6_grad=np.mod(-125970/100,360)*-1.*np.pi/180
alpha_orb_rob.append(180./np.pi*np.arcsin((-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.sin(T5)*np.cos(T4) + (np.sin(T2)*np.cos(T3) + np.sin(T3)*np.cos(T2))*np.cos(T5)))
alpha_xray_robot.append(180./np.pi*np.arcsin((-(-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.sin(T4)*np.sin(T6) + ((-np.sin(T2)*np.sin\
(T3) + np.cos(T2)*np.cos(T3))*np.cos(T4)*np.cos(T5) - (np.sin(T2)*np.cos(T3) + np.sin(T3)*np.cos(T2))*sin\
(T5))*np.cos(T6))*np.cos(beta) - ((-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.sin(T4)*np.cos(T6\
) + ((-np.sin(T2)*np.sin(T3) + np.cos(T2)*np.cos(T3))*np.cos(T4)*np.cos(T5) - (np.sin(T2)*np.cos(T3) + sin\
(T3)*np.cos(T2))*np.sin(T5))*np.sin(T6))*np.sin(beta)))
if len(alpha_orb_rob)>1:
if alpha_orb_rob[-1]<-89.0 and alpha_orb_rob[-2]<-89.0:
idx1=bisect.bisect_left(envtime2d,dateutil.parser.parse(scu_224_time[-1]) )
idx2=bisect.bisect_left(envtime2d,dateutil.parser.parse(scu_224_time[-2]) )
vertical_tube_time+=(idx1-idx2)
#Robi test
##############
#Example position 1:
#Cran0, rao0 headside pos. (Tisch gedreht siehe Example2)
#W 05-Dec-2013 10:35:57 224 AX_SCU 0 LOG: origin tbl, A -90.01, B -0.05, C 0.10
# Time: 5.12.2013, 10:35:57, Process: C:\AXIOM\Service\bin\Rep.exe_1948,
# Text: (05.12.2013 10:35:53) SCU SET: [00224]A12,-6662,10438,108097,-3843,-117066 INC33,5,0 S|0,no src
#W 05-Dec-2013 10:35:57 221 AX_SCU 0 LOG: cran_a 0.0, rao_a -0.2, sid_a 119.91
# Time: 5.12.2013, 10:35:57, Process: C:\AXIOM\Service\bin\Rep.exe_1948,
# Text: (05.12.2013 10:35:53) SCU SET: [00221]-23,0 C8997,-2 B9002 G0,16,12010,-11991 T9872,9592,1734 R-9001 T5 C10 S 1
#EAS
#W 06-Jun-14 10:17:07 224 AX_SCU <I>LOG: origin tbl, A 0.00, B 0.00, C 0.00 </I>
# Time: 6.6.2014, 10:17:07, Process: C:\Axiom\Service\bin\Rep.exe_2572,
# Text: (06.06.2014 10:17:07) SCU SET: [00224]A21482,-21853,-2682,0,0,-4208 INCNIL,NIL,NIL |0,no src
"""
beta_grad=-90 #(fix)
T1_grad=12/100.
T2_grad=-6662/100.*-1.
T3_grad=10438/100.*-1
T4_grad=np.mod(108097/100,360)*-1.
T5_grad=-3843/100.*-1
T6_grad=np.mod(-117066/100,360)*-1.
#Example Postion 2
#Cran90, rao-0 headside pos., tisch rot 90 grad (also eigentlich cran 0, rao-90 wenn Tisch 0,0,0)
#W 05-Dec-2013 10:35:50 224 AX_SCU 0 LOG: origin tbl, A -90.01, B -0.05, C 0.10
#Time: 5.12.2013, 10:35:50, Process: C:\AXIOM\Service\bin\Rep.exe_1948,
#Text: (05.12.2013 10:35:47) SCU SET: [00224]A11,-6661,10439,108088,-3847,-125970 INC35,-8889,0 S|0,no src
#W 05-Dec-2013 10:35:50 221 AX_SCU 0 LOG: cran_a -89.0, rao_a -0.3, sid_a 119.91
#Time: 5.12.2013, 10:35:50, Process: C:\AXIOM\Service\bin\Rep.exe_1948,
#Text: (05.12.2013 10:35:47) SCU SET: [00221]-26,-8900 C8998,-3 B8999 G0,16,12011,-11991 T9872,9592,1734 R-9001 T5 C10
beta_grad=-90. #(fix)
T1_grad=11/100.
T2_grad=-6661/100.*-1.
T3_grad=10439/100.*-1
T4_grad=np.mod(108088/100,360)*-1.
T5_grad=-3847/100.*-1
T6_grad=np.mod(-125970/100,360)*-1.
"""
#(alpha_orb_grad,alpha_xray_grad)=get_tube_rot_robi(beta,T1,T2,T3,T4,T5,T6)
#print alpha_orb_grad,alpha_xray_grad
#print scu_carm_rot[-1],scu_carm_orb[-1],alpha_orb[-1]
else:
print 'error in scu 224: '+lines[i+2].lstrip()
#Biplane Reset
#Text: (08.09.2014 08:02:46) ACU-A SET: [00130],0|fl_ab pressed, place: on table (example, all 'pressed' events are intial)
if lines[i].find('pressed,')>-1:
actual_biplane=0
#Biplane Set
#W 08-Sep-14 06:59:53 42 AX_ACU <I>LOG, Internal Info </I>
# Time: 8.9.2014, 06:59:53, Process: C:\AXIOM\Service\bin\Rep.exe_2140,
# Text: (08.09.2014 06:59:55) ACU-A SET: [00201]CommPlaneSyncThread,209|MASTER SEQUENCE
#W 08-Sep-14 06:59:53 42 AX_ACU <I>LOG, Internal Info </I>
# Time: 8.9.2014, 06:59:53, Process: C:\AXIOM\Service\bin\Rep.exe_2140,
# Text: (08.09.2014 06:59:56) ACU-B SET: [00201]CommPlaneSyncThread,186|SLAVE SEQUENCE
#evtl. reicht nach Master Sequenz zu suchen...
if lines[i].find('42\tAX_ACU')>-1 :
data_biplane=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ACU-([A,B]) SET:.+CommPlaneSyncThread.+MASTER SEQUENCE',lines[i+2]) #Events kommen nur bei Biplane FL/ACQ
if data_biplane!=None:
if data_biplane.group(7)=='A':
actual_biplane=1
else: #==B
actual_biplane=2
#ACU 0095
plane_str_acu='ACU-'+self.plane
if (lines[i].find('[00095]')>-1 and lines[i].find(plane_str_acu)>-1 ):
actual_OGP='None' #because this telegram should be later in log and overwrite 'n.a' if found correctly
#Text: (01.10.2008 07:01:58) ACU-A SET: [00095] ,0|X0100 #0064 B0041 g0409 b1 k0008 D4f19 f03 r0002 p02 i^02de 5012 ms
data_acu95=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ACU-([A,B]) SET: \[00095\].+#(\d+)\s*B(\d+).+D([0-9,a-f]+)\s*f([0-9,a-f]+)\s*r([0-9,a-f]+).+i\^([0-9,a-f]+)\s*(\d+)\s*',lines[i])
#VB11:'Text: ACU-B SET: [00095] ,0|X0100 #1212 B0271 g0407 b1 k0008 D1001 f02 r001d p02 i004067 44940 ms'
if data_acu95!=None:
acu_exist=1
else:
if not IcConsMode:
print 'invalid [00095] entry: '+lines[i].strip()
acu_exist=0
if (acu_exist==1 and exist_p391==1 and self.plane==data_acu95.group(7)):
try:
if int(data_acu95.group(13),16)==int(data_391p.group(21),16):
ACU_ID=int(data_acu95.group(13),16)
acu_frames=int(data_acu95.group(8))
except:
print "missing preview due to RM?"
#ACU 00169 (Pname)
plane_str_acu='ACU-'+self.plane
if (lines[i].find('[00169]')>-1 and lines[i].find(plane_str_acu)>-1 ):
#Text: (02.05.2012 00:07:59) ACU-A SET: [00169],0|Pid: 000005, Pname: RM Neuro #Artis
#Text: (31.10.2013 17:09:03) ACU-A SET: [00169]Pid: 000002, Pname: FL Normal.(,0) #EAS
#print lines[i]
mat9=re.search(r'ACU-([A-B]) SET: \[00169\](?:\,0\||)Pid: ([0-9]+)\, Pname:\s*(.+)(?:\(\,0\)|)',lines[i].decode('unicode-escape'))
if(mat9!=None):
if(self.plane==mat9.group(1)):
actual_OGP=mat9.group(3)
actual_OGP=actual_OGP.replace('(,0)','')
actual_OGP=actual_OGP.strip()
actual_OGP=actual_OGP.replace(';','.')
else:
if not IcConsMode:
print 'invalid [00169] entry: '+lines[i].strip()
actual_OGP='None'
#print actual_OGP
#Arcing-events (PUD 5016)
#Text: (01.06.2012 08:00:50) ANG-A SET: [0x5016]PL A100G (SW:EG02L5; HW:VG01C): (5016 GEN. 13 1c)#-15#122
#Text: (01.06.2012 07:11:28) ANG-A SET: [0x5016]PL A100G (SW:EG02L1; HW:VG01C): (Err5016 GEN. 13 18)#-245
searchstring=r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-['+self.plane+'] SET: \[0x5016\].+SW:(.+)\).+5016 GEN.\s*(.+)'
if(lines[i].rfind('ANG-'+self.plane+' SET: [0x5016]')>-1):
#test if event in in allowed time intervall
zzz=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-['+self.plane+'] SET: \[0x5016\]',lines[i])
event_time1=False
event_datetime1=datetime.datetime(int(zzz.group(3)),int(zzz.group(2)),int(zzz.group(1)),int(zzz.group(4)),int(zzz.group(5)),int(zzz.group(6)))
if(event_datetime1>=self.start__datum and event_datetime1<=self.ende__datum):
event_time1=True
arcing_dat = re.search(searchstring, lines[i])
if arcing_dat!=None and event_time1:
a_t = arcing_dat.group(3)+'-'+arcing_dat.group(2)+'-'+arcing_dat.group(1)+' '+arcing_dat.group(4)+':'+arcing_dat.group(5)+':'+arcing_dat.group(6)
arcing_time.append(a_t)
num_arcing_tot+=1
#Text1: (16.03.2012 01:18:39) ANG-A SET: [0x5016]PL A100G (SW:VG02F; HW:VG01C): (Err5016 GEN. 13 18)#+123
# oder
#Text2: (01.06.2012 07:51:47) ANG-A SET: [0x5016]PL A100G (SW:EG02L5; HW:VG01C): (5016 GEN. 13 1d)#-34#82
# oder
#Text3: (09.03.2012 18:10:55) ANG-B SET: [0x5016]PL A100G (SW:VG02F; HW:VG01C): (Err5016 GEN. 0x13 0x0007)
if arcing_dat.group(8).count('#')==1: #Text2
arcing_tmp = re.search(r'13\s*(.*)\)#(.+)',arcing_dat.group(8))
if arcing_tmp!=None:
arcing_type.append('0x00'+arcing_tmp.group(1))
arcing_frame.append(arcing_tmp.group(2))
else:
arcing_type.append('n.a.') #from 'upload error'
arcing_frame.append('n.a.')
elif arcing_dat.group(8).count('#')==2: #Text2
arcing_tmp = re.search(r'13\s*(.*)\)#(.*)#',arcing_dat.group(8))
if arcing_tmp!=None:
arcing_type.append('0x00'+arcing_tmp.group(1).upper())
arcing_frame.append(arcing_tmp.group(2))
else:
arcing_type.append('n.a.') #from 'upload error'
arcing_frame.append('n.a.')
else: #Text1
arcing_tmp = re.search(r'0x13\s*(.*)\)',arcing_dat.group(8))
if arcing_tmp!=None:
arcing_type.append(arcing_tmp.group(1))
arcing_frame.append('0') #'0' because it is not defined on this older PUN FW
else:
arcing_type.append('n.a.') #from 'upload error'
arcing_frame.append('n.a.')
arcing_time_global.append(arcing_time[-1]) #speichere die Zeit des arcing-events
arcing_type_global.append(arcing_type[-1]) #speichere den Typ des arcing-events ab
arcing_kV_global.append(actual_kV) #speichere den Typ des arcing-events ab
arcing_mA_global.append(actual_mA) #speichere den Typ des arcing-events ab
arcing_ms_global.append(actual_ms)
arcing_foc_global.append(actual_foc) #speichere den Typ des arcing-events ab
arcing_frame_global.append(arcing_frame[-1]) #speichere den Typ des arcing-events ab
arcing_ogp_global.append(actual_OGP)
arcing_HU_global.append(actual_HU)
arcing_idx_global.append(actual_idx)
#PUN Type and SW Version #works only if radiation is done during analysized time
#Text: (22.06.2015 18:13:58) ANG-A SET: [0x9225]PL A100Plus (SW:VG02Y; HW:VG01C): (No. of SWR pulses: 5)
if lines[i].find('ANG-'+self.plane+' SET')>-1 and lines[i].find('No. of SWR pulses')>-1: #xxx treat PUN change
dat_gen=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-['+self.plane+'] SET: \[0x9225\]PL (.+).+SW:(.+);.+HW:(.+)\):',lines[i])
temptime=datetime.date(int(dat_gen.group(3)),int(dat_gen.group(2)),int(dat_gen.group(1)))
if len(generator)>0:
if generator[-1][1:]!=(dat_gen.group(8),dat_gen.group(9)):
generator.append((str(temptime),dat_gen.group(8),dat_gen.group(9)))
else:
generator.append((str(temptime),dat_gen.group(8),dat_gen.group(9)))
generator_type=dat_gen.group(7).strip()
#Grid warnings 509A
searchstring=r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-['+self.plane+'] SET: \[0x509A\].+SW:(.+)\).+509a GEN.\s*(.+)'
if(lines[i].rfind('SET: [0x509A]')>-1):
grid_dat = re.search(searchstring, lines[i])
if grid_dat!=None:
a_t = grid_dat.group(3)+'-'+grid_dat.group(2)+'-'+grid_dat.group(1)+' '+grid_dat.group(4)+':'+grid_dat.group(5)+':'+grid_dat.group(6)
grid_time.append(a_t)
num_grid_tot+=1
#Text2: (26.04.2012 13:08:39) ANG-A SET: [0x509A]PL A100G (SW:VG02L; HW:VG01C): (Err509a GEN. 0x9D 0x0003)#-9
grid_tmp = re.search(r'9d\s*(.*)\)#(.*)#',grid_dat.group(8))
if grid_tmp!=None:
grid_type.append('0x00'+grid_tmp.group(1).upper())
grid_frame.append(grid_tmp.group(2))
else:
grid_type.append('n.a.') #from 'upload error'
grid_frame.append('n.a.')
#-------------------
#ANG Errors-Warnings
if lines[i].find('AX_ANG')>-1 and lines[i+2].find('ANG-'+self.plane)>-1 and lines[i].find('255\tAX_ANG')==-1 and lines[i].find('636\tAX_ANG')==-1:
for ang_err_type in ANG_ERR.keys():
if lines[i].find(ang_err_type)>-1:
vvv=re.search(r'(\d+)\.(\d+)\.(\d+),\s*(\d+):(\d+):(\d+)',lines[i+1])
if vvv!=None:
altern_ang_err_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)))
uuu=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\)' ,lines[i+2])
if uuu!=None:
ang_err_time=datetime.datetime(int(uuu.group(3)),int(uuu.group(2)),int(uuu.group(1)),int(uuu.group(4)),int(uuu.group(5)),int(uuu.group(6)) )
if vvv!=None:
if abs(altern_ang_err_time-ang_err_time)>datetime.timedelta(minutes=1):
ang_err_time=altern_ang_err_time
ANG_ERR[ang_err_type].append(ang_err_time)
#--------------------
#PUD Errors-Warnings
if lines[i].find('AX_PUD')>1 and lines[i].find('Info_9225')==-1 and lines[i+2].find('ANG-'+self.plane)>-1:
for pun_err_type in PUN_ERR.keys():
err_nr_str=pun_err_type.split('_')[1]
if lines[i+2].find('0x'+err_nr_str)>-1:
vvv=re.search(r'(\d+)\.(\d+)\.(\d+),\s*(\d+):(\d+):(\d+)',lines[i+1])
if vvv!=None:
altern_pud_err_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)))
uuu=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[0x'+err_nr_str+'\].+',lines[i+2])
if uuu!=None:
pud_err_time=datetime.datetime(int(uuu.group(3)),int(uuu.group(2)),int(uuu.group(1)),int(uuu.group(4)),int(uuu.group(5)),int(uuu.group(6)) )
if vvv!=None:
if abs(altern_pud_err_time-pud_err_time)>datetime.timedelta(minutes=1):
pud_err_time=altern_pud_err_time
PUN_ERR[pun_err_type].append(pud_err_time)
if pun_err_type=='Warn_5112_WARNING_OVERLOAD' or pun_err_type=='Info_5113_INFO_ITACT_SHUNT':
if len(PUN_ERR['Warn_5112_WARNING_OVERLOAD'])>0 and len(PUN_ERR['Info_5113_INFO_ITACT_SHUNT'])>0:
if abs(PUN_ERR['Warn_5112_WARNING_OVERLOAD'][-1]-PUN_ERR['Info_5113_INFO_ITACT_SHUNT'][-1]) <= datetime.timedelta(minutes=1): #check if both events occur in same minute
MMT_warning.append(PUN_ERR['Warn_5112_WARNING_OVERLOAD'][-1])
###FPGA Error F2 Megalix A100Plus
# F2 from ANG391p
# 50 AX_ANG High voltage active after pulse end
# Info_5113_INFO_ITACT_SHUNT???
# Warn_5081_FIL_WARNING (A100)
# increase heat current offset F2 (-> 5000)
if pun_err_type=='Warn_5081_FIL_WARNING':
try:
if data_391p.group(19)=='L' and generator_type=='A100Plus':
event_391p=datetime.datetime(int(data_391p.group(3)),int(data_391p.group(2)),int(data_391p.group(1)),int(data_391p.group(4)),int(data_391p.group(5)),int(data_391p.group(6)))
event_PUN5081=PUN_ERR['Warn_5081_FIL_WARNING'][-1]
event_ANG50=ANG_ERR['\t50\tAX_ANG'][-1]
if abs(event_391p-event_PUN5081)<datetime.timedelta(seconds=1) and abs(event_391p-event_ANG50)<datetime.timedelta(seconds=1):
FPGA_Error.append(event_ANG50)
except:
True
#Tube Adjust
#VD10+
#Text: (18.03.2014 12:00:06) ANG-A SET: [0xAD00]PL A100G (SW:VG02Y; HW:VG01C): Done Tube Adjust
if(lines[i].rfind('ANG-'+self.plane+' SET: [0xAD00]')>-1) and (lines[i].rfind('Done Tube Adjust')>-1):
vvv=re.search(r'(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)',lines[i])
TUBE_ADJUST_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)) )
TUBE_ADJUST.append(TUBE_ADJUST_time)
# !!! Todo check for VCxx, EAS !!!
#VCxx
#I 04-Jun-14 12:37:55 2 AX_SF <I>Pms_Cag: Generator adjustment (tube) on plane A finished!
if current_SW_short[:-2] == 'VC':
if(lines[i].rfind('Pms_Cag: Generator adjustment (tube) on plane '+self.plane+' finished!')>-1):
vvv=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
TUBE_ADJUST_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)) )
TUBE_ADJUST.append(TUBE_ADJUST_time)
#Tube Conditioning
#Time: 24.11.2014, 15:50:51, Process: C:\AXIOM\Service\bin\Rep.exe_2124,
#Text: (24.11.2014 15:50:50) ANG-B SET: [00001]Tube condition Start - Heat Unit: 4 % - Threshold: 5 % - T0: 49
#Text: (09.04.2014 08:50:24) ANG-B SET: [00001] Tube Condition Ended with - Heat Unit: 58 % T0: 70
#or
#Text: (09.04.2014 08:50:25) ANG-B SET: [00001] Tube Condition Aborted with
if(lines[i].rfind('ANG-'+self.plane+' SET: [00001]Tube condition')>-1): #only start, regardless of abort (VD10 ok, other versions?)
vvv=re.search(r'(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)',lines[i])
TUBE_CONDITIONING_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)) )
TUBE_CONDITIONING.append(TUBE_CONDITIONING_time)
#NO_XRAY
if(lines[i].rfind('ANG-'+self.plane+' :[00220]ErrNo Xray')>-1):
vvv=re.search(r'(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)',lines[i])
NO_XRAY_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)) )
NO_XRAY.append(NO_XRAY_time)
if(lines[i].rfind('NO XRAY, Bypass Fluoro not possible')>-1):
vvv=re.search(r'(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)\) ANG-'+self.plane+' RESET',lines[i])
if vvv !=None:
NO_XRAY_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)) )
NO_XRAY.append(NO_XRAY_time)
#if(lines[i].upper().rfind('BYPASS')>-1) or (lines[i].upper().rfind('NO XRAY')>-1) or (lines[i].upper().rfind('DOSE LESS')>-1):
# print lines[i]
#W 28-Apr-14 10:50:42 2118 AX_ACU LOG: Less frames than forecasted
#Time: 28.4.2014, 10:50:42, Process: C:\AXIOM\Service\bin\Rep.exe_2116,
#Text: (28.04.2014 10:50:42) ACU-A SET: [00061]XrayCntThread3d,1527|Less Frs than forecasted
if(lines[i].rfind('ACU-'+self.plane+' SET: [00061]XrayCntThread3d')>-1 and lines[i].rfind('Less Frs than forecasted')>-1):
vvv=re.search(r'(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)',lines[i])
LESS_FRAMES_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)) )
LESS_FRAMES.append(LESS_FRAMES_time)
#-------------------------------------------------
#I 05-Mar-15 09:02:43 40000 CAP_AN <I>Send successful.3 image(s) of patient with Loid __ sent to Dynamics. </I>
# Time: 5.3.2015, 09:02:43, Line: 822, File: t:\medcom\src\archnet\archnet_server\src\capanbeserver\CapANBeNetworkNodeJob_haz.cpp, Process: CsaGenericMain (3148),
if lines[i].find('40000\tCAP_AN')>-1:
dat_capan=re.search(r'Send successful\.(\d+) image\(s\) of patient with Loid',lines[i])
vvv=re.search(r'(\d+)\.(\d+)\.(\d+), (\d+):(\d+):(\d+)',lines[i+1])
if vvv !=None:
capan_time=datetime.datetime(int(vvv.group(3)),int(vvv.group(2)),int(vvv.group(1)),int(vvv.group(4)),int(vvv.group(5)),int(vvv.group(6)))
try:
transfer_dynamics.append((capan_time,dat_capan.group(1)))
except:
1
#------------
#Leo
#W 20-Dec-13 03:42:29 17 AX_REP syngoXWP connected to ARTIS
# Time: 20.12.2013, 03:42:29, Process: C:\AXIOM\Service\bin\Rep.exe_2052,
# Text: System type: syngo_XWP, SW Version: VC10C, Serial number: 12005, Part number: m-001-740623
if lines[i].find('syngoXWP connected to ARTIS')>-1:
zzz=re.search(r'SW Version: (.+), Serial number: (\d+),', lines[i+2])
try:
self.Leo.add(zzz.group(2))
self.Leo_SW.add(zzz.group(1))
except:
print('error reading syngoxwp '+lines[i+2])
#Axis DEV 001
#W 13-Feb-14 09:01:25 1 AX_DEV <I>AxisTrace: EDR-A (896x896, 12-bit) ActID: 0x605e (24670) MaxFrames: 1024 Rate: 750 </I>
# Time: 13.2.2014, 276496:00:00, Line: -1, File: EDR::ProcessImageInfo, Process: "C:\AXIOM\axis\ERRORH~1.HLP"_376
if(lines[i].find('<I>AxisTrace: EDR-'+self.plane)>-1 ) and (lines[i].find('MaxFrames')>-1):
dat_dev2=re.search(r'(\d{2}):(\d{2}):(\d{2})\s*1\s*AX_DEV\s*<I>AxisTrace: EDR-'+self.plane+' \((\d+x\d+).+\) ActID: 0x([0-9a-f]+) ',lines[i])
if dat_dev2.group(0)!=None:
act_axis_id2=dat_dev2.group(5)
act_axis_resolution[act_axis_id2]=dat_dev2.group(4)
#W 13-Feb-14 09:01:25 1 AX_DEV <I>AxisTrace: EDR-A Mode: Fluoro ActID: 0x605e (24670) BP: 0 Room: 1 </I> ##First message after footswitch
# Time: 13.2.2014, 276496:00:00, Line: -1, File: EDR::ProcessStartCommand, Process: "C:\AXIOM\axis\ERRORH~1.HLP"_410376
if(lines[i].find('<I>AxisTrace: EDR-'+self.plane)>-1 ) and (lines[i].find('Room')>-1):
dat_dev1=re.search(r'(\d{2}):(\d{2}):(\d{2})\s*1\s*AX_DEV\s*<I>AxisTrace: EDR-'+self.plane+' Mode: (.+)ID: 0x([0-9a-f]+) ',lines[i])
if dat_dev1.group(0)!=None:
act_axis_id1=dat_dev1.group(5)
act_axis_mode[act_axis_id1]=dat_dev1.group(4)
#--------------------------------------------------
#AX_ANG 255
if(lines[i].rfind('diagnostic')>-1 ):
# new patient if new day (new log file)
if(new_day==1):
new_pat=1 #unklar ob das hier ueberhaupt gebraucht wird, da vor Strahlung immer Patient angelegt wird -> 105008 Arbeiten über Datumgrenze checken?!
old_date_time=old_time #Zeit vom letzten Strahlungsevent vom Vortag merken
new_day=0;
line=lines[i+2]
i=i+2
#Suche nach statischen Lernparametern auf aktueller Ebene
if self.myXEvent.numFoken == 3:
if(line.rfind('L1:')>1 and line.rfind('ANG-'+self.plane)>1 and line.rfind('Backlog')==-1):
#Text: Backlog (01.01.2007 01:00:56) ANG-B SET: [00001]L1:102, L2:-609, S1:99, S2:905, M1:99, M2:32
Lernparameter = re.search(r'.+L1:(-?\d+), L2:(-?\d+), S1:(-?\d+), S2:(-?\d+), M1:(-?\d+), M2:(-?\d+)', line)
Lernparameter_DATUM = re.search(r'.+Time: (\d+).(\d+).(\d+), (\d+):(\d+):(\d+)', lines[i-1]) #das Datum steht eine Zeile drüber
try:
x=Lernparameter.group();
exist__=1
except AttributeError:
print 'Fehler bei Lernparametern\n'
exist__=0
L_time = Lernparameter_DATUM.group(3)+'-'+Lernparameter_DATUM.group(2)+'-'+Lernparameter_DATUM.group(1)+' '+Lernparameter_DATUM.group(4)+':'+Lernparameter_DATUM.group(5)+':'+Lernparameter_DATUM.group(6)
Lernparameter_datum.append(L_time)
if int(Lernparameter.group(1)) <= 32767:
L1.append(Lernparameter.group(1))
else:
L1.append(int(Lernparameter.group(1))-65536)
if int(Lernparameter.group(2)) <= 32767:
L2.append(int(Lernparameter.group(2)))
else:
L2.append(int(Lernparameter.group(2))-65536)
if int(Lernparameter.group(3)) <= 32767:
S1.append(int(Lernparameter.group(3)))
else:
S1.append(int(Lernparameter.group(3))-65536)
if int(Lernparameter.group(4)) <= 32767:
S2.append(int(Lernparameter.group(4)))
else:
S2.append(int(Lernparameter.group(4))-65536)
if int(Lernparameter.group(5)) <= 32767:
M1.append(int(Lernparameter.group(5)))
else:
M1.append(int(Lernparameter.group(5))-65536)
if int(Lernparameter.group(6)) <= 32767:
M2.append(int(Lernparameter.group(6)))
else:
M2.append(int(Lernparameter.group(6))-65536)
if (line.rfind('L3:')>1 and line.rfind('ANG-'+self.plane)>1 and line.rfind('Backlog')==-1):
Lp = re.search(r'.+L3:(-?\d+), S3:(-?\d+), M3:(-?\d+)', line)
if int(Lp.group(1)) <= 32767:
L3.append(int(Lp.group(1)))
else:
L3.append(int(Lp.group(1))-65536)
if int(Lp.group(2)) <= 32767:
S3.append(int(Lp.group(2)))
else:
S3.append(int(Lp.group(2))-65536)
if int(Lp.group(3)) <= 32767:
M3.append(int(Lp.group(3)))
else:
M3.append(int(Lp.group(3))-65536)
else:
if(line.rfind('L1:')>1 and line.rfind('ANG-'+self.plane)>1 and line.rfind('Backlog')==-1):
#Text: Backlog (01.01.2007 01:00:56) ANG-B SET: [00001]L1:102, L2:-609, S1:99, S2:905, M1:99, M2:32
Lernparameter = re.search(r'.+L1:(-?\d+), L2:(-?\d+), S1:(-?\d+), S2:(-?\d+)', line)
Lernparameter_DATUM = re.search(r'.+Time: (\d+).(\d+).(\d+), (\d+):(\d+):(\d+)', lines[i-1]) #das Datum steht eine Zeile drüber
try:
x=Lernparameter.group();
exist__=1
except AttributeError:
print 'Fehler bei Lernparametern\n'
exist__=0
L_time = Lernparameter_DATUM.group(3)+'-'+Lernparameter_DATUM.group(2)+'-'+Lernparameter_DATUM.group(1)+' '+Lernparameter_DATUM.group(4)+':'+Lernparameter_DATUM.group(5)+':'+Lernparameter_DATUM.group(6)
Lernparameter_datum.append(L_time)
if int(Lernparameter.group(1)) <= 32767:
L1.append(int(Lernparameter.group(1)))
else:
L1.append(int(Lernparameter.group(1))-65536)
if int(Lernparameter.group(2)) <= 32767:
L2.append(int(Lernparameter.group(2)))
else:
L2.append(int(Lernparameter.group(2))-65536)
if int(Lernparameter.group(3)) <= 32767:
S1.append(int(Lernparameter.group(3)))
else:
S1.append(int(Lernparameter.group(3))-65536)
if int(Lernparameter.group(4)) <= 32767:
S2.append(int(Lernparameter.group(4)))
else:
S2.append(int(Lernparameter.group(4))-65536)
if (line.rfind('L3:')>1 and line.rfind('ANG-'+self.plane)>1 and line.rfind('Backlog')==-1):
Lp = re.search(r'.+L3:(-?\d+), S3:(-?\d+)', line)
if int(Lp.group(1)) <= 32767:
L3.append(int(Lp.group(1)))
else:
L3.append(int(Lp.group(1))-65536)
if int(Lp.group(2)) <= 32767:
S3.append(int(Lp.group(2)))
else:
S3.append(int(Lp.group(2))-65536)
plane_str='ANG-'+self.plane
#AX_ANG 255 [00391]p -------------nur preview---------dient zur Ermittlung der Soll-FD-Dosis
if (line.rfind('[00391]p')>1 and line.rfind(plane_str)>1):
#new preview, forget all old values (maybe wrong if ACU 0095 is late); preview may still be errorneous
exist_391=0
exist_p453=0
exist_453=0
acu_exist=0
dap453=0
dose453=0
current453=0
scenetime453=0
if len(arcing_time) > 0:
arcing_time=[]
arcing_type=[]
if len(grid_time) > 0:
grid_time=[]
grid_type=[]
if len(T1_arcing_time) > 0:
T1_arcing_time=[]
#Artis Text: (30.12.2009 10:35:58) ANG-A SET: [00391]p0100: 0 0# 200W - 70U100I 3T 333u 0u 45n 2S1 -2256i
#EAS Text: (28.01.2013 10:53:02) ANG-A SET: [00391]p0100: 0 0# 200W - 70U 47I 3T 148u 0u 23n 1L0 - 48i
if current_SW_short != 'VA10':
data_391p = re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[00391\]p([0-2]+):\s+([0,-])\s+(\d+)#\s*(-?\d+)W - \s*(-?\d+)U\s*(-?\d+)I\s*(\d+)T\s*(\d+)[u,m]\s*(\d+)[u,n]\s*(\d+)[u,n]\s*(\d)([S;L;M])(\d)\s*-\s*([0-9,a-f]+)i',line)
else:
data_391p = re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[00391\]p([0-2]+):\s+([0,-])\s+(\d+)#\s*(-?\d+)W . \s*(-?\d+)U\s*(-?\d+)I\s*(\d+)T\s*(\d+)[u,m]\s*(\d+)[u,n]\s*(\d+)[u,n]\s*(\d)([S;L;M])(\d)\s*-\s*([0-9,a-f]+)i',line)
if(data_391p!=None): #erste logeintrag eines neuen events, alle flags resetten
exist_p391=1
actual_kV=float(data_391p.group(12))
actual_mA=float(data_391p.group(13)) #nicht ganz korrekt, da mA sich im Review unterscheiden koennen...
actual_ms=float(data_391p.group(14))
actual_foc=data_391p.group(19)
actual_idx=data_391p.group(21)
else:
exist_p391=0;
if not IcConsMode:
print 'invalid [00391]p entry: '+line.strip()
#find out kV,mA,foc for arcing in service mode
#ANG-B SET: [00391]p0100: 0 0# 200W - 102U 31I - 1030u 0u - 0S0 - -
data_391p2 = re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[00391\]p([0-2]+):.+W . \s*(-?\d+)U\s*(-?\d+)Is*(\d+)T.+([S;L;M]).+([0-9,a-f]+)i',line)
if data_391p2!=None:
actual_kV=float(data_391p2.group(9))
actual_mA=float(data_391p2.group(10))
actual_ms=float(data_391p2.group(11))
actual_foc=data_391p2.group(12)
actual_idx=data_391p2.group(13)
else:
actual_kV=0.
actual_mA=0.
actual_ms=0
actual_foc='None'
actual_idx=0
#HU counting (also in service)
dataHU=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-'+self.plane+' SET: \[00453\].+ (\d+)\[?%\]?',line)
if dataHU != None:
all_HU.append(int(dataHU.group(7)))
all_HU_time.append(dataHU.group(3)+'-'+dataHU.group(2)+'-'+dataHU.group(1)+' '+dataHU.group(4)+':'+dataHU.group(5)+':'+dataHU.group(6))
#AX_ANG 255 [00391]
if (line.rfind('[00391]')>-1 and line.rfind(plane_str)>1 and line.rfind('[00391]p')==-1 ): #if Pname entry is slower than 5016
if len(arcing_ogp_global)>0:
if arcing_ogp_global[-1]=='None':
arcing_ogp_global=[w.replace('None',actual_OGP) for w in arcing_ogp_global]
#Text: (01.10.2008 07:02:38) ANG-A SET: [00391]0001: - 64# 200W3 57U191I 2T 399u 0u - 9S0 0s 2e0i110c 0R 0
#data=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-([A,B]) SET: \[00391\]([0-2]+):.+ (\d+)#\s*(\d+)W([0-9,a])\s*(\d+)U\s*(\d+)I\s*(\d+)T\s*(\d+)[u,m]\s*(\d+)[u,n]\s*(\d+)[u,n]\s*(\d)([S;L;M])(\d)\s*(\d+)s\s*([0-9,a-f]+)i\s*(\d+)c\s*(-?\d+)R\s*(-?\d+)',line) #bis VC14B
data=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[00391\]([0-2]+):.+ (\d+)#\s*(-?\d+)W([0-9,a])\s*(\d+)U\s*(\d+)I\s*(\d+)T\s*(\d+[u,m])\s*(\d+)[u,n]\s*(\d+)[u,n]\s*(\d)([S;L;M])(\d)\s*(\d+)s\s*([0-9,a-f]+)i',line)
#test if event in in allowed time intervall
ttt=re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[00391\]([0-8]+):',line)
event_time=False
if ttt!=None:
event_datetime=datetime.datetime(int(ttt.group(3)),int(ttt.group(2)),int(ttt.group(1)),int(ttt.group(4)),int(ttt.group(5)),int(ttt.group(6)))
if(event_datetime>=self.start__datum and event_datetime<=self.ende__datum):
event_time=True
#print re.search(r'.+\((\d+).(\d+).(\d+) (\d+):(\d+):(\d+)\) ANG-(['+self.plane+']) SET: \[00391\]([0-8]+):',line).group(0)
if ttt.group(8)=='8000': #bypass
bypass_fl.append(event_datetime) #skindose to be added
#if event_datetime-power_on[-1]>datetime.timedelta(minutes=1):
#total events
rrr=re.search(r'.+[S;L;M]\d\s*\d+s\s*([0-9,a-f]+)i',line)
if rrr!=None and event_time:
act_index=rrr.group(1)
if old_index!=act_index:
total_events.append(1)
old_index=act_index
try:
x=data.group();
exist_391=1
exist_453=0 #391 has to be previous to 453, so last 453 entry is irrelevant
#test if event in in allowed time intervall
#event_time=False
#event_datetime=datetime.datetime(int(data.group(3)),int(data.group(2)),int(data.group(1)),int(data.group(4)),int(data.group(5)),int(data.group(6)))
#if(event_datetime>=self.start__datum and event_datetime<=self.ende__datum):
# event_time=True
frames_391=int(data.group(9))
#WW should be >0
if float(data.group(10))<=0.0 and self.cb_negWV.GetValue()==False:
exist_391=0
#Roadmap problem, fluoro with control stop (no preview)
if (data.group(8)=='0100' or data.group(8)=='0200') and data.group(11)=='6':
exist_p391=1
exist_p453=1
acu_frames=int(data_acu95.group(8)) #nicht ganz sauber...
if (data.group(8)=='0001' or data.group(8)=='0002') and exist_p391==0:
if not IcConsMode:
print 'invalid [00391] entry (missing preview for acq): '+line.strip()
exist_391=0
frames_391=0
except AttributeError:
if not IcConsMode:
print 'invalid [00391] entry: '+line.strip()
exist_391=0
frames_391=0
#AX_ANG 255 preview
plane_str='ANG-'+self.plane
if (line.rfind('[00453]p')>1 and line.rfind(plane_str)>1):
#Text: (22.09.2009 08:53:41) ANG-A SET: [00453]0001: 111cm 0C 0R 4930A 9907T 11% 150F 94fr 3D:NO (VC14)
#Text: (07.05.2014 17:22:27) ANG-A SET: [00453]p0100: PP 94cm 4C 0R - - 2[%] -120F 1000fr no3d 0#0 (EAS)
#Text: (09.10.2013 11:29:28) ANG-A SET: [00453]p0100: GP 100cm 0C 0R - - 0% 0F 750fr no3d 2#2 (VD10)
if current_SW_short == 'VC14':
preview = re.search(r'.+ANG-(['+self.plane+']) SET: \[00453\]p([0-2]+):\s*(GP|PP|)\s*(\d+)cm\s*(-?\d+)C\s*(-?\d+)R.+\s(\d+)%',line)
else:
preview = re.search(r'.+ANG-(['+self.plane+']) SET: \[00453\]p([0-2]+):\s*(GP|PP|)\s*(\d+)cm\s*(-?\d+)C\s*(-?\d+)R.+\s(\d+)\[?%\]?',line)
if len(scu_T1)>0:
prev_table_pos=np.array([scu_T1[-1],scu_T2[-1],scu_T3[-1]])
try:
xx=preview.group()
exist_p453=1
actual_HU=preview.group(7)
except AttributeError:
if not IcConsMode:
print 'invalid [00453]p entry: '+line.strip()
exist_p453=0
actual_HU=-1
#AX_ANG 255 [00453] ------- review
if (line.rfind('ANG-'+self.plane+' SET: [00453]0')>1 ):
#Text: (22.09.2009 08:53:41) ANG-A SET: [00453]0001: 111cm 0C 0R 4930A 9907T 11% 150F 94fr 3D:NO
#Text: (09.10.2013 11:28:36) ANG-A SET: [00453]0100: GP 100cm 0C 0R 96A 1339ST 0% 90F 750fr no3d 1#1 (VC21,VD10)
#Text: (07.05.2014 17:22:32) ANG-A SET: [00453]0100: PP 94cm 4C 0R 509A 4020ST 2[%] -20F 1000fr no3d 0#0 (EAS)
if current_SW_short == 'VC14':
data1=re.search(r'ANG-(['+self.plane+'])\s*SET:\s*\[00453\]([0-2]+):\s*(GP|PP|)\s*(\d+)cm\s*(-?\d+)C\s*(-?\d+)R\s*(\d+)A\s*(\d+)T\s*(\d+)%\s*(-?\d+)F\s*(\d+)fr\s*(\d*?XT|-|)\s*(\d*?Um|-|)\s*3D:([NO,DR,DRLV,DSA,CARD]+).+',line)
else:
data1=re.search(r'ANG-(['+self.plane+'])\s*SET:\s*\[00453\]([0-2]+):\s*(GP|PP|)\s*(\d+)cm\s*(-?\d+)C\s*(-?\d+)R\s*(\d+)A\s*(\d+)ST\s*(\d+)\[?%\]?\s*(-?\d+)F\s*(\d+)fr\s*(\d*?XT|-|)\s*(\d*?Um|-|)\s*([a-zA-Z0-9]+)',line)
#print line
if data1!=None and exist_391==1:
exist_453=1
dap453+=float(data1.group(7))
scenetime453+=float(data1.group(8))
try:
dose453+=float(data.group(21))*float(data1.group(8))
current453+=float(data.group(13))*float(data1.group(8))
except:
print 'data391 not defined!'
##evtl. missing actual_OGP, weil 453 zu schnell...
if actual_OGP=='None':
k=0
temp_pulses=-1
#Text: (10.05.2014 10:57:12) ACU-B SET: [00130],0|fl_ab pressed, place: on table etc....
while lines[i+k].find('pressed,')==-1 and k<60:
#print lines[i+k]
mat12=re.search(r'No\. of SWR pulses\:\s*(\d+)',lines[i+k])
if mat12!=None:
temp_pulses= int(mat12.group(1))
plane_str_acu='ACU-'+self.plane
if (lines[i+k].find('[00169]')>-1 and lines[i+k].find(plane_str_acu)>-1 ):
#Text: (31.10.2013 17:09:03) ACU-A SET: [00169]Pid: 000002, Pname: FL Normal.(,0) #EAS
mat9=re.search(r'ACU-([A-B]) SET: \[00169\](?:\,0\||)Pid: ([0-9]+)\, Pname:\s*(.+)(?:\(\,0\)|)',lines[i+k])
if(mat9!=None):
if(self.plane==mat9.group(1)):
actual_OGP=mat9.group(3)
actual_OGP=actual_OGP.replace('(,0)','')
actual_OGP=actual_OGP.strip()
actual_OGP=actual_OGP.replace(';','.')
else:
if not IcConsMode:
print 'invalid [00169] entry: '+lines[i+k].strip()
actual_OGP='None'
k+=1
#test, ob Strahlungspulse gleich viel sind
if(data!=None):
if temp_pulses!=int(data.group(9)):
actual_OGP='None'
else:
actual_OGP='None'
else:
if not IcConsMode:
print 'invalid [00453] entry: '+line.strip()
exist_453=0
if event_time==False:
#reset flags and re results
exist_453=0
exist_391=0
exist_p453=0
exist_p391=0
acu_exist=0
dap453=0
dose453=0
current453=0
scenetime453=0
data_391p=None
data=None
data_391p=None
data1=None
preview=None
data_acu95=None
actual_OGP='None'
#generate event entry
if (acu_exist==1 and exist_453==1 and exist_391==1 and exist_p453==1 and self.plane==data.group(7) and exist_p391==1 and acu_frames==frames_391): # and service_flag==0 ):#and int(data.group(22),16)==ACU_ID): #correct plane & same ID
if not IcConsMode:
print self.events
print actual_OGP
review_SID.append(int(data1.group(4)))
review_cran.append(int(data1.group(5)))
review_rao.append(int(data1.group(6)))
try:
preview_SID.append(int(preview.group(4)))
preview_cran.append(int(preview.group(5)))
preview_rao.append(int(preview.group(6)))
except:
preview_SID.append(-1) #no preview
preview_cran.append(-1)
preview_rao.append(-1)
#es wird getestet, ob SID/cran/Rao-Werte von preview und review eines events übereinstimmen
if len(scu_T1)>0:
rev_table_pos=np.array([scu_T1[-1],scu_T2[-1],scu_T3[-1]])
else:
rev_table_pos=np.array([0,0,0])
if preview_SID[-1] == review_SID[-1]:
if preview_cran[-1] == review_cran[-1]:
if preview_rao[-1] == review_rao[-1] and np.linalg.norm(prev_table_pos-rev_table_pos)<0.01:
preview_review.append(1)
else:
preview_review.append(0)
else:
preview_review.append(0)
else:
preview_review.append(0)
#Arcing
num_arcing.append(len(arcing_time)) #gibt an, wieviele arcing-Ereignisse zu dem gegenwärtigen review-event gehören
self.myXEvent.arc_0x001A_frame.append('')
self.myXEvent.arc_0x001B_frame.append('')
self.myXEvent.arc_0x001C_frame.append('')
self.myXEvent.arc_0x001D_frame.append('')
self.myXEvent.arc_0x001E_frame.append('')
self.myXEvent.arc_0x0018_frame.append('')
self.myXEvent.arc_0x000A_frame.append('')
self.myXEvent.arc_0x000B_frame.append('')
self.myXEvent.arc_0x000C_frame.append('')
self.myXEvent.arc_0x0008_frame.append('')
self.myXEvent.arc_0x0007_frame.append('')
self.myXEvent.arc_0x0006_frame.append('')
self.myXEvent.arc_0x0005_frame.append('')
self.myXEvent.arc_0x0004_frame.append('')
self.myXEvent.arc_0x0003_frame.append('')
self.myXEvent.arc_0x0002_frame.append('')
self.myXEvent.arc_0x0001_frame.append('')
self.myXEvent.arc_0x0000_frame.append('')
self.myXEvent.arc_other_frame.append('')
if len(arcing_time) > 0:
for j in range(len(arcing_time)):
if arcing_type[j].rfind('0x001A')>-1:
self.myXEvent.arc_0x001A[self.events]+=1
self.myXEvent.arc_0x001A_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x001B')>-1:
self.myXEvent.arc_0x001B[self.events]+=1
self.myXEvent.arc_0x001B_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x001C')>-1:
self.myXEvent.arc_0x001C[self.events]+=1
self.myXEvent.arc_0x001C_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x001D')>-1:
self.myXEvent.arc_0x001D[self.events]+=1
self.myXEvent.arc_0x001D_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x001E')>-1:
self.myXEvent.arc_0x001E[self.events]+=1
self.myXEvent.arc_0x001E_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0018')>-1:
self.myXEvent.arc_0x0018[self.events]+=1
self.myXEvent.arc_0x0018_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x000A')>-1:
self.myXEvent.arc_0x000A[self.events]+=1
self.myXEvent.arc_0x000A_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x000B')>-1:
self.myXEvent.arc_0x000B[self.events]+=1
self.myXEvent.arc_0x000B_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x000C')>-1:
self.myXEvent.arc_0x000C[self.events]+=1
self.myXEvent.arc_0x000C_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0008')>-1:
self.myXEvent.arc_0x0008[self.events]+=1
self.myXEvent.arc_0x0008_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0007')>-1:
self.myXEvent.arc_0x0007[self.events]+=1
self.myXEvent.arc_0x0007_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0006')>-1:
self.myXEvent.arc_0x0006[self.events]+=1
self.myXEvent.arc_0x0006_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0005')>-1:
self.myXEvent.arc_0x0005[self.events]+=1
self.myXEvent.arc_0x0005_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0004')>-1:
self.myXEvent.arc_0x0004[self.events]+=1
self.myXEvent.arc_0x0004_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0003')>-1:
self.myXEvent.arc_0x0003[self.events]+=1
self.myXEvent.arc_0x0003_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0002')>-1:
self.myXEvent.arc_0x0002[self.events]+=1
self.myXEvent.arc_0x0002_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0001')>-1:
self.myXEvent.arc_0x0001[self.events]+=1
self.myXEvent.arc_0x0001_frame[self.events]+=arcing_frame[j]+'|'
elif arcing_type[j].rfind('0x0000')>-1:
self.myXEvent.arc_0x0000[self.events]+=1
self.myXEvent.arc_0x0000_frame[self.events]+=arcing_frame[j]+'|'
else:
self.myXEvent.arc_other[self.events]+=1
self.myXEvent.arc_other_frame[self.events]+=arcing_frame[j]+'|'
arcing_time=[]
arcing_type=[]
arcing_frame=[]
#T1 events due to arcing
num_T1_arcing.append(len(T1_arcing_time))
if len(T1_arcing_time) > 0:
for j in range(len(T1_arcing_time)):
T1_arcing_time_global.append(T1_arcing_time[0])
T1_arcing_time.remove(T1_arcing_time[0])
#Grid warnings
num_grid.append(len(grid_time)) #gibt an, wieviele grid warnings zu dem gegenwärtigen review-event gehören
self.myXEvent.grid_0x000A_frame.append('')
self.myXEvent.grid_0x0009_frame.append('')
self.myXEvent.grid_0x0008_frame.append('')
self.myXEvent.grid_0x0007_frame.append('')
self.myXEvent.grid_0x0006_frame.append('')
self.myXEvent.grid_0x0005_frame.append('')
self.myXEvent.grid_0x0004_frame.append('')
self.myXEvent.grid_0x0003_frame.append('')
self.myXEvent.grid_0x0002_frame.append('')
self.myXEvent.grid_0x0001_frame.append('')
self.myXEvent.grid_0x0000_frame.append('')
self.myXEvent.grid_other_frame.append('')
if len(grid_time) > 0:
for j in range(len(grid_time)):
if grid_type[j].rfind('0x000A')>-1:
self.myXEvent.grid_0x000A[self.events]+=1
self.myXEvent.grid_0x000A_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0009')>-1:
self.myXEvent.grid_0x0009[self.events]+=1
self.myXEvent.grid_0x0009_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0008')>-1:
self.myXEvent.grid_0x0008[self.events]+=1
self.myXEvent.grid_0x0008_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0007')>-1:
self.myXEvent.grid_0x0007[self.events]+=1
self.myXEvent.grid_0x0007_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0006')>-1:
self.myXEvent.grid_0x0006[self.events]+=1
self.myXEvent.grid_0x0006_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0005')>-1:
self.myXEvent.grid_0x0005[self.events]+=1
self.myXEvent.grid_0x0005_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0004')>-1:
self.myXEvent.grid_0x0004[self.events]+=1
self.myXEvent.grid_0x0004_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0003')>-1:
self.myXEvent.grid_0x0003[self.events]+=1
self.myXEvent.grid_0x0003_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0002')>-1:
self.myXEvent.grid_0x0002[self.events]+=1
self.myXEvent.grid_0x0002_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0001')>-1:
self.myXEvent.grid_0x0001[self.events]+=1
self.myXEvent.grid_0x0001_frame[self.events]+=grid_frame[j]+'|'
elif grid_type[j].rfind('0x0000')>-1:
self.myXEvent.grid_0x0000[self.events]+=1
self.myXEvent.grid_0x0000_frame[self.events]+=grid_frame[j]+'|'
else:
self.myXEvent.grid_other[self.events]+=1
self.myXEvent.grid_other_frame[self.events]+=grid_frame[j]+'|'
grid_time_global.append(grid_time[j]) #speichere die Zeit des grid-events
grid_type_global.append(grid_type[j]) #speichere den Typ des arcing-events ab
grid_time=[]
grid_type=[]
grid_frame=[]
#Soll-FD-Dosis
try:
self.myXEvent.soll_fd_dosis.append(int(data_391p.group(17)))
except:
self.myXEvent.soll_fd_dosis.append(-1)
# Date & time
thetimestr=data.group(4)+':'+data.group(5)+':'+data.group(6)+' '+data.group(1)+'.'+data.group(2)+'.'+data.group(3)
_time = data.group(3)+'-'+data.group(2)+'-'+data.group(1)+' '+data.group(4)+':'+data.group(5)+':'+data.group(6)
thetime=time.strptime(thetimestr,"%H:%M:%S %d.%m.%Y")
fl_time=time.mktime(thetime)
event_dates.append(datetime.datetime.fromtimestamp(time.mktime(thetime)))
Startzeit.append(_time)
Datum_array.append(data.group(1))
Time.append(fl_time)
Tag.append(data.group(1))
Monat.append(data.group(2))
Jahr.append(data.group(3))
Stunden.append(data.group(4))
Minuten.append(data.group(5))
Sekunden.append(data.group(6))
TIME.append(_time)
self.myXEvent.date[self.events]=fl_time
# Mode
if data.group(8) == '0002':
alternative_acquisition.append(1) #zählt die Anzzahl der alternative-acquisition-events
if(data.group(8)=='0001' or data.group(8)=='0002'): #Todo single Tag for Low Dose Acq.?
self.myXEvent.mode[self.events]=ord('A')
if data.group(8)=='0002':
self.myXEvent.alt_acq[self.events]=1
elif (data.group(8)=='0100'):
self.myXEvent.mode[self.events]=ord('F')
elif (data.group(8)=='0200'): #Biplane Fluoro
self.myXEvent.mode[self.events]=ord('F')
else:
self.myXEvent.mode[self.events]=ord('0')
#Soll-Szenenlaenge - nur Acq soll beruecksichtigt werden
if data.group(8) == '0001' or data.group(8) == '0002':
self.myXEvent.soll_Szenenlaenge.append( round(float(data_391p.group(10))/(float(data1.group(11))/100.0 ),2))
else:
self.myXEvent.soll_Szenenlaenge.append('600') #Fluoro 600s Sollszenenlaenge
self.myXEvent.ist_Szenenlaenge.append(float(data1.group(8))/1000.)
try:
self.myXEvent.soll_kV.append(float(data_391p.group(12)))
self.myXEvent.soll_mA.append(float(data_391p.group(13)))
self.myXEvent.soll_ms.append(float(data_391p.group(14)))
self.myXEvent.soll_WW.append(float(data_391p.group(11)))
except:
self.myXEvent.soll_kV.append(-1.)
self.myXEvent.soll_mA.append(-1.)
self.myXEvent.soll_ms.append(-1.)
self.myXEvent.soll_WW.append(-1.)
self.myXEvent.frames[self.events]=int(data.group(9))
self.myXEvent.was[self.events]=float(data.group(10))
self.myXEvent.wPawMode[self.events]=int(data.group(11))
self.myXEvent.biplane[self.events]=actual_biplane
self.myXEvent.voltage[self.events]=float(data.group(12))
self.myXEvent.current[self.events]=current453/scenetime453
self.myXEvent.time[self.events]=float(data.group(14))
if data.group(15)[-1]=='u':
self.myXEvent.mAs[self.events]=float(data.group(15)[:-1])
else:
self.myXEvent.mAs[self.events]=float(data.group(15)[:-1])*1000.
self.myXEvent.system_dose[self.events]=float(data.group(17))
self.myXEvent.filt[self.events]=int(data.group(18))
self.myXEvent.focus[self.events]=ord(data.group(19))
self.myXEvent.zoom[self.events]=int(data.group(20))
self.myXEvent.skindoserate[self.events]=dose453/scenetime453
self.myXEvent.index[self.events]=int(data.group(22),16)
#Axis DEV 1
idx=data.group(22)
if idx in act_axis_mode.keys() and idx in act_axis_resolution.keys():
self.myXEvent.axis_mode.append(act_axis_mode[idx])
del act_axis_mode[idx]
self.myXEvent.resolution.append(act_axis_resolution[idx])
del act_axis_resolution[idx]
else:
self.myXEvent.axis_mode.append('n a')
self.myXEvent.resolution.append('n a')
#from 453
if data1.group(3)=='GP':
self.myXEvent.gridpulse[self.events]=1 # grid on
else:
self.myXEvent.gridpulse[self.events]=0 #grid off
if current_SW_short[:-1] != 'VD1':
self.myXEvent.gridpulse[self.events]=-1 #not defined (no grid pulse in versions <VD)
try:
if data1.group(3)!=preview.group(3):
self.myXEvent.gridpulse[self.events]=-1 #grid error
except:
print "missing preview" #probably RM
try:
self.myXEvent.prevHU[self.events]=int(preview.group(7))
except:
self.myXEvent.prevHU[self.events]=-1
self.myXEvent.SID[self.events]=float(data1.group(4))
self.myXEvent.cran[self.events]=float(data1.group(5))
self.myXEvent.rao[self.events]=float(data1.group(6))
self.myXEvent.DAP[self.events]=dap453 #float(data1.group(7))
self.myXEvent.HU[self.events]=int(data1.group(9))
self.myXEvent.offset[self.events]=float(data1.group(10))
if(self.myXEvent.offset[self.events]>32767):
self.myXEvent.offset[self.events]=self.myXEvent.offset[self.events]-65536
self.myXEvent.frequency[self.events]=float(data1.group(11))/100.0
if current_SW_short == 'VC14':
self.myXEvent._3Dmode.append(data1.group(14))
if self.myXEvent._3Dmode[self.events]=='NO' or self.myXEvent._3Dmode[self.events]=='N':
self.myXEvent._3Dmode[self.events]='no3d'
else: #VC20 ++
self.myXEvent._3Dmode.append(data1.group(14)) #todo XT Um 3#3 auswerten in VC20
if self.myXEvent._3Dmode[self.events]=='no3' or self.myXEvent._3Dmode[self.events]=='no' or self.myXEvent._3Dmode[self.events]=='n' : #because of problem with line length from ANG
self.myXEvent._3Dmode[self.events]='no3d'
if self.myXEvent._3Dmode[self.events]=='no3d':
self.myXEvent.scenelength[self.events]=float(data1.group(8))
else:
self.myXEvent.scenelength[self.events]=scenetime453 #self.myXEvent.frames[self.events]/self.myXEvent.frequency[self.events]*1000. #evtl 0095 ACU besser oder summe beider 453?
#from SYC 45 (new patient)
if(new_pat==1):
new_pat_time=fl_time
self.myXEvent.pat_in_time.append(new_pat_time)
if(patient_number>0):
self.myXEvent.pat_time.append((old_time-self.myXEvent.pat_in_time[patient_number-1])/60.0) #in Minuten Todo: time of last patient is missing?!
if(old_time!=0):
self.myXEvent.pat_out_time.append(old_time)
self.myXEvent.pat_dap.append(temp_pat_dap)
temp_pat_dap=0
self.myXEvent.pat_skindose.append(temp_pat_skindose)
temp_pat_skindose=0
patient_number=patient_number+1 #Todo: z.B. kein neuer Patient wenn keine Strahlungevents aufgetreten sind
self.myXEvent.pat_idx.append(self.events)
new_pat=0
self.pat_position.append(int(new_pat_position))
temp_pat_dap +=dap453
temp_pat_skindose+=self.myXEvent.scenelength[self.events]/1000.*self.myXEvent.skindoserate[self.events]
self.myXEvent.pat_number[self.events]=patient_number
#time_between_xrays
if self.events>0:
time_between_xray.append(self.myXEvent.date[self.events]-self.myXEvent.date[self.events-1]-self.myXEvent.scenelength[self.events]/1000.)
else:
time_between_xray.append(-1.)
#Program Number; from SYC 0056 select program
if(self.myXEvent.mode[self.events]==ord('A')):
self.myXEvent.p1[self.events]=prog1A
self.myXEvent.p2[self.events]=prog2A
else:
self.myXEvent.p1[self.events]=prog1F
self.myXEvent.p2[self.events]=prog2F
#from AX_ACU 2097
self.myXEvent.OGP.append(actual_OGP.rstrip())
#from ACU 0095
self.myXEvent.Bsig[self.events]=int(data_acu95.group(9))
self.myXEvent.FDmode.append(data_acu95.group(10))
self.myXEvent.Mfield[self.events]=int(data_acu95.group(12),16)
#from AX_SCU 221, 222, 224 (Table Positions, C-Arm Rotations, Robot angles)
if len(scu_T1)==0:
self.myXEvent.scu_T1[self.events]=8888.
self.myXEvent.scu_base_rot[self.events]=8888.
self.myXEvent.scu_table_rot[self.events]=8888.
self.myXEvent.scu_table_tilt[self.events]=8888.
self.myXEvent.scu_table_cradle[self.events]=8888.
self.myXEvent.scu_carm_rot[self.events]=8888.
self.myXEvent.scu_carm_orb[self.events]=8888.
self.myXEvent.alpha_orb[self.events]=8888.
self.myXEvent.alpha_xray[self.events]=8888.
self.myXEvent.table_height[self.events]=8888.
self.myXEvent.gamma[self.events]=8888.
else:
self.myXEvent.scu_T1[self.events]=scu_T1[-1]
self.myXEvent.scu_T2[self.events]=scu_T2[-1]
self.myXEvent.scu_T3[self.events]=scu_T3[-1]
self.myXEvent.table_height[self.events]= (scu_T1[-1]-106.) #wrong for ROS and MP!!!
self.myXEvent.scu_base_rot[self.events]=scu_base_rot[-1]
self.myXEvent.scu_table_rot[self.events]=scu_table_rot[-1]
self.myXEvent.scu_table_tilt[self.events]=scu_table_tilt[-1]
self.myXEvent.scu_table_cradle[self.events]=scu_table_cradle[-1]
self.myXEvent.scu_carm_rot[self.events]=scu_carm_rot[-1]
self.myXEvent.scu_carm_orb[self.events]=scu_carm_orb[-1]
if self.myXEvent.SystemType=='Robot Stand':
if len (alpha_orb_rob)>0:
self.myXEvent.alpha_orb[self.events]=alpha_orb_rob[-1]
else:
self.myXEvent.alpha_orb[self.events]=8888.
self.myXEvent.gamma[self.events]=8888.
else:
self.myXEvent.alpha_orb[self.events]=alpha_orb[-1]
#Set (0,0,0) to ISO centrum if C-arm is in headside position
# should be table pos (T1=Tablelift=106, T2=TableLong=75,
dist_focus_iso=self.myXEvent.IR+15. #75 cm oder 78.5 cm oder frei bei ROS
table_object_distance_z=18. #TOD aus system.caf (Table Object Distance)
cran_rad=self.myXEvent.cran[self.events]*np.pi/180.
rao_rad=self.myXEvent.rao[self.events]*np.pi/180.
table_floor_distance=106. #Tisch im Isozentrum
#Heart pos vector
#A: x(l,m)=l*e_x+m*e_y+e_z*(Tischpos_z+10cm)
heart_pos=np.matrix([scu_T2[-1]-78.5,scu_T3[-1],scu_T1[-1]-table_floor_distance+table_object_distance_z])
heart_pos2=np.matrix([scu_T2[-1]-78.5,scu_T3[-1],scu_T1[-1]-table_floor_distance])
heart_pos_z=heart_pos[0,2]
#X-ray Gerade:
#tube_FD_vec: y(k)= e_z*ISO_z-dist(focus,iso)*tube_xray_rot_v +k*tube_xray_rot_v
tube_xray_vec=np.matrix([sin(cran_rad) ,
cos(cran_rad)*sin(rao_rad),
cos(cran_rad)*cos(rao_rad)])
tube_xray_vec_z=tube_xray_vec[0,2]
#Ursprung Strahlungsvektor
tube_focal_spot_pos= -dist_focus_iso*tube_xray_vec
tube_focal_spot_pos_z=tube_focal_spot_pos[0,2]
self.myXEvent.tube_focal_spot_pos_table.append((heart_pos2,tube_xray_vec))
#abs_vec=np.linalg.norm(tube_xray_vec,2)
#min Abstand Heart zu X-ray
#dist=np.linalg.norm(np.cross(tube_xray_vec,tube_focal_spot_pos-heart_pos),2)
#SOD
switch_angle=50
if abs(self.myXEvent.cran[self.events])>switch_angle or abs(self.myXEvent.rao[self.events])>switch_angle:
SOD=dist_focus_iso
else:
SOD=(-tube_focal_spot_pos_z+heart_pos_z)/tube_xray_vec_z
gamma=scu_sid[-1]/SOD
self.myXEvent.gamma[self.events]=gamma #Vergroesserungsfaktor
self.myXEvent.SOD[self.events]=SOD
#--------BE-----------
if(self.myXEvent.mode[self.events]==ord('F')):
weight_factor=1./30.
else: #Acq.
weight_factor=1./2.
if(self.myXEvent.focus[self.events]==ord('S')):
F1_add=self.myXEvent.scenelength[self.events]/1000.*weight_factor
F2_add=0
FG_add=0
elif(self.myXEvent.focus[self.events]==ord('L')):
F1_add=0
F2_add=self.myXEvent.scenelength[self.events]/1000.*weight_factor
FG_add=0
else: #FG
F1_add=0
F2_add=0
FG_add=self.myXEvent.scenelength[self.events]/1000.*weight_factor
self.myXEvent.BE_F1[self.events]=F1_add
self.myXEvent.BE_F2[self.events]=F2_add
self.myXEvent.BE_FG[self.events]=FG_add
self.myXEvent.BE_total[self.events]=F1_add+F2_add+FG_add
#prepare next event
ACU_ID=-1
#print 'event: ',self.events
self.events=self.events+1
if self.events>=self.myXEvent.range-1:
print "Too many X-ray events to analyse in given period! Stopping with analysis at current event!"
max_iter_reached=True
break
old_time=fl_time #for calculation of duration of intervention last event<=>old_time
#reset flags and re results
exist_453=0
exist_391=0
exist_p453=0
exist_p391=0
acu_exist=0
dap453=0
dose453=0
current453=0
scenetime453=0
data_391p=None
data=None
data_391p=None
data1=None
preview=None
data_acu95=None
actual_OGP='None'
actual_biplane=0
else:
1#print 'event '+data.group(22)+'i skipped!'
#Abschluss Patientenzeiten
if(self.myXEvent.pat_in_time.__len__()>0):
self.myXEvent.pat_time.append((old_time-self.myXEvent.pat_in_time[patient_number-1])/60.0) #in Minuten
self.myXEvent.pat_out_time.append(old_time)
#Abschluss Cooling time (no Switch off at the end...)
if len(cooling_state)>0:
if cooling_state[-1]==1:
idx1=len(envtime2d)-1
idx2a=bisect.bisect_left(envtime2d,dateutil.parser.parse(cooling_time[-1]) )
if idx2a==len(envtime2d):
idx2a-=1
idx2b=bisect.bisect_right(envtime2d,dateutil.parser.parse(cooling_time[-1]) )
if idx2b==len(envtime2d):
idx2b-=1
try:
if envtime2d[idx2a]-dateutil.parser.parse(cool_time)<envtime2d[idx2b]-dateutil.parser.parse(cool_time):
idx2=idx2a
else:
idx2=idx2b
except:
idx2=idx2b
cool_duration=idx1-idx2
cooling_ontime.append(cool_duration*60.) #in seconds
self.myXEvent.pat_dap.append(temp_pat_dap)
self.myXEvent.pat_skindose.append(temp_pat_skindose)
self.myXEvent.pat_idx.append(self.events)
if self.myXEvent.SW==[]:
self.myXEvent.SW.append('n.a.')
#------------------------------------------------------------------
def calc_derived_measurements(self):
#---change scenelength because of large deviations of value from 453 telegram ----- vari frame rate???
#for i in range(len(preview_SID)):
# if self.myXEvent._3Dmode[i]=='no3d':
# self.myXEvent.scenelength[i]=self.myXEvent.frames[i]/self.myXEvent.frequency[i]*1000.
#----Skindose from scene/[µGy]----
self.myXEvent.skindose=self.myXEvent.scenelength/1000.*self.myXEvent.skindoserate
#----maxArea \[cm²]----- for recognition of halftransparent at IR
zooms_large_FD=[48, 42, 32, 22, 16, 11]; #Diagonale in [cm]
zooms_small_FD=[25, 20, 16, 10];
zooms_midsize_FD=[39,32,26,20,16,10];
for i in range(len(preview_SID)):
if(self.myXEvent.FDtype=='4700' or self.myXEvent.FDtype=='3040'):
#temp1=float(zooms_large_FD[1+int(self.myXEvent.zoom[i])]*zooms_large_FD[1+int(self.myXEvent.zoom[i])])
temp1=float(zooms_large_FD[int(self.myXEvent.zoom[i])]*zooms_large_FD[int(self.myXEvent.zoom[i])])
temp2=(self.myXEvent.IR/self.myXEvent.SID[i])*(self.myXEvent.IR/self.myXEvent.SID[i]) # Eingangsfläche 15 cm über Tisch in cm²
self.myXEvent.maxarea[i]=temp1/2.0*temp2
if(self.myXEvent.zoom[i]==0):
self.myXEvent.maxarea[i]=29.6*38.2*(self.myXEvent.IR/self.myXEvent.SID[i])*(self.myXEvent.IR/self.myXEvent.SID[i]);
elif (self.myXEvent.FDtype=='4800'):
self.myXEvent.maxarea[i]=zooms_small_FD[0+int(self.myXEvent.zoom[i])]*zooms_small_FD[0+int(self.myXEvent.zoom[i])]/2*(self.myXEvent.IR/self.myXEvent.SID[i])*(self.myXEvent.IR/self.myXEvent.SID[i]); # Eingangsflaeche 15 cm ueber Tisch in cm²
else: #self.myXEvent.FDtype=='Midsize Type 2a/2b Detector' !!!Achtung EAS: Midsize hat andere evtl. Groesse
self.myXEvent.maxarea[i]=zooms_midsize_FD[0+int(self.myXEvent.zoom[i])]*zooms_midsize_FD[0+int(self.myXEvent.zoom[i])]/2*(self.myXEvent.IR/self.myXEvent.SID[i])*(self.myXEvent.IR/self.myXEvent.SID[i]); # Eingangsflaeche 15 cm ueber Tisch in cm²
if(self.myXEvent.zoom[i]==0):
self.myXEvent.maxarea[i]=1792.0*1632*0.160*0.160*(self.myXEvent.IR/self.myXEvent.SID[i])*(self.myXEvent.IR/self.myXEvent.SID[i])/100.; #/100. wg mm²->cm²
#----Area (from Collimator params)----
self.myXEvent.area=100.*self.myXEvent.DAP/self.myXEvent.skindose #Achtung Division durch Null kann vorkommen (fehlerhafte Skindosewerte!)
self.myXEvent.area[np.isnan(self.myXEvent.area)]=0
self.myXEvent.area[np.isinf(self.myXEvent.area)]=0
#----Dutycycle----
self.myXEvent.dutycycle=self.myXEvent.time*self.myXEvent.frequency/1000.0
#----Dose efficiency--
cu_atten_fac=self.kV_Cu_attenuation_factor() #calculation of kV-specific Cu-attenuation Vector
#DoseEff=Skindoserate/mA/ms/Freq*kV_Dose(125)/kV_Dose(kV)/Cu_atten(kV,Cu)*SID_factor
#self.myXEvent.dose_per_mAs=self.myXEvent.skindose/self.myXEvent.current/self.myXEvent.time/self.myXEvent.frames/self.kV_dose_factor(self.myXEvent.voltage)*self.kV_dose_factor(125)*cu_atten_fac*self.myXEvent.SID_factor*1000.0; #1000 wegen ms->s
self.myXEvent.dose_per_mAs=self.myXEvent.skindose/self.myXEvent.mAs/self.myXEvent.frames*cu_atten_fac*self.myXEvent.SID_factor*1000.0;
#org###self.myXEvent.dose_per_mAs=self.myXEvent.skindose/self.myXEvent.current/self.myXEvent.time/self.myXEvent.frames*cu_atten_fac*self.myXEvent.SID_factor*1000.0; #1000 wegen ms->s
#self.myXEvent.dose_per_mAs=self.myXEvent.skindoserate/self.myXEvent.current/self.myXEvent.time/self.myXEvent.frequency/self.kV_dose_factor(self.myXEvent.voltage)*self.kV_dose_factor(125)/cu_atten_fac*self.myXEvent.SID_factor*1000.0; #1000 wegen ms->s
#----Physical Dose----
ZDF_Large=[0.5,0.5,0.71,1,1.41,2];
ZDF_Small=[0.85,1.1,1.4,2.2];
ZDF_Midsize=[0.57,0.70,0.84,1.1,1.4,2.2];
for i in range(len(preview_SID)):
if(self.myXEvent.FDtype=='4700' or self.myXEvent.FDtype=='3040'): #large FD
self.myXEvent.SysDose_with_ZDF[i]=self.myXEvent.system_dose[i]*ZDF_Large[int(self.myXEvent.zoom[i])]
elif(self.myXEvent.FDtype=='4800'): #large FD
self.myXEvent.SysDose_with_ZDF[i]=self.myXEvent.system_dose[i]*ZDF_Small[int(self.myXEvent.zoom[i])]
else: #Midisze
self.myXEvent.SysDose_with_ZDF[i]=self.myXEvent.system_dose[i]*ZDF_Midsize[int(self.myXEvent.zoom[i])]
#-----10R Limit-----(only Fluoro), is set to 0 for Acq.
#SID_factor ist für Umrechung Skindose von IR auf 100cm
dist_factor=self.myXEvent.SID_factor*(100./(self.myXEvent.SID-34.))*(100./(self.myXEvent.SID-34.))
self.myXEvent._10Rlimit=self.myXEvent.skindoserate*(self.myXEvent.mode==70)*60.0/1000.0*dist_factor/8.7 #in R/min, 1R=8.7mGy (skindoserate in [µGy/s])
#anpassen von environment log zeiten an strahlzeiten
self.myXEvent.act_tube_freq=zeros(self.events) #defaults =0
self.myXEvent.driv_tube_freq=zeros(self.events)
self.myXEvent.driv_current=zeros(self.events)
self.myXEvent.oil_temp=zeros(self.events)
if(len(self.AuswahlEnvLogs)>0 and self.cb_EnvLog.GetValue() and self.events>0):
#take shortest timearray to avoid illegal array access
if len(self.envtime)>0:
if len(self.envtime3)>0: #VD10+
if len(self.envtime)<len(self.envtime3) and len(self.envtime)<len(self.envtime2):
temp_date=[dateutil.parser.parse(x) for x in self.envtime]
elif len(self.envtime2)<len(self.envtime3) and len(self.envtime2)<len(self.envtime):
temp_date=[dateutil.parser.parse(x) for x in self.envtime2]
else:
temp_date=[dateutil.parser.parse(x) for x in self.envtime3]
else: #
if len(self.envtime)<len(self.envtime2):
temp_date=[dateutil.parser.parse(x) for x in self.envtime]
else:
temp_date=[dateutil.parser.parse(x) for x in self.envtime2]
if len(self.t0_time)>0:
temp_date2=[dateutil.parser.parse(x) for x in self.t0_time]
for i in range(self.events):
itime=dateutil.parser.parse(TIME[i])
if len(self.envtime)>0:
idx=bisect_left(temp_date,itime)
if idx==len(temp_date):
idx-=1
try:
if abs(temp_date[idx]-itime)<datetime.timedelta(minutes=1):
self.myXEvent.act_tube_freq[i]=self.act_tube_freq[idx]
self.myXEvent.driv_tube_freq[i]=self.driv_tube_freq[idx]
self.myXEvent.driv_current[i]=self.driv_current[idx]
else: #too much time in between
self.myXEvent.act_tube_freq[i]=-1
self.myXEvent.driv_tube_freq[i]=-1
self.myXEvent.driv_current[i]=-1
except:
1
else:
self.myXEvent.act_tube_freq[i]=-1
self.myXEvent.driv_tube_freq[i]=-1
self.myXEvent.driv_current[i]=-1
if len(self.t0_time)>0: #not available for Megalix in VC21, VC14; VD11???
idx2=bisect_left(temp_date2,itime)
if idx2==len(temp_date2):
idx2-=1
if abs(temp_date2[idx2]-itime)<datetime.timedelta(minutes=2):
self.myXEvent.oil_temp[i]=self.t0_temp[idx2]
else:
self.myXEvent.oil_temp[i]=-1
else:
self.myXEvent.oil_temp[i]=-1
###
#replace Xray parameters in arcing events with corrupted ANG entries
for i in range(len(arcing_time_global)):
if arcing_idx_global[i]!=0:
if int(arcing_idx_global[i],16) in self.myXEvent.index:
i2=np.where(self.myXEvent.index ==int(arcing_idx_global[i],16))[0][0] #number of xevent
arc_idx=[j for j, x in enumerate(arcing_idx_global) if x == arcing_idx_global[i]] #list of arc indices with same xray id
for k in arc_idx:
arcing_kV_global[k]=self.myXEvent.voltage[i2]
arcing_mA_global[k]=self.myXEvent.current[i2]
arcing_ms_global[k]=self.myXEvent.time[i2]
arcing_ogp_global[k]=self.myXEvent.OGP[i2]
###################
## emitter temperature and tungsten evaporation rate
#for i in range(len(preview_SID)):
# self.heating_current[i]=4
#self.emitter_temp=numpy.zeros(self.range)
#self.tungst_evaporation_rate=numpy.zeros(self.range)
self.calc_heating_current_emitter_temp_tungst_eva_rate()
#------------------------------------------------------------------
def calc_heating_current_emitter_temp_tungst_eva_rate(self):
prom_test = False
if (self.myXEvent.tubetype==2 and self.myXEvent.numFoken==3): #3F Gigalix
spec_tubeprom_filename="g253685_specific.xml"
elif (self.myXEvent.tubetype==2 and self.myXEvent.numFoken==2): #2F Gigalix
spec_tubeprom_filename="g4086_specific.xml"
elif (self.myXEvent.tubetype==1 and self.myXEvent.numFoken==2): #2F Megalix Cat+
spec_tubeprom_filename="m4090_specific_Draft02.xml"
elif (self.myXEvent.tubetype==1 and self.myXEvent.numFoken==3): #3F Megalix Cat+
spec_tubeprom_filename="m204080_specific_Draft_Olli.xml"
else:
prom_test = False
if prom_test ==True:
prom_return = parseXMLTubeProm_special(self.myXEvent.numFoken,spec_tubeprom_filename)
if prom_return==False:
prom_test=False
else:
prom_test=True
kVs =prom_return[0]
tube_currents =prom_return[1]
heating_currents =prom_return[2]
#F1
kVs_F1=np.array(kVs['small'])
tube_currents_F1=np.array(tube_currents['small']) # in [V]
heating_currents_F1=np.array(heating_currents['small']) # in [0.1 mA]
heating_currents_F1=heating_currents_F1.reshape([1,-1])[0] # in [0.1 mA]
#F2
kVs_F2=np.array(kVs['large'])
tube_currents_F2=np.array(tube_currents['large'])
heating_currents_F2=np.array(heating_currents['large'])
heating_currents_F2=heating_currents_F2.reshape([1,-1])[0]
#FG
if self.myXEvent.numFoken==3:
kVs_FG=np.array(kVs['micro'])
tube_currents_FG=np.array(tube_currents['micro'])
heating_currents_FG=np.array(heating_currents['micro'])
heating_currents_FG=heating_currents_FG.reshape([1,-1])[0]
if prom_test:
for i in range(self.events):
if self.myXEvent.focus[i]==ord('S'):
self.myXEvent.heating_current[i]=self.my_linear_interpol2d(kVs_F1,tube_currents_F1,heating_currents_F1,self.myXEvent.voltage[i]*1000,self.myXEvent.current[i]*10.)/10.
elif self.myXEvent.focus[i]==ord('L'):
self.myXEvent.heating_current[i]=self.my_linear_interpol2d(kVs_F2,tube_currents_F2,heating_currents_F2,self.myXEvent.voltage[i]*1000,self.myXEvent.current[i]*10.)/10.
else:
self.myXEvent.heating_current[i]=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,self.myXEvent.voltage[i]*1000,self.myXEvent.current[i]*10.)/10.
self.myXEvent.emitter_temp[i]=self.get_filament_temp(self.myXEvent.heating_current[i])
self.myXEvent.tungst_evaporation_rate[i]=self.get_evap_rate(self.myXEvent.emitter_temp[i])
self.myXEvent.tungst_thickness[i]=self.get_evap_rate(self.myXEvent.emitter_temp[i])*self.myXEvent.scenelength[i]/60./60./1000.
return
#------------------------------------------------------------------
def my_linear_interpol2d(self,x_arr,y_arr,z_values,x,y):
if x<min(x_arr):
x=min(x_arr)
if x>max(x_arr):
x=max(x_arr)
if y<min(y_arr):
y=min(y_arr)
if y>max(y_arr):
y=max(y_arr)
x_0_idx=min(range(len(x_arr)), key=lambda i: abs(x_arr[i]-x))
x_0=x_arr[x_0_idx]
if x_0<x or (x_0==x and x==min(x_arr)):
x_1_idx=x_0_idx+1
x_1=x_arr[x_1_idx]
else:
x_1_idx=x_0_idx-1
x_1=x_arr[x_1_idx]
y_0_idx=min(range(len(y_arr)), key=lambda i: abs(y_arr[i]-y))
y_0=y_arr[y_0_idx]
if y_0<y or (y_0==y and y==min(y_arr)):
y_1_idx=y_0_idx+1
y_1=y_arr[y_1_idx]
else:
y_1_idx=y_0_idx-1
y_1=y_arr[y_1_idx]
z_00_idx=x_0_idx+y_0_idx*len(x_arr)
z_10_idx=x_1_idx+y_0_idx*len(x_arr)
z_01_idx=x_0_idx+y_1_idx*len(x_arr)
z_11_idx=x_1_idx+y_1_idx*len(x_arr)
z_00=float(z_values[z_00_idx])
z_10=float(z_values[z_10_idx])
z_01=float(z_values[z_01_idx])
z_11=float(z_values[z_11_idx])
z_m0=(z_00-z_10)/(float(x_0)-float(x_1))*(x-float(x_0))+z_00
z_m1=(z_01-z_11)/(float(x_0)-float(x_1))*(x-float(x_0))+z_01
z_mm=(z_m0-z_m1)/(float(y_0)-float(y_1))*(y-float(y_0))+z_m0
return z_mm
#------------------------------------------------------------------
def my_linear_interpol1d(self,x_arr,z_values,x):
if x<min(x_arr):
x=min(x_arr)
if x>max(x_arr):
x=max(x_arr)
x_0_idx=min(range(len(x_arr)), key=lambda i: abs(x_arr[i]-x))
x_0=x_arr[x_0_idx]
if x_0<x or (x_0==x and x==min(x_arr)):
x_1_idx=x_0_idx+1
x_1=x_arr[x_1_idx]
else:
x_1_idx=x_0_idx-1
x_1=x_arr[x_1_idx]
z_00_idx=x_0_idx
z_10_idx=x_1_idx
z_00=float(z_values[z_00_idx])
z_10=float(z_values[z_10_idx])
z_mm=(z_00-z_10)/(float(x_0)-float(x_1))*(x-float(x_0))+z_00
return z_mm
#------------------------------------------------------------------
def get_filament_temp(self,current): #in [mA]
return (2550.-2200.)/900.*(current-4200.)+2200. #aus powerpoint "Zusammenfassung FG Problem; July 2013" - Temperaturabhaengigkeit nur für Wendel (220um Dicke) FG richtig!!!
#------------------------------------------------------------------
def get_filament_heat_current(self,temperature): #in [mA]
return (temperature-2200.)*900/(2550.-2200.)+4200. #aus powerpoint "Zusammenfassung FG Problem; July 2013" - Temperaturabhaengigkeit nur für Wendel (220um Dicke) FG richtig!!!
#------------------------------------------------------------------
def get_evap_rate(self,temp): #in [µm/h]
return 1.0e-17*math.exp(0.0147*temp) #aus powerpoint "Zusammenfassung FG Problem; July 2013" - Temperaturabhaengigkeit nur für Wendel (220um Dicke) FG richtig!!!???
#dortige Quelle: Handbook of Chemistry and Physics 65. Auflage
#------------------------------------------------------------------
def calc_power_vs_prom(self):
#Test vs Tube Prom (Attention: kV, ms, mA Values in ANG review are mean values
prom_test = True
if (self.myXEvent.tubetype==2 and self.myXEvent.numFoken==3): #3F Gigalix
tubeprom_filename="g253685.xml"
elif (self.myXEvent.tubetype==2 and self.myXEvent.numFoken==2): #2F Gigalix
tubeprom_filename="g4086.xml"
elif (self.myXEvent.tubetype==1 and self.myXEvent.numFoken==2): #2F Megalix Cat+
tubeprom_filename="m4090_Draft02.xml"
elif (self.myXEvent.tubetype==1 and self.myXEvent.numFoken==3): #3F Megalix Cat+
tubeprom_filename="m204080_Draft_Olli.xml"
else:
prom_test = False
if prom_test ==True:
prom_return = parseXMLTubeProm(self.myXEvent.numFoken,tubeprom_filename)
if prom_return==False:
prom_test=False
else:
prom_test=True
self.SerialLoadTable200=prom_return[0]
self.SerialLoadTable=prom_return[1]
self.myDutyCycle=prom_return[2]
self.mySceneTime=prom_return[3]
self.PulseDuration=prom_return[4]
self.ConstantLoad=prom_return[5]
self.xrayVoltage=prom_return[6]
self.maxCurrAcq=prom_return[7]
self.maxCurrFluoro=prom_return[8]
for i in range(self.events):
if prom_test:
dutycycle_soll=self.myXEvent.dutycycle[i]*self.myXEvent.soll_ms[i]/self.myXEvent.time[i]
maxCurrSerialLoad_Istzeit =self.calcStromSerie(self.myXEvent.dutycycle[i]*100., self.myXEvent.scenelength[i]/1000. , self.myXEvent.focus[i])/self.myXEvent.voltage[i]*1000.
if self.myXEvent.time[i]==0:
dutycycle_soll=0
try:
maxCurrSerialLoad_Sollzeit =self.calcStromSerie(dutycycle_soll*100. , float(self.myXEvent.soll_Szenenlaenge[i]), self.myXEvent.focus[i])/self.myXEvent.soll_kV[i]*1000.
except:
blubb=1
cooling_pow=self.get_power_from_HU(self.myXEvent.prevHU[i])
cooling_pow=max(200,cooling_pow) #minimum 200W = 10%HU
if EA_IC!='':
maxCurrSerialLoad_dyn=self.calcStromSerieDyn(self.myXEvent.dutycycle[i]*100., self.myXEvent.scenelength[i]/1000. , self.myXEvent.focus[i],cooling_pow )/self.myXEvent.voltage[i]*1000.
maxCurrDurchgriff_Prev=self.calcStromDurchgriff(self.myXEvent.soll_kV[i],self.myXEvent.mode[i], self.myXEvent.focus[i]) #Soll
maxCurrDurchgriff_Rev=self.calcStromDurchgriff(self.myXEvent.voltage[i],self.myXEvent.mode[i], self.myXEvent.focus[i]) #Ist
if (self.myXEvent.frequency[i]==0.01): #ConstantLoad/Single Shot
maxCurrSerialLoad_Istzeit=self.calcConstantLoad(self.myXEvent.time[i],self.myXEvent.focus[i])/self.myXEvent.voltage[i]*1000.
maxCurrSerialLoad_Sollzeit=self.calcConstantLoad(self.myXEvent.soll_ms[i],self.myXEvent.focus[i])/self.myXEvent.soll_kV[i]*1000.
self.myXEvent.maxPower_Sollzeit.append(min(maxCurrDurchgriff_Prev,maxCurrSerialLoad_Sollzeit)*self.myXEvent.soll_kV[i]/1000.) #correct serial load table is chosen in fuction internaly
self.myXEvent.maxPower_Istzeit.append(min(maxCurrDurchgriff_Rev,maxCurrSerialLoad_Istzeit)*self.myXEvent.voltage[i]/1000.)
self.myXEvent.maxCurrentRev_punchthrough[i]=maxCurrDurchgriff_Rev
self.myXEvent.maxCurrentPrev.append(min(maxCurrDurchgriff_Prev,maxCurrSerialLoad_Sollzeit)) #max Preview Current
self.myXEvent.maxCurrentRev.append(min(maxCurrDurchgriff_Rev,maxCurrSerialLoad_Istzeit)) #max Review Current
if EA_IC!='':
self.myXEvent.maxPowerdyn.append(min(maxCurrDurchgriff_Rev,maxCurrSerialLoad_dyn)*self.myXEvent.voltage[i]/1000.) #Achtung Fluoro limit Durchgriff 250mA!!!
else:
self.myXEvent.maxPower_Sollzeit.append(-1)
self.myXEvent.maxPower_Istzeit.append(-1)
self.myXEvent.maxCurrentPrev.append(-1)
self.myXEvent.maxCurrentRev.append(-1)
self.myXEvent.maxPowerdyn.append(-1)
#------------------------------------------------------------------
def extract_ivs_hw_info(self):
tab=self.notebook.GetSelection()
self.sys_model='n a'
self.gpu_model=[]
if tab==3:#tab==1,2?
if len (self.AuswahlIVS_Systemlog)>0:
last_ivs_file=self.AuswahlIVS_Systemlog[-1]
try:
zf = zipfile.ZipFile(self.AuswahlIVS_Systemlog_dict[last_ivs_file,'zipfile'])
fp = zf.open(self.AuswahlIVS_Systemlog_dict[(last_ivs_file,'fullname')])
ivs_txt=fp.readlines()
fp.close()
for line in ivs_txt:
# System model: 0402000000
dd=re.search(r'System model: (.+)',line.strip())
if dd!=None:
self.sys_model=dd.group(1)
dd=re.search(r'Video processor: (.+)',line.strip())
if dd!=None:
self.gpu_model.append(dd.group(1))
if self.gpu_model==[]:
self.gpu_model.append('n a')
return True
except:
print 'error during ivs syslog analysis'
self.gpu_model.append('n a')
return False
#------------------------------------------------------------------
def extract_scu_caf_info(self):
tab=self.notebook.GetSelection()
scu_dat='n a'
if tab==3:#tab==1,2?
if len (self.Auswahl_scu_caf)>0:
last_scu_caf=self.Auswahl_scu_caf[-1]
try:
zf = zipfile.ZipFile(self.Auswahl_scu_caf_dict[last_scu_caf,'zipfile'])
fp = zf.open(self.Auswahl_scu_caf_dict[(last_scu_caf,'fullname')])
scu_caf_txt=fp.readlines()
fp.close()
for line in scu_caf_txt:
if line.find('Manual Table Top panning without pressing TCM')>-1:
if line.find('Yes')>-1: scu_dat='Yes'
elif line.find('No')>-1: scu_dat='No'
else: scu_dat='n a'
except:
print 'error during scu.caf analysis'
return scu_dat
#------------------------------------------------------------------
def extract_examsets(self):
tab=self.notebook.GetSelection()
ret=True
examset_txt=u''
old_examset_txt=u''
do_comparison=False
old_set_acq=set([])
old_set_fl=set([])
old_set_rm=set([])
old_set_alt=set([])
self.ACQ_set={}
self.FL_set={}
self.RM_set={}
self.ALT_set={}
self.ogp_del={}
self.ogp_new={}
self.ogp_change={}
self.ogp_diff={}
if len(self.AuswahlExamSet)>0 and (tab==3 or tab==0):
for exam_file in self.AuswahlExamSet:
#print exam_file
try:
if tab==0:
fp=open(exam_file, 'r')
#examset_txt=fp.read()
#fp=codecs.open(exam_file, "r", "utf-8")
examset_txt=fp.read()
fp.close()
elif tab==3:
zf = zipfile.ZipFile(self.AuswahlExamSet_dict[exam_file,'zipfile'])
fp = zf.open(self.AuswahlExamSet_dict[(exam_file,'fullname')])
examset_txt=fp.read()
fp.close()
init_examset=False
curr_examset_date=exam_file[9:19]
if exam_file==self.AuswahlExamSet[0]:init_examset=True
if examset_txt!='':
#if exam_file==self.AuswahlExamSet[0]:old_examset_txt=examset_txt
do_comparison=not self.examsets_identical(old_examset_txt,examset_txt)
old_examset_txt=examset_txt
else:
do_comparison=False
if do_comparison:
(ACQ_set,FL_set,RM_set,ALT_set,acq_params,fl_params,rm_params,alt_params,ogp_diff,acq_idx,fl_idx,rm_idx,alt_idx)=analyze_examsets(examset_txt.decode('unicode-escape'))
act_set_acq=set(acq_idx.values())
act_set_fl=set(fl_idx.values())
act_set_rm=set(rm_idx.values())
act_set_alt=set(alt_idx.values())
if not init_examset:
#ACQ
self.ogp_del[curr_examset_date,'ACQ']=list(set.difference(old_set_acq,act_set_acq)) #check new
self.ogp_new[curr_examset_date,'ACQ']=list(set.difference(act_set_acq,old_set_acq)) #deck deleted
self.ogp_change[curr_examset_date,'ACQ']=[]
for ogp in set.intersection(act_set_acq,old_set_acq): #detect changes
if ACQ_set[ogp]!=self.ACQ_set[ogp]:
changes=[]
for param in acq_params:
try:
if ACQ_set[ogp][param]!=self.ACQ_set[ogp][param]:
changes.append((param,self.ACQ_set[ogp][param],ACQ_set[ogp][param]))
except:
print 'skipping param '+param+' in ogp '+ogp
self.ogp_change[curr_examset_date,'ACQ'].append((ogp,changes))
#FL
self.ogp_del[curr_examset_date,'FL']=list(set.difference(old_set_fl,act_set_fl)) #check new
self.ogp_new[curr_examset_date,'FL']=list(set.difference(act_set_fl,old_set_fl)) #deck deleted
self.ogp_change[curr_examset_date,'FL']=[]
for ogp in set.intersection(act_set_fl,old_set_fl): #detect changes
if FL_set[ogp]!=self.FL_set[ogp]:
changes=[]
for param in fl_params:
try:
if FL_set[ogp][param]!=self.FL_set[ogp][param]:
changes.append((param,self.FL_set[ogp][param],FL_set[ogp][param]))
except:
print 'skipping param '+param+' in ogp '+ogp
self.ogp_change[curr_examset_date,'FL'].append((ogp,changes))
#RM
self.ogp_del[curr_examset_date,'RM']=list(set.difference(old_set_rm,act_set_rm)) #check new
self.ogp_new[curr_examset_date,'RM']=list(set.difference(act_set_rm,old_set_rm)) #deck deleted
self.ogp_change[curr_examset_date,'RM']=[]
for ogp in set.intersection(act_set_rm,old_set_rm): #detect changes
if RM_set[ogp]!=self.RM_set[ogp]:
changes=[]
for param in rm_params:
try:
if RM_set[ogp][param]!=self.RM_set[ogp][param]:
changes.append((param,self.RM_set[ogp][param],RM_set[ogp][param]))
except:
print 'skipping param '+param+' in ogp '+ogp
self.ogp_change[curr_examset_date,'RM'].append((ogp,changes))
old_set_acq=act_set_acq
old_set_fl=act_set_fl
old_set_rm=act_set_rm
old_set_alt=act_set_alt
self.ACQ_set.update(ACQ_set)
self.FL_set.update(FL_set)
self.RM_set.update(RM_set)
self.ALT_set.update(ALT_set)
self.acq_params=acq_params
self.fl_params=fl_params
self.rm_params=rm_params
self.alt_params=alt_params
self.ACQ_ogps=self.ACQ_ogps.union(acq_idx.values())
self.FL_ogps=self.FL_ogps.union(fl_idx.values())
self.RM_ogps=self.RM_ogps.union(rm_idx.values())
self.ALT_ogps=self.ALT_ogps.union(alt_idx.values())
self.ogp_diff.update(ogp_diff)
except Exception,e:
print e
print 'error during exam set analysis'
ret=False
return ret
#------------------------------------------------------------------
def examsets_identical(self,examset1,examset2):
examset1=examset1.split('\n')
examset2=examset2.split('\n')
if examset1[2:]==examset2[2:]:
return True
else:
return False
#------------------------------------------------------------------
def save_data(self):
#output to file
global rac_op
tab=self.notebook.GetSelection()
fromDate = str(self.start__datum.date()).replace(' ','_')
toDate = str(self.ende__datum.date()).replace(' ','_')
Anzahltage=((self.ende__datum-self.start__datum).days+1)
self.extract_ivs_hw_info()
scu_dat=self.extract_scu_caf_info()
self.success_examsets=self.extract_examsets()
if self.events>0:
outputfile = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate +'_plane_' + str(self.plane) + '_events.csv')
fw = open(outputfile, "w")
headline=("Date+Time"
+",Index,Focus"
+",Number,Rate/[Hz]"
+",Volt/[kV]"
+",Curr/[mA]"
+",Time/[ms]"
+",Power/[kW]"
+",meanPower/[kW]"
+",Modus"
+",Biplane"
+",AltAcq"
+",Axis_mode"
+",Resolution"
+",SID/[cm]"
+",WW/[mm]"
+",Cu-Filt"
+",Zoom"
+",FD-Dosis/[nGy]"
+",phys.FD-Dose[nGy]"
+",Bsig"
+",FD mode"
+",M-Field"
+",CRAN/[grad]"
+",RAO/[grad]"
+",Table Height/[cm]"
+",SOD/[cm]"
+",Gamma"
+",Gantry_Rot/[grad]"
+",SkinDoseRate/[uGy/s]"
+",Study"
+",Area/[cm*cm]"
+",maxArea/[cm*cm]"
+",SkinDose/[uGy]"
+",DAP/[0.01uGy*m*m]"
+",Dose yield[uGy/mAs]"
+",Scenelength/[s]"
+",Dutycycle"
+",3D-Mode"
+",HU/[proz]"
+",Dyn. Offset"
+",wPawMode_"
+",BE"
+",P1"
+",P2"
+",OGP"
+",Pos. Prev. = Rev."
+",arcing"
+",time_between_xray/[s]"
+",Soll-Szenenlaenge/[s]"
+",Soll-FD-Dosis/[nGy]"
+",OGP_ms"
+",kV_ms"
+",kV_dose"
+",CArm_rot/[grad]"
+",CArm_orb/[grad]"
+",TableLift/[cm]"
+",TableLong/[cm]"
+",TableTrans/[cm]"
+",TableRot"
+",TableTilt"
+",TableCradle"
+",alpha_orb/[grad]"
+",weekday"
+",act_tube_freq/[Hz]"
+",drive_tube_freq/[Hz]"
+",drive current/[mA]"
+",oil temperatur/[C]"
+",gridpulse"
+",arc_0x001A"
+",arc_0x001A_#fr"
+",arc_0x001B"
+",arc_0x001B_#fr"
+",arc_0x001C"
+",arc_0x001C_#fr"
+",arc_0x001D"
+",arc_0x001D_#fr"
+",arc_0x001E"
+",arc_0x001E_#fr"
+",arc_0x0018"
+",arc_0x0018_#fr"
+",arc_0x000A"
+",arc_0x000A_#fr"
+",arc_0x000B"
+",arc_0x000B_#fr"
+",arc_0x000C"
+",arc_0x000C_#fr"
+",arc_0x0008"
+",arc_0x0008_#fr"
+",arc_0x0007"
+",arc_0x0007_#fr"
+",arc_0x0006"
+",arc_0x0006_#fr"
+",arc_0x0005"
+",arc_0x0005_#fr"
+",arc_0x0004"
+",arc_0x0004_#fr"
+",arc_0x0003"
+",arc_0x0003_#fr"
+",arc_0x0002"
+",arc_0x0002_#fr"
+",arc_0x0001"
+",arc_0x0001_#fr"
+",arc_0x0000"
+",arc_0x0000_#fr"
+",arc_other"
+",num grid warnings"
+",grid_0x000A"
+",grid_0x000A_#fr"
+",grid_0x0009"
+",grid_0x0009_#fr"
+",grid_0x0008"
+",grid_0x0008_#fr"
+",grid_0x0007"
+",grid_0x0007_#fr"
+",grid_0x0006"
+",grid_0x0006_#fr"
+",grid_0x0005"
+",grid_0x0005_#fr"
+",grid_0x0004"
+",grid_0x0004_#fr"
+",grid_0x0003"
+",grid_0x0003_#fr"
+",grid_0x0002"
+",grid_0x0002_#fr"
+",grid_0x0001"
+",grid_0x0001_#fr"
+",grid_0x0000"
+",grid_0x0000_#fr"
+",grid_other"
+",10R/min"
+",ScanSec/[s]"
+",Volt_Prev/[kV]"
+",Curr_Prev/[mA]"
+",Time_Prev/[ms]"
+",WW_Prev/[ms]"
+",CRAN_Prev/[grad]"
+",RAO_Prev/[grad]"
+",maxPower_Prev/[kW]"
+",maxPower_Rev/[kW]"
+",maxCurrent_Prev/[mA]"
+",maxCurrent_Rev/[mA]"
+",MaxPowerPrev-PowerPrev/[kW]"
+",MaxPowerRev-PowerRev/[kW]"
+",MaxCurrPrev-CurrPrev/[mA]"
+",MaxCurrRev-CurrRev/[mA]"
+",HU_prev/[proz]"
+",rel.maxPower (rev/max from prev)"
+",uAs"
+",emitter_current/[mA]"
+",emitter_temp/[C]"
+",tungsten_evap_rate/[um/h]"
+",tungsten_thickness/[um]"
)
if self.plane=='B':
headline.replace('Gantry_Rot/[grad]','Gantry_long/[mm]')
if EA_IC!='':
headline=headline+",maxPower_dyn/[kW]"
headline=headline+'\n'
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
headline=headline.replace(',',';')
if IcConsMode:
headline=headline.replace('#','No')
fw.write(headline)
for i in range(len(preview_SID)):
try:
if self.myXEvent.mode[i]==ord('A'):
if self.myXEvent.OGP[i] in self.ACQ_set:
kvms=self.ACQ_set[self.myXEvent.OGP[i]]['kV ms']
kvdose=self.ACQ_set[self.myXEvent.OGP[i]]['kV-Dose']
ogp_ms=self.ACQ_set[self.myXEvent.OGP[i]]['Pulsewidth']
if self.ACQ_set[self.myXEvent.OGP[i]]['E X P O S U R E'] in ['3D-DR','3D-DSA','3D-CARD','3D-DRLV','3D-DRLF','DYNA','DRDYNA','3D-CORO']:
self.myXEvent._3Dmode[i]=self.ACQ_set[self.myXEvent.OGP[i]]['E X P O S U R E']
else:
self.myXEvent._3Dmode[i]='no3d'
elif self.myXEvent.OGP[i] in self.ALT_set:
kvms=self.ALT_set[self.myXEvent.OGP[i]]['kV ms']
kvdose=self.ALT_set[self.myXEvent.OGP[i]]['kV-Dose']
ogp_ms=self.ALT_set[self.myXEvent.OGP[i]]['Pulsewidth']
else:
kvms=-1
kvdose=-1
ogp_ms=-1
else: #FL or RDMP
if self.myXEvent.OGP[i] in self.FL_set:
kvms=self.FL_set[self.myXEvent.OGP[i]]['kV ms']
kvdose=self.FL_set[self.myXEvent.OGP[i]]['kV Dose']
ogp_ms=self.FL_set[self.myXEvent.OGP[i]]['Pulse Width']
elif self.myXEvent.OGP[i] in self.RM_set:
kvms=self.RM_set[self.myXEvent.OGP[i]]['kV ms']
kvdose=self.RM_set[self.myXEvent.OGP[i]]['kV Dose']
ogp_ms=self.RM_set[self.myXEvent.OGP[i]]['Pulse Width']
else:
kvms=-1
kvdose=-1
ogp_ms=-1
except:
kvms=-1
kvdose=-1
ogp_ms=-1
datastr= ( str(time.strftime("%d.%m.%Y %H:%M:%S", time.localtime(self.myXEvent.date[i])))
+','+"%xi" % int(self.myXEvent.index[i])
+','+chr(int(self.myXEvent.focus[i]))
+','+str(int(self.myXEvent.frames[i]))
+','+str(self.myXEvent.frequency[i])
+','+str(self.myXEvent.voltage[i])
+', %4.2f' % self.myXEvent.current[i]
+','+str(self.myXEvent.time[i])
+','+str(self.myXEvent.voltage[i]*self.myXEvent.current[i]/1000.)
+','+str(self.myXEvent.voltage[i]*self.myXEvent.current[i]/1000.*self.myXEvent.dutycycle[i])
+','+chr(int(self.myXEvent.mode[i]))
+','+str(self.myXEvent.biplane[i])
+','+str(self.myXEvent.alt_acq[i])
+','+self.myXEvent.axis_mode[i]
+','+self.myXEvent.resolution[i]
+','+str(self.myXEvent.SID[i])
+','+str(self.myXEvent.was[i])
+','+str(self.myXEvent.filt[i])
+','+str(int(self.myXEvent.zoom[i]))
+','+str(int(self.myXEvent.system_dose[i]))
+','+str(int(self.myXEvent.SysDose_with_ZDF[i]))
+','+str(self.myXEvent.Bsig[i])
+',_'+self.myXEvent.FDmode[i]
+','+str(self.myXEvent.Mfield[i])
+','+str(self.myXEvent.cran[i])
+','+str(self.myXEvent.rao[i])
+', %4.2f' % (self.myXEvent.table_height[i])
+', %4.2f' % (self.myXEvent.SOD[i])
+', %4.2f' % (self.myXEvent.gamma[i])
+', %4.2f' % (self.myXEvent.scu_base_rot[i])
+','+str(self.myXEvent.skindoserate[i])
+','+str(int(self.myXEvent.pat_number[i]))
+', %4.2f' % self.myXEvent.area[i]
+', %4.2f' % self.myXEvent.maxarea[i]
+', %4.2f' % self.myXEvent.skindose[i]
+','+str(self.myXEvent.DAP[i])
+', %4.2f' % self.myXEvent.dose_per_mAs[i]
+', %4.2f' % (self.myXEvent.scenelength[i]/1000.)
+','+str(self.myXEvent.dutycycle[i])
+','+self.myXEvent._3Dmode[i]
+','+str(self.myXEvent.HU[i])
+', %4.2f' % self.myXEvent.offset[i]
+','+str(self.myXEvent.wPawMode[i])
+', %4.2f' % self.myXEvent.BE_total[i]
+','+str(self.myXEvent.p1[i])
+','+str(self.myXEvent.p2[i])
+','+self.myXEvent.OGP[i]
+','+str(preview_review[i])
+','+str(num_arcing[i])
+', %4.2f' %time_between_xray[i]
+','+str(self.myXEvent.soll_Szenenlaenge[i])
+','+str(self.myXEvent.soll_fd_dosis[i])
+','+str(ogp_ms)
+','+str(kvms)
+','+str(kvdose)
+', %4.2f' % self.myXEvent.scu_carm_rot[i]
+', %4.2f' % self.myXEvent.scu_carm_orb[i]
+','+str(self.myXEvent.scu_T1[i])
+','+str(self.myXEvent.scu_T2[i])
+','+str(self.myXEvent.scu_T3[i])
+','+str(self.myXEvent.scu_table_rot[i])
+','+str(self.myXEvent.scu_table_tilt[i])
+','+str(self.myXEvent.scu_table_cradle[i])
+', %4.2f' % self.myXEvent.alpha_orb[i]
+','+str(datetime.datetime.weekday(datetime.datetime.fromtimestamp(self.myXEvent.date[i])))
+','+str(self.myXEvent.act_tube_freq[i])
+','+str(self.myXEvent.driv_tube_freq[i])
+','+str(self.myXEvent.driv_current[i])
+','+str(self.myXEvent.oil_temp[i])
+','+str(self.myXEvent.gridpulse[i])
+','+str(self.myXEvent.arc_0x001A[i])
+','+str(self.myXEvent.arc_0x001A_frame[i])
+','+str(self.myXEvent.arc_0x001B[i])
+','+str(self.myXEvent.arc_0x001B_frame[i])
+','+str(self.myXEvent.arc_0x001C[i])
+','+str(self.myXEvent.arc_0x001C_frame[i])
+','+str(self.myXEvent.arc_0x001D[i])
+','+str(self.myXEvent.arc_0x001D_frame[i])
+','+str(self.myXEvent.arc_0x001E[i])
+','+str(self.myXEvent.arc_0x001E_frame[i])
+','+str(self.myXEvent.arc_0x0018[i])
+','+str(self.myXEvent.arc_0x0018_frame[i])
+','+str(self.myXEvent.arc_0x000A[i])
+','+str(self.myXEvent.arc_0x000A_frame[i])
+','+str(self.myXEvent.arc_0x000B[i])
+','+str(self.myXEvent.arc_0x000B_frame[i])
+','+str(self.myXEvent.arc_0x000C[i])
+','+str(self.myXEvent.arc_0x000C_frame[i])
+','+str(self.myXEvent.arc_0x0008[i])
+','+str(self.myXEvent.arc_0x0008_frame[i])
+','+str(self.myXEvent.arc_0x0007[i])
+','+str(self.myXEvent.arc_0x0007_frame[i])
+','+str(self.myXEvent.arc_0x0006[i])
+','+str(self.myXEvent.arc_0x0006_frame[i])
+','+str(self.myXEvent.arc_0x0005[i])
+','+str(self.myXEvent.arc_0x0005_frame[i])
+','+str(self.myXEvent.arc_0x0004[i])
+','+str(self.myXEvent.arc_0x0004_frame[i])
+','+str(self.myXEvent.arc_0x0003[i])
+','+str(self.myXEvent.arc_0x0003_frame[i])
+','+str(self.myXEvent.arc_0x0002[i])
+','+str(self.myXEvent.arc_0x0002_frame[i])
+','+str(self.myXEvent.arc_0x0001[i])
+','+str(self.myXEvent.arc_0x0001_frame[i])
+','+str(self.myXEvent.arc_0x0000[i])
+','+str(self.myXEvent.arc_0x0000_frame[i])
+','+str(self.myXEvent.arc_other[i])
+','+str(num_grid[i])
+','+str(self.myXEvent.grid_0x000A[i])
+','+str(self.myXEvent.grid_0x000A_frame[i])
+','+str(self.myXEvent.grid_0x0009[i])
+','+str(self.myXEvent.grid_0x0009_frame[i])
+','+str(self.myXEvent.grid_0x0008[i])
+','+str(self.myXEvent.grid_0x0008_frame[i])
+','+str(self.myXEvent.grid_0x0007[i])
+','+str(self.myXEvent.grid_0x0007_frame[i])
+','+str(self.myXEvent.grid_0x0006[i])
+','+str(self.myXEvent.grid_0x0006_frame[i])
+','+str(self.myXEvent.grid_0x0005[i])
+','+str(self.myXEvent.grid_0x0005_frame[i])
+','+str(self.myXEvent.grid_0x0004[i])
+','+str(self.myXEvent.grid_0x0004_frame[i])
+','+str(self.myXEvent.grid_0x0003[i])
+','+str(self.myXEvent.grid_0x0003_frame[i])
+','+str(self.myXEvent.grid_0x0002[i])
+','+str(self.myXEvent.grid_0x0002_frame[i])
+','+str(self.myXEvent.grid_0x0001[i])
+','+str(self.myXEvent.grid_0x0001_frame[i])
+','+str(self.myXEvent.grid_0x0000[i])
+','+str(self.myXEvent.grid_0x0000_frame[i])
+','+str(self.myXEvent.grid_other[i])
+', %4.2f' % self.myXEvent._10Rlimit[i]
+', %4.2f' % (self.myXEvent.frames[i]*self.myXEvent.time[i]/1000.)
+','+str(self.myXEvent.soll_kV[i])
+','+str(self.myXEvent.soll_mA[i])
+','+str(self.myXEvent.soll_ms[i])
+','+str(self.myXEvent.soll_WW[i])
+','+str(preview_cran[i])
+','+str(preview_rao[i])
+', %4.2f' % self.myXEvent.maxPower_Sollzeit[i]
+', %4.2f' % self.myXEvent.maxPower_Istzeit[i]
+', %4.2f' % self.myXEvent.maxCurrentPrev[i]
+', %4.2f' % self.myXEvent.maxCurrentRev[i]
+', %4.2f' % (self.myXEvent.maxPower_Sollzeit[i]-self.myXEvent.soll_kV[i]*self.myXEvent.soll_mA[i]/1000.)
+', %4.2f' % (self.myXEvent.maxPower_Istzeit[i]-self.myXEvent.voltage[i]*self.myXEvent.current[i]/1000.)
+', %4.2f' % (self.myXEvent.maxCurrentPrev[i]-self.myXEvent.soll_mA[i])
+', %4.2f' % (self.myXEvent.maxCurrentRev[i]-self.myXEvent.current[i])
+','+str(self.myXEvent.prevHU[i])
+', %4.2f' % ((self.myXEvent.voltage[i]*self.myXEvent.current[i]/1000.)/self.myXEvent.maxPower_Sollzeit[i])
+','+str(self.myXEvent.mAs[i])
+', %4.2f' % (self.myXEvent.heating_current[i])
+', %4.2f' % (self.myXEvent.emitter_temp[i])
+', %4.2e' % (self.myXEvent.tungst_evaporation_rate[i])
+', %4.2e' % (self.myXEvent.tungst_thickness[i])
)
if EA_IC!='':
datastr=datastr +', %4.2f' % self.myXEvent.maxPowerdyn[i]
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
datastr=datastr[0:10]+datastr[10:].replace(',',';').replace('.',',')
fw.write("%s\n"%datastr)
fw.close()
#PUN Errors and warnings
racstr=''
outputfile=os.path.join(self.resultsDirSN,'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate +'_plane_' + str(self.plane) + '_PUN_ERRORS.csv')
racop_fp = open(outputfile, "w")
for pun_err_type in sort(PUN_ERR.keys()):
if len(PUN_ERR[pun_err_type])>0 and pun_err_type!='Warn_5016_SCAN_WARNING':
racstr+=pun_err_type+'\n'
for ttt in PUN_ERR[pun_err_type]:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='MMT_warning\n'
for ttt in MMT_warning:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='FPGA_Error\n'
for ttt in FPGA_Error:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='Warn_5016_SCAN_WARNING\n'
racstr+='time; type; focus; kV; mA; ms; HU; kW; frame; OGP; index\n'
for i in range(len(arcing_time_global)):
racstr+=str(arcing_time_global[i])+';'
racstr+=arcing_type_global[i]+';'
racstr+=arcing_foc_global[i]+';'
racstr+=str(arcing_kV_global[i]).replace('.',',')+';'
racstr+=str(arcing_mA_global[i]).replace('.',',')+';'
racstr+=str(arcing_ms_global[i]).replace('.',',')+';'
racstr+=str(arcing_HU_global[i])+';'
racstr+=str(round(arcing_mA_global[i]*arcing_kV_global[i]/1000.,1)).replace('.',',')+';'
racstr+=arcing_frame_global[i]+';'
racstr+=arcing_ogp_global[i]+';'
racstr+=str(arcing_idx_global[i])+'i\n'
racstr+='\n'
racstr+='TUBE_ADJUST\n'
for ttt in TUBE_ADJUST:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='TUBE_CONDITIONING\n'
for ttt in TUBE_CONDITIONING:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='ANG_ERR\n'
for ang_err_type in sort(ANG_ERR.keys()):
if len(ANG_ERR[ang_err_type])>0:
racstr+=ang_err_type.replace('\t',' ')+'\n'
for ttt in ANG_ERR[ang_err_type]:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='\n'
racstr+='ANG_CURR_DEVIATION >15%: '+str(len(ANG_CUR_DEV))+'\n'
racstr+='\n'
racstr+='NO_XRAY\n'
for ttt in NO_XRAY:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='Bypass_Fluoro\n'
for ttt in bypass_fl:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='3D_abort\n'
for ttt in LESS_FRAMES:
racstr+=str(ttt)+'\n'
racstr+='\n'
racstr+='Cooling on/off\n'
for ctime,cstate in zip(cooling_time,cooling_state):
racstr+=str(ctime)+';'+str(cstate)+'\n'
racstr+='\n'
racstr+='System on\n'
for ctime in power_on:
racstr+=str(ctime)+'\n'
racstr+='\n'
racstr+='System off\n'
for ctime in power_off:
racstr+=str(ctime)+'\n'
racstr+='\n'
racstr+='Image transfers to Syngo Dynamics\n'
if len(transfer_dynamics)>0:
racstr+='Date; #images\n'
for ctime,num_ima in transfer_dynamics:
racstr+=str(ctime)+';'+str(num_ima)+'\n'
racstr+='\n'
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
racstr.replace(',',';')
racop_fp.write(racstr)
racop_fp.close
#save scu data
if len(scu_time)>0:
outputfile = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate +'_plane_' + str(self.plane) + '_scu_data.csv')
fw = open(outputfile, "w")
if self.plane=='A':
txtstr='Date,SID,cran,rao,scu_carm_rot,scu_carm_orb,scu_camera_rot,scu_collim_rot,base rot,gantry rot,gantry_long,alpha_orb,T1,T2,T3,scu_table_rot,scu_table_tilt,scu_table_cradle'
else:
txtstr='Date,SID,cran,rao,scu_carm_rot,scu_carm_orb,scu_camera_rot,scu_collim_rot,base rot,gantry rot,gantry_long,alpha_orb'
if len(scu_224_time)>0:
txtstr+=',scu_A1,scu_A2,scu_A3,scu_A4,scu_A5,scu_A6,alpha_orb_robot,alpha_xray_robot,224_time'
txtstr+='\n'
for i in range(len(scu_time)):
if self.plane=='A':
line=scu_time[i]+','+str(scu_sid[i])+','+str(scu_cran[i])+','+str(scu_rao[i])+','+str(scu_carm_rot[i])+','+str(scu_carm_orb[i])+','+str(scu_camera_rot[i])+','+str(scu_collim_rot[i])+','+str(scu_base_rot[i])+','+str(scu_gantry_rot[i])+','+str(scu_gantry_long[i])+','+'%4.2f'%alpha_orb[i]+','+str(scu_T1[i])+','+str(scu_T2[i])+','+str(scu_T3[i])+','+str(scu_table_rot[i])+','+str(scu_table_tilt[i])+','+str(scu_table_cradle[i])
else:
line=scu_time[i]+','+str(scu_sid[i])+','+str(scu_cran[i])+','+str(scu_rao[i])+','+str(scu_carm_rot[i])+','+str(scu_carm_orb[i])+','+str(scu_camera_rot[i])+','+str(scu_collim_rot[i])+','+'na' +',na,' +str(scu_gantry_long[i])+','+'%4.2f'%alpha_orb[i]
try:
idx=bisect_left(scu_224_time,scu_time[i])
if idx==len(scu_224_time):
idx=len(scu_224_time)-1
line+=','+scu_224_robot_angles[idx][0]+','+scu_224_robot_angles[idx][1]+','+scu_224_robot_angles[idx][2]+','+scu_224_robot_angles[idx][3]+','+scu_224_robot_angles[idx][4]+','+scu_224_robot_angles[idx][5]
line+=','+'%4.2f'%alpha_orb_rob[idx]+','+'%4.2f'%alpha_xray_robot[idx]
line+=','+scu_224_time[idx]
except:
True
txtstr+=line+'\n'
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
fw.write(txtstr.replace(',',';').replace('.',','))
else:
fw.write(txtstr)
fw.close()
if len(fingerfilter_in)>0:
outputfile=os.path.join(self.resultsDirSN,'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate +'_plane_' + str(self.plane) + '_finger_filter.csv')
fp = open(outputfile, "w")
for ttt in fingerfilter_in:
fp.write(ttt+'\n')
fp.close
###save SN specific results
if tab==3 or tab==1:
exp_type={}
exp_type['CARD']=0
exp_type['DR']=0
exp_type['DSA']=0
exp_type['RDMP']=0
exp_type['FLUORO']=0
exp_type['3D-DR']=0
exp_type['3D-DSA']=0
exp_type['3D-CARD']=0
exp_type['3D-DRLV']=0
exp_type['3D-DRLF']=0
exp_type['3D-CORO']=0
exp_type['DYNA']=0
exp_type['DRDYNA']=0
exp_type['PERI']=0
exp_type['DRSTEP']=0
exp_type['unknown']=0
for i in range(self.events):
try:
if self.myXEvent.OGP[i] in self.ACQ_set.keys():
exp_type[self.ACQ_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
elif self.myXEvent.OGP[i] in self.FL_set.keys():
exp_type[self.FL_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
elif self.myXEvent.OGP[i] in self.RM_set.keys():
exp_type[self.RM_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
elif self.myXEvent.OGP[i] in self.ALT_set.keys():
exp_type[self.ALT_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
else: #could happen if OGP is deleted, micro symbol is used,...
best_matches_acq=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.ACQ_ogps))
best_matches_fl=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.FL_ogps))
best_matches_rm=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.RM_ogps))
best_matches_alt=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.ALT_ogps))
found=False
if len(best_matches_acq)>0 and not found:
for ogp in best_matches_acq:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.ACQ_set[ogp]['E X P O S U R E']]+=1
found=True
if len(best_matches_fl)>0 and not found:
for ogp in best_matches_fl:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.FL_set[ogp]['E X P O S U R E']]+=1
found=True
if len(best_matches_rm)>0 and not found:
for ogp in best_matches_rm:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.RM_set[ogp]['E X P O S U R E']]+=1
found=True
if len(best_matches_alt)>0 and not found:
for ogp in best_matches_rm:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.ALT_set[ogp]['E X P O S U R E']]+=1
found=True
if not found:
exp_type['unknown']+=1
except:
exp_type['unknown']+=1 #might happen if the Examset file in Ziplog is missing or corrupt
if self.init_analysis==True: #write header only at first system
self.init_analysis=False
self.today=str(datetime.datetime.now()).replace(' ','_').replace(':','-')
txtstr=u'SN'
txtstr+=',Start'
txtstr+=',End'
txtstr+=',Plane'
txtstr+=',SystemType'
txtstr+=',SyngoSystemType'
txtstr+=',SystemShape'
txtstr+=',City'
txtstr+=',Country'
txtstr+=',SW Version'
txtstr+=',IVS System Model'
txtstr+=',GPU Type'
txtstr+=',Tube Type'
txtstr+=',Tube SNs'
txtstr+=',Generator Type'
txtstr+=',Generator SW/HW'
txtstr+=',FD Type'
txtstr+=',XWP SN'
txtstr+=',XWP SW'
txtstr+=',Line Resistance'
txtstr+=',Line Voltage'
txtstr+=',X-rays'
txtstr+=',X-rays F1 [%]'
txtstr+=',X-rays F2 [%]'
txtstr+=',X-rays FG [%]'
txtstr+=',# FL'
txtstr+=',# ACQ'
txtstr+=',mean FL time/d [s]'
txtstr+=',std FL time/d [s]'
txtstr+=',mean ACQ time/d [s]'
txtstr+=',std ACQ time/d [s]'
txtstr+=',days with x-rays'
txtstr+=',days with logs'
txtstr+=',BE'
txtstr+=',BE/d'
txtstr+=',BE >50%'
txtstr+=',BE >75%'
txtstr+=',ScanSec'
txtstr+=',Arcs'
txtstr+=',Arctrains'
txtstr+=',Arctrains/10k ScanSec'
txtstr+=',GridWarnings'
txtstr+=',mean_Slip'
txtstr+=',std_Slip'
txtstr+=',max_Slip'
txtstr+=',mean_act_anode_frq'
txtstr+=',vertTubeTime/[min]'
txtstr+=',meanDrivCurr'
txtstr+=',minDrivCurr'
txtstr+=',maxDrivCurr'
txtstr+=',stdDrivCurr'
txtstr+=',max_HU'
txtstr+=',mean_Oiltemp'
txtstr+=',max_Oiltemp'
txtstr+=',Run time /[h]'
txtstr+=',System starts'
txtstr+=',Cooling state changes'
txtstr+=',Cooling Dutycycle'
for pun_err_type in sort(PUN_ERR.keys()):
txtstr+=','+pun_err_type
for ang_err_type in sort(ANG_ERR.keys()):
txtstr+=','+ang_err_type.replace('\t',' ')
txtstr+=',MMT_warning'
txtstr+=',FPGA_Error'
txtstr+=',3D_ABORT (less frames)'
txtstr+=',Curr_Dev_15perc'
txtstr+=',#Bypass Fluoro'
txtstr+=',mean TubeEff@125kV_F1'
txtstr+=',std TubeEff@125kV_F1'
txtstr+=',mean dyn. Offset F1'
txtstr+=',std dyn. Offset F1'
txtstr+=',min dyn. Offset F1'
txtstr+=',max dyn. Offset F1'
txtstr+=',mean dyn. Offset FG'
txtstr+=',std dyn. Offset FG'
txtstr+=',min dyn. Offset FG'
txtstr+=',max dyn. Offset FG'
txtstr+=',mean dyn. Offset F2'
txtstr+=',std dyn. Offset F2'
txtstr+=',min dyn. Offset F2'
txtstr+=',max dyn. Offset F2'
txtstr+=',Num Patients'
txtstr+=',mean Skindose/patient'
txtstr+=',std Skindose/patient'
txtstr+=',mean DAP/patient'
txtstr+=',std DAP/patient'
txtstr+=',mean Gamma'
txtstr+=',std Gamma'
txtstr+=',mean WV [mm]'
txtstr+=',std WV [mm]'
txtstr+=',num maxed Outs FL'
txtstr+=',num maxed Outs ACQ'
txtstr+=',num 3D'
txtstr+=',mean SID [cm]'
txtstr+=',min SID [cm]'
txtstr+=',max SID [cm]'
txtstr+=',std SID [cm]'
txtstr+=',#Xrays@SID>120'
txtstr+=',preview_review'
txtstr+=',mean pulsetime [ms]'
txtstr+=',std pulsetime [ms]'
txtstr+=',mean fl system dose [nGy]'
txtstr+=',std fl system dose [nGy]'
txtstr+=',mean acq system dose [nGy]'
txtstr+=',std acq system dose [nGy]'
txtstr+=',mean freq /Fl'
txtstr+=',mean freq /Acq'
txtstr+=',mean Zoom'
txtstr+=',std Zoom'
txtstr+=',mean patient time [min]'
txtstr+=',std patient time [min]'
txtstr+=', # Lat<-10 Cran>10'
txtstr+=', # Lat<-10 Cran<10>-10'
txtstr+=', # Lat<-10 Cran<-10'
txtstr+=', # Lat>-10<10 Cran>10'
txtstr+=', # Lat>-10<10 Cran<10>-10'
txtstr+=', # Lat>-10<10 Cran<-10'
txtstr+=', # Lat>10 Cran>10'
txtstr+=', # Lat>10 Cran<10>-10'
txtstr+=', # Lat>10 Cran<-10'
txtstr+=', # CARD'
txtstr+=', # DR'
txtstr+=', # DSA'
txtstr+=', # FLUORO'
txtstr+=', # RDMP'
txtstr+=', # 3D_DR'
txtstr+=', # 3D_DSA'
txtstr+=', # 3D_CARD'
txtstr+=', # 3D_DRLV'
txtstr+=', # 3D_DRLF'
txtstr+=', # 3D_CORO'
txtstr+=', # DYNA'
txtstr+=', # DRDYNA'
txtstr+=', # PERI'
txtstr+=', # DRSTEP'
txtstr+=', # unknown'
txtstr+=', Manual table panning w/o TCM'
txtstr+=', PatPosition 1'
txtstr+=', PatPosition 2'
txtstr+=', PatPosition 3'
txtstr+=', PatPosition 4'
txtstr+=', PatPosition 5'
txtstr+=', PatPosition 6'
txtstr+=', PatPosition 7'
txtstr+=', PatPosition 8'
txtstr+=', New Examsets'
txtstr+=', Del Examsets'
txtstr+=', Changed Examsets'
txtstr+=', Image Quality Setting'
txtstr+='\n'
self.datastr_tot=txtstr
ende=self.events
datastr=self.SN
datastr+=','+str(self.startdate)
datastr+=','+str(self.enddate)
datastr+=','+self.plane
datastr+=','+self.myXEvent.SystemType
datastr+=','+self.myXEvent.syngo_system_type
datastr+=','+self.myXEvent.SystemShape
datastr+=','+self.myXEvent.city
datastr+=','+self.myXEvent.country
datastr+=','+str(self.usedSWs).replace(',',' ')
datastr+=','+self.sys_model
datastr+=','+str(self.gpu_model).replace(',',' ')
datastr+=','+self.myXEvent.tubetype_str
try:
old_SN='n.a.'
SN_txt=[]
old_BE=0
old_date=''
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
SN_txt.append((date,SN,BE))
old_SN=SN
datastr+=','+str(SN_txt).replace(',',' ')
except:
datastr+=',na'
try:
datastr+=','+generator_type
datastr+=','+str(generator).replace(',','')
except:
datastr+=',n a'
datastr+=',n a'
datastr+=','+self.myXEvent.FDtype
datastr+=','+str(list(self.Leo)).replace(',',' ')
datastr+=','+str(list(self.Leo_SW)).replace(',',' ')
datastr+=','+str(self.line_resistance)
datastr+=','+str(self.line_voltage)
datastr+=','+str(self.events)
try:
datastr+=',%4.2f' %((self.myXEvent.focus==ord('S')).sum()/float(self.events))
except:
datastr+=',na'
try:
datastr+=',%4.2f' %((self.myXEvent.focus==ord('L')).sum()/float(self.events))
except:
datastr+=',na'
try:
datastr+=',%4.2f' %((self.myXEvent.focus==ord('M')).sum()/float(self.events))
except:
datastr+=',na'
datastr+=','+str((self.myXEvent.mode==ord('F')).sum())
datastr+=','+str((self.myXEvent.mode==ord('A')).sum())
try:
date_tmp=self.myXEvent.date[:self.events].copy()
day_count=0
for i in range(self.events):
date_tmp[i]=pylab.date2num(datetime.datetime.fromtimestamp(date_tmp[i]).date())
try:
if date_tmp[i]!=date_tmp[i-1] and i>0:
day_count+=1
except:
True
initday=date_tmp[0]
sl_fl=[]
sl_acq=[]
date_list = np.arange(initday,initday+Anzahltage)
for current_date in date_list:
sl_fl.append(((current_date==date_tmp)*(self.myXEvent.mode[:self.events]==ord('F'))*self.myXEvent.scenelength[:self.events]).sum()/1000.)
sl_acq.append(((current_date==date_tmp)*(self.myXEvent.mode[:self.events]==ord('A'))*self.myXEvent.scenelength[:self.events]).sum()/1000.)
sl_fl=np.array(sl_fl)
sl_acq=np.array(sl_acq)
datastr+=',%4.2f'%(sl_fl.mean())
datastr+=',%4.2f'%(sl_fl.std())
datastr+=',%4.2f'%(sl_acq.mean())
datastr+=',%4.2f'%(sl_acq.std())
datastr+=',%d'%(day_count)
except:
datastr+=',n a'
datastr+=',n a'
datastr+=',n a'
datastr+=',n a'
datastr+=',n a'
datastr+=',%d'%(len(self.Auswahl))
datastr+=',%4.2f' %(self.myXEvent.BE_total.sum())
try:
datastr+=',%4.2f' %(self.myXEvent.BE_total.sum()/float(Anzahltage))
except:
datastr+=',na'
try:
datastr+=',%4.2f' %(((self.myXEvent.prevHU>50)*self.myXEvent.BE_total).sum())
except:
datastr+=',na'
try:
datastr+=',%4.2f' %(((self.myXEvent.prevHU>75)*self.myXEvent.BE_total).sum())
except:
datastr+=',na'
scan_sec=(self.myXEvent.time*self.myXEvent.frames).sum()/1000.
datastr+=','+str(scan_sec)
datastr+=','+str(num_arcing_tot)
arc_trains=(np.array(num_arcing)>0).sum()
datastr+=','+str(arc_trains)
try:
datastr+=',%4.2f' %(arc_trains/scan_sec*10000.)
except:
datastr+=',na'
datastr+=','+str(num_grid_tot)
try:
temp_driv_frq=numpy.array(self.driv_tube_freq)
temp_act_frq=numpy.array(self.act_tube_freq)
del_elem=numpy.nonzero(temp_act_frq==65535)
temp_driv_frq=numpy.delete(temp_driv_frq,del_elem)
temp_act_frq=numpy.delete(temp_act_frq,del_elem)
min_l=min(len(temp_driv_frq),len(temp_act_frq))
slip=temp_driv_frq[:min_l]-temp_act_frq[:min_l]
slip[0]
slip_mean=',%4.2f' %(slip.mean())
slip_std =',%4.2f' %(slip.std())
slip_max =',%4.2f' %(slip.max())
act_drv_frq_mean=',%4.2f' %(temp_act_frq.max())
except:
slip_mean=',na'
slip_std= ',na'
slip_max= ',na'
act_drv_frq_mean= ',na'
datastr+=slip_mean
datastr+=slip_std
datastr+=slip_max
datastr+=act_drv_frq_mean
datastr+=',%4.2f' %(vertical_tube_time)
try:
temp_curr_mean=numpy.array(self.driv_current)
driv_curr_mean=temp_curr_mean.mean()
driv_curr_min=temp_curr_mean.min()
driv_curr_max=temp_curr_mean.max()
datastr+=',%4.2f' %(driv_curr_mean)
datastr+=',%4.2f' %(driv_curr_min)
datastr+=',%4.2f' %(driv_curr_max)
except:
datastr+= ',na'
datastr+= ',na'
datastr+= ',na'
try:
driv_curr_std=temp_curr_mean.std()
datastr+=',%4.2f' %(driv_curr_std)
except:
datastr+= ',na'
datastr+=','+str(self.myXEvent.HU.max())
try:
max(self.t0_temp) #will throw exception if empty
datastr+=',%4.2f' %(mean(self.t0_temp))
datastr+=',%4.2f' %(max(self.t0_temp))
except:
datastr+=',na'
datastr+=',na'
#running_time
try:
hour_sum=len(self.envtime2)/60. #every event equals 1 minute
datastr+=',%4.2f'%(hour_sum)
except:
datastr+=',na'
try:
datastr+=',%d'%(len(power_on))
except:
datastr+=',na'
try:
datastr+=',%d'%(len(cooling_state))
except:
datastr+=',na'
try:
cooling_ontime[1] #to run into exception if there is not entry
summed_ontime=sum(cooling_ontime)
total_time=hour_sum*3600. #from Environmental Log (anode freq)
duty_cycle=summed_ontime/total_time
datastr+=',%2.2f'%(duty_cycle)
except:
datastr+=',na'
for pun_err_type in sort(PUN_ERR.keys()):
datastr+=','+str(len(PUN_ERR[pun_err_type]))
for ang_err_type in sort(ANG_ERR.keys()):
datastr+=','+str(len(ANG_ERR[ang_err_type]))
datastr+=','+str(len(MMT_warning))
datastr+=','+str(len(FPGA_Error))
datastr+=','+str(len(LESS_FRAMES)) #3D abort
datastr+=','+str(len(ANG_CUR_DEV))
datastr+=','+str(len(bypass_fl))
try:
del_elem=numpy.nonzero(self.myXEvent.dose_per_mAs[:ende]*(self.myXEvent.focus[:ende]!=ord('S')))
tube_eff_F1=numpy.delete(self.myXEvent.dose_per_mAs[:ende],del_elem)
tube_eff_F1[0]
datastr+=',%4.2f' % np.median(tube_eff_F1)
datastr+=',%4.2f' % tube_eff_F1.std()
except:
datastr+=',na'
datastr+=',na'
try:
del_elem=numpy.nonzero(self.myXEvent.offset[:ende]*(self.myXEvent.focus[:ende]!=ord('S')))
dyn_offset_F1=numpy.delete(self.myXEvent.offset[:ende],del_elem)
dyn_offset_F1[0]
datastr+=',%4.2f' % dyn_offset_F1.mean()
datastr+=',%4.2f' % dyn_offset_F1.std()
datastr+=',%4.2f' % dyn_offset_F1.min()
datastr+=',%4.2f' % dyn_offset_F1.max()
except:
datastr+=',na'
datastr+=',na'
datastr+=',na'
datastr+=',na'
try:
del_elem=numpy.nonzero(self.myXEvent.offset[:ende]*(self.myXEvent.focus[:ende]!=ord('M')))
dyn_offset_FG=numpy.delete(self.myXEvent.offset[:ende],del_elem)
dyn_offset_FG[0]
datastr+=',%4.2f' % dyn_offset_FG.mean()
datastr+=',%4.2f' % dyn_offset_FG.std()
datastr+=',%4.2f' % dyn_offset_FG.min()
datastr+=',%4.2f' % dyn_offset_FG.max()
except:
datastr+=',na'
datastr+=',na'
datastr+=',na'
datastr+=',na'
try:
del_elem=numpy.nonzero(self.myXEvent.offset[:ende]*(self.myXEvent.focus[:ende]!=ord('L')))
dyn_offset_F2=numpy.delete(self.myXEvent.offset[:ende],del_elem)
dyn_offset_F2[0]
datastr+=',%4.2f' % dyn_offset_F2.mean()
datastr+=',%4.2f' % dyn_offset_F2.std()
datastr+=',%4.2f' % dyn_offset_F2.min()
datastr+=',%4.2f' % dyn_offset_F2.max()
except:
datastr+=',na'
datastr+=',na'
datastr+=',na'
datastr+=',na'
try:
numPats=self.myXEvent.pat_number[ende-1]+1. #remove those with patime<5min dose<x?
datastr+=','+str(numPats)
except:
datastr+=',na'
try:
temp_sk=np.array(self.myXEvent.pat_skindose)
temp_sk=temp_sk[temp_sk>0.01]/1000.
datastr+=',%4.2f' %(temp_sk.mean())
datastr+=',%4.2f' %(temp_sk.std())
except:
datastr+=',na'
datastr+=',na'
try:
temp_dap=np.array(self.myXEvent.pat_dap)
temp_dap=temp_dap[temp_dap>0.01]/100.
datastr+=',%4.2f' %(temp_dap.mean())
datastr+=',%4.2f' %(temp_dap.std())
except:
datastr+=',na'
datastr+=',na'
datastr+=',%4.2f' %self.myXEvent.gamma[:ende].mean()
datastr+=',%4.2f' %self.myXEvent.gamma[:ende].std()
datastr+=',%4.2f' %self.myXEvent.was[:ende].mean()
datastr+=',%4.2f' %self.myXEvent.was[:ende].std()
try:
datastr+=',%4.2f' %((self.myXEvent.mode[:ende]==ord('F')*(self.myXEvent.system_dose[:ende]<=20)).sum())
except:
datastr+=',na'
try:
datastr+=',%4.2f' %((self.myXEvent.mode[:ende]==ord('A')*(self.myXEvent.system_dose[:ende]<=70)).sum())
except:
datastr+=',na'
num3D=0
for kk in range(self.events):
if self.myXEvent._3Dmode[kk]!='no3d':
num3D+=1
datastr+=',%d' %num3D
datastr+=',%4.2f' %self.myXEvent.SID[:ende].mean()
try:
datastr+=',%4.2f' %self.myXEvent.SID[:ende].min()
datastr+=',%4.2f' %self.myXEvent.SID[:ende].max()
except:
datastr+=',n a'
datastr+=',n a'
datastr+=',%4.2f' %self.myXEvent.SID[:ende].std()
datastr+=',%d' %((self.myXEvent.SID[:ende]>120).sum())
datastr+=',%4.2f' %(np.array(preview_review).mean())
datastr+=',%4.2f' %self.myXEvent.time[:ende].mean()
datastr+=',%4.2f' %self.myXEvent.time[:ende].std()
sysdostmp=self.myXEvent.system_dose[self.myXEvent.mode[:ende]==ord('F')]
datastr+=',%4.2f' %(sysdostmp.mean())
try:
datastr+=',%4.2f' %(sysdostmp.std())
except:
datastr+=',%4.2f' %(-1.0)
sysdostmp=self.myXEvent.system_dose[self.myXEvent.mode[:ende]==ord('A')]
datastr+=',%4.2f' %(sysdostmp.mean())
try:
datastr+=',%4.2f' %(sysdostmp.std())
except:
datastr+=',%4.2f' %(-1.0)
datastr+=',%4.2f' %(((self.myXEvent.mode[:ende]==ord('F'))*(self.myXEvent.frequency[:ende])).sum()/(self.myXEvent.mode[:ende]==ord('F')).sum())
datastr+=',%4.2f' %(((self.myXEvent.mode[:ende]==ord('A'))*(self.myXEvent.frequency[:ende])).sum()/(self.myXEvent.mode[:ende]==ord('A')).sum())
datastr+=',%4.2f' %self.myXEvent.zoom[:ende].mean()
datastr+=',%4.2f' %self.myXEvent.zoom[:ende].std()
tmp_arr=np.array(self.myXEvent.pat_time[:ende])
tmp_arr=tmp_arr[tmp_arr>3] #only consider patients with time > 3minr
datastr+=',%4.2f' %(tmp_arr.mean())
datastr+=',%4.2f' %(tmp_arr.std())#sum up only pat times >3min
fl_evts=float(self.events)
if fl_evts==0.:fl_evts=1.
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]<-10.)*(self.myXEvent.cran[0:self.events]>10.)).sum()/fl_evts) # Lat<-10 Cran>10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]<-10.)*(self.myXEvent.cran[0:self.events]>-10.)*(self.myXEvent.cran[0:self.events]<=10.)).sum()/fl_evts) # Lat<-10 Cran<10>-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]<-10.)*(self.myXEvent.cran[0:self.events]<=-10.)).sum()/fl_evts) # Lat<-10 Cran<-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]>=-10.)*(self.myXEvent.rao[0:self.events]<10.)*(self.myXEvent.cran[0:self.events]>10.)).sum()/fl_evts) # Lat>-10<10 Cran>10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]>=-10.)*(self.myXEvent.rao[0:self.events]<10.)*(self.myXEvent.cran[0:self.events]>-10.)*(self.myXEvent.cran[0:self.events]<=10.)).sum()/fl_evts) # Lat>-10<10 Cran<10>-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]>=-10.)*(self.myXEvent.rao[0:self.events]<10.)*(self.myXEvent.cran[0:self.events]<=-10.)).sum()/fl_evts) # Lat>-10<10 Cran<-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]>=10.)*(self.myXEvent.cran[0:self.events]>10.)).sum()/fl_evts) # Lat>10 Cran>10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]>=10.)*(self.myXEvent.cran[0:self.events]>-10.)*(self.myXEvent.cran[0:self.events]<=10.)).sum()/fl_evts) # Lat>10 Cran<10>-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[0:self.events]>=10.)*(self.myXEvent.cran[0:self.events]<=-10.)).sum()/fl_evts) # Lat>10 Cran<-10
datastr+= ',%5.2f' %(float(exp_type['CARD'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['DR'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['DSA'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['FLUORO'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['RDMP'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['3D-DR'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['3D-DSA'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['3D-CARD'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['3D-DRLV'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['3D-DRLF'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['3D-CORO'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['DYNA'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['DRDYNA'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['PERI'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['DRSTEP'])/fl_evts)
datastr+= ',%5.2f' %(float(exp_type['unknown'])/fl_evts)
datastr+=','+scu_dat
datastr+= ',%d' %((np.array(self.pat_position)==1).sum())
datastr+= ',%d' %((np.array(self.pat_position)==2).sum())
datastr+= ',%d' %((np.array(self.pat_position)==3).sum())
datastr+= ',%d' %((np.array(self.pat_position)==4).sum())
datastr+= ',%d' %((np.array(self.pat_position)==5).sum())
datastr+= ',%d' %((np.array(self.pat_position)==6).sum())
datastr+= ',%d' %((np.array(self.pat_position)==7).sum())
datastr+= ',%d' %((np.array(self.pat_position)==8).sum())
try:
count=0
for key in self.ogp_new.keys():
count+=len(self.ogp_new[key])
datastr+= ',%d' %count
except:
datastr+= ',n a'
try:
count=0
for key in self.ogp_del.keys():
count+=len(self.ogp_del[key])
datastr+= ',%d' %count
except:
datastr+= ',n a'
try:
count=0
for key in self.ogp_change.keys():
count+=len(self.ogp_change[key])
datastr+= ',%d' %count
except:
datastr+= ',n a'
try:
datastr+=','+self.key_status['Image Quality Setting']
except:
datastr+= ',n a'
datastr+='\n'
self.datastr_tot+=datastr
outputfile = os.path.join(self.resultsDir, 'Artis-results_'+self.today+'.csv')
fw = open(outputfile, "w")
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
fw.write(self.datastr_tot.replace(',',';').replace('.',','))
else:
fw.write(self.datastr_tot)
fw.close()
#------------------------------------------------------------------
def kV_dose_factor(self,kV_):
#ideale Dosisausbeute bei def. kV-Punkt
#12grad, 2.5 mmAl, 4.0mm PMMA (fuer Oel), 1000mm Abstand (ungefährer Nachbau der gemessenen Dosisausbeute mit 'Spectrum Processor')
#Dose(kV)=0.0038 *kV²+0.9792*kV-28.54 µGy/mAs (Kurvenfit)
result=0.0038*kV_*kV_+0.9792*kV_-28.54; # in µGy/mAs
return result
#-------------------------------------------------------------
def kv_interplote(self, cu_atten_val, kvgrid, kv): #1D linear interpolation
# interpolation starting
voltalt = 0
cuAtt_alt = 0
for volt, cuAtt in zip(kvgrid, cu_atten_val):
if int(volt) >= int(kv):
break
voltalt = float(volt)
cuAtt_alt = float(cuAtt)
# just float-cast
volt = float(volt)
cuAtt = float(cuAtt)
value = (cuAtt - cuAtt_alt) / ( volt - voltalt) * (kv - voltalt) + cuAtt_alt
return value
#-------------------------------------------------------------
def kV_Cu_attenuation_factor(self):
"""
#Filterschwächung bei verschiedenen kV und Cu -Filterdicken (aus Blauem Buch)
#Cu 0.0 0.1 0.2 0.3 0.5 0.6 0.7 0.9
#---------------------------------------------------------------------------------------------------------------
attenuation_kV_Cu=numpy.array([[1.0, 0.249, 0.0903, 0.0384, 0.00875, 0.00448, 0.00236, 0.000698], #40kV
[1.0, 0.335, 0.158, 0.0854, 0.0309, 0.0197, 0.0129, 0.00589], #50kV
[1.0, 0.397, 0.215, 0.133, 0.0608, 0.0435, 0.0318, 0.0179], #60kV
[1.0, 0.447, 0.265, 0.177, 0.0937, 0.0715, 0.0558, 0.0355], #70kV
[1.0, 0.492, 0.314, 0.223, 0.131, 0.105, 0.0855, 0.0591], #80kV
[1.0, 0.532, 0.359, 0.266, 0.168, 0.139, 0.117, 0.0851], #90kV
[1.0, 0.565, 0.398, 0.305, 0.203, 0.171, 0.147, 0.111], #100kV
[1.0, 0.636, 0.482, 0.392, 0.285, 0.25, 0.221, 0.178]]) #125kV
"""
if self.myXEvent.numFoken==2:
#9° 3.0Al,5mmPMMA,@750mm 0.00 0.10 0.20 0.30 0.60 0.90 mmCu
#---------------------------------------------------------------------------------------------------------------
attenuation_kV_Cu=numpy.array([[ 22.10, 6.15, 2.28, 0.97, 0.110, 0.0166], #40kV
[ 41.02, 15.45, 7.52, 4.11, 0.947, 0.2774], #50kV
[ 61.70, 27.67, 15.60, 9.77, 3.23, 1.325] , #60kV
[ 82.71, 41.84, 25.97, 17.72, 7.32, 3.64 ], #70kV
[105.70, 58.95, 39.43, 28.70, 13.90, 7.91 ], #80kV
[130.40, 78.50, 55.50, 42.24, 22.77, 14.11 ], #90kV
[156.20, 99.83, 73.58, 57.87, 33.60, 22.08 ], #100kV
[224.30, 159.2, 125.8, 104.4, 68.40, 49.40 ]]) #125kV
else: #3F
#12° 3.0Al,5mmPMMA,@750mm 0.00 0.10 0.20 0.30 0.60 0.90 mmCu
#---------------------------------------------------------------------------------------------------------------
attenuation_kV_Cu=numpy.array([[ 23.50, 6.38, 2.34, 0.99, 0.112, 0.017], #40kV
[ 44.30, 16.20, 7.77, 4.23, 0.96, 0.281], #50kV
[ 67.40, 29.24, 16.40, 10.10, 3.30, 1.344], #60kV
[ 91.30, 44.60, 27.20, 18.40, 7.50, 3.71 ], #70kV
[117.50, 63.20, 41.56, 29.93, 14.30, 8.09 ], #80kV
[145.90, 84.70, 58.88, 44.37, 23.60, 14.53 ], #90kV
[175.70, 108.50, 78.64, 61.26, 35.10, 22.94 ], #100kV
[255.40, 176.00, 137.1, 112.8, 72.90, 52.35 ]]) #125kV
grid_Cu=[0.0,0.1,0.2,0.3,0.6,0.9]
grid_kV=[40,50,60,70,80,90,100,125]
dim=len(self.myXEvent.filt)
result=numpy.zeros(dim)
for i in xrange(self.events):
cu_id=grid_Cu.index(self.myXEvent.filt[i]/10.)
cu_grid_kv=attenuation_kV_Cu[:,cu_id]
cu0_grid_kv=attenuation_kV_Cu[:,0]
#result[i]=self.kv_interplote(cu0_grid_kv, grid_kV, self.myXEvent.voltage[i])/self.kv_interplote(cu_grid_kv, grid_kV, self.myXEvent.voltage[i]) #Umrechung auf 0.0Cu und 125kV
result[i]=self.kv_interplote(cu0_grid_kv, grid_kV, 125.)/self.kv_interplote(cu_grid_kv, grid_kV, self.myXEvent.voltage[i]) #Umrechung auf 0.0Cu und 125kV
result[np.isnan(result)]=0
#img = numpy.zeros( (200,200) )
#for k in xrange(200):
#
# for j in xrange(200):
# img[k,j] = tef( k*0.9/199.0, 40.0 + j*(125.0-40.0)/199.0 )
#import matplotlib.pyplot
#matplotlib.pyplot.imshow( img )
#matplotlib.pyplot.show()
return result
#-------------------------------------------------------------
def show_data(self):
tab=self.notebook.GetSelection()
try:
plt.close("all")
except:
True
if len(TIME) == 0:
if tab==0:
wx.MessageBox("No corresponding events found!")
self.do_part18()
else:
print "No corresponding events found!"
self.do_part18()
else:
#erzeuge info.txt
day_count = []
day_count.append(0) #zaehlt die Tageswechsel; die Anzahl der Tage ist dann eins mehr; nur die Tage, an denen auch events stattfinden, werden betrachtet
for i in range(len(Datum_array)-1):
if Datum_array[i]!=Datum_array[i+1]:
day_count.append(0)
#Gesamtzahl der Tage - Differenz zwischen Enddatum und Startdatum
Tagesdifferenz = (Time[len(Time)-1]-Time[0])/60/60/24 #Sekunden in Tage umgerechnet
day_total = int(math.ceil(Tagesdifferenz))
name = 'XA'+str(self.myXEvent.SN)+'_info.txt'
outputfile=os.path.join(self.resultsDirSN,name)
f = open(outputfile, 'w')
f.write('Start: ' + str(Startzeit[0]) + ' ' + 'End: ' + str(Startzeit[len(Startzeit)-1]) + ' ' + 'Days: ' + str(len(day_count))+'\n')
f.write('Files: '+ str(self.eventlog_files)+'\n' )
f.write('Radiation events on plane ' + str(self.plane)+': '+ str(self.events -1)+'\n' )
f.write('Software-version: '+str(self.myXEvent.SW[-1][0])+'\n\n')
for filename in self.system_caf:
w = open(filename,'r')
lines=w.readlines()
for line in lines:
#logging.info(line)
if (line.rfind('VERSION')>-1 ):
f.write(line+'\n')
if (line.rfind('syngo_system_type ')>-1 ):
f.write(line+'\n')
if (line.rfind('system ident')>-1 ):
f.write(line+'\n')
if (line.rfind('System Type')>-1 ):
f.write(line+'\n')
if (line.rfind('X-Ray Tube')>-1 ):
f.write(line+'\n')
if (line.rfind('Generator ')>-1 ):
f.write(line+'\n')
if (line.rfind('Generator Plane B')>-1 ):
f.write(line+'\n')
if (line.rfind('FD Type ')>-1 ):
f.write(line+'\n')
if (line.rfind('FD Type Plane B')>-1 ):
f.write(line+'\n')
f.close()
pulsepower = self.myXEvent.voltage*self.myXEvent.current/1000.
pulsepower_nullfrei = []
pulsepower_F = []
pulsepower_A = []
SID_nullfrei = []
scenelength = []
scenelength_F = []
scenelength_A = []
meanpower = []
meanpower_F = []
meanpower_A = []
skindoserate_nullfrei = []
skindoserate_A = []
skindoserate_F = []
skindose = []
skindose_A = []
skindose_F =[]
dutycycle = []
dutycycle_A = []
dutycycle_F = []
filter = []
filter_A = []
filter_F = []
xtime = []
time_A = []
time_F = []
frequency = []
frequency_A = []
frequency_F = []
watervalue = []
watervalue_F = []
watervalue_A = []
voltage = []
voltage_F = []
voltage_A = []
current = []
current_F = []
current_A = []
zoom = []
zoom_F = []
zoom_A = []
rao = []
rao_A = []
rao_F = []
cran = []
cran_A = []
cran_F = []
SID = []
SID_A = []
heatunit = []
offset = []
focus = []
patient_number = []
patient_number_F = []
patient_number_A = []
DAP = []
DAP_F = []
DAP_A = []
Dosisausbeute = []
offset = []
modus = []
BE = []
systemdose_A = []
systemdose = []
global cooling_state
global cooling_time
for i in range(self.events):
SID.append(self.myXEvent.SID[i])
scenelength.append(self.myXEvent.scenelength[i]/1000.)
meanpower.append(pulsepower[i]*self.myXEvent.dutycycle[i])
SID_nullfrei.append(self.myXEvent.SID[i])
pulsepower_nullfrei.append(pulsepower[i])
skindoserate_nullfrei.append(self.myXEvent.skindoserate[i])
dutycycle.append(self.myXEvent.dutycycle[i])
filter.append(self.myXEvent.filt[i])
xtime.append(self.myXEvent.time[i])
frequency.append(self.myXEvent.frequency[i])
watervalue.append(self.myXEvent.was[i])
voltage.append(self.myXEvent.voltage[i])
current.append(self.myXEvent.current[i])
zoom.append(self.myXEvent.zoom[i])
rao.append(self.myXEvent.rao[i])
cran.append(self.myXEvent.cran[i])
heatunit.append(self.myXEvent.HU[i])
offset.append(self.myXEvent.offset[i])
focus.append(self.myXEvent.focus[i])
patient_number.append(self.myXEvent.pat_number[i])
DAP.append(self.myXEvent.DAP[i])
skindose.append(self.myXEvent.skindose[i])
Dosisausbeute.append(self.myXEvent.dose_per_mAs[i])
modus.append(self.myXEvent.mode[i])
BE.append(self.myXEvent.BE_total[0:i+1].sum()) #BE summed up
systemdose.append(self.myXEvent.system_dose[i])
if self.myXEvent.mode[i] == ord('F'):
scenelength_F.append(self.myXEvent.scenelength[i]/1000.)
meanpower_F.append(pulsepower[i]*self.myXEvent.dutycycle[i])
pulsepower_F.append(pulsepower[i])
skindoserate_F.append(self.myXEvent.skindoserate[i])
dutycycle_F.append(self.myXEvent.dutycycle[i])
time_F.append(self.myXEvent.time[i])
frequency_F.append(self.myXEvent.frequency[i])
watervalue_F.append(self.myXEvent.was[i])
voltage_F.append(self.myXEvent.voltage[i])
current_F.append(self.myXEvent.current[i])
zoom_F.append(self.myXEvent.zoom[i])
rao_F.append(self.myXEvent.rao[i])
cran_F.append(self.myXEvent.cran[i])
patient_number_F.append(self.myXEvent.pat_number[i])
skindose_F.append(self.myXEvent.skindose[i])
DAP_F.append(self.myXEvent.DAP[i])
filter_F.append(self.myXEvent.filt[i])
elif self.myXEvent.mode[i] == ord('A'):
scenelength_A.append(self.myXEvent.scenelength[i]/1000.)
meanpower_A.append(pulsepower[i]*self.myXEvent.dutycycle[i])
pulsepower_A.append(pulsepower[i])
skindoserate_A.append(self.myXEvent.skindoserate[i])
dutycycle_A.append(self.myXEvent.dutycycle[i])
time_A.append(self.myXEvent.time[i])
frequency_A.append(self.myXEvent.frequency[i])
watervalue_A.append(self.myXEvent.was[i])
voltage_A.append(self.myXEvent.voltage[i])
current_A.append(self.myXEvent.current[i])
zoom_A.append(self.myXEvent.zoom[i])
rao_A.append(self.myXEvent.rao[i])
cran_A.append(self.myXEvent.cran[i])
patient_number_A.append(self.myXEvent.pat_number[i])
skindose_A.append(self.myXEvent.skindose[i])
DAP_A.append(self.myXEvent.DAP[i])
systemdose_A.append(self.myXEvent.system_dose[i])
SID_A.append(self.myXEvent.SID[i])
filter_A.append(self.myXEvent.filt[i])
###################################################################################
fromDate = str(Startzeit[0]).split(" ")[0]
toDate = str(Startzeit[-1]).split(" ")[0]
#part1
if self.cb1.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
#Voltage histogram
ax = fig.add_subplot(4,3,1)
ax.hist(voltage_F, 50, range =(40, 130))
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Voltage (Fluoro)')
ax = fig.add_subplot(4,3,2)
ax.hist(voltage_A, 50, range =(40, 130))
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Voltage (Acquisition)')
ax = fig.add_subplot(4,3,3)
ax.hist(voltage, 50, range =(40, 130))
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Voltage')
#Current histogram
ax = fig.add_subplot(4,3,4)
ax.hist(current_F, 50, range =(1, 800))
ax.set_xlabel('Current /[mA]',size='x-small')
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title('Current (Fluoro)')
ax = fig.add_subplot(4,3,5)
ax.hist(current_A, 50, range =(1, 800))
ax.set_xlabel('Current /[mA]',size='x-small')
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title('Current (Acquisition)')
ax = fig.add_subplot(4,3,6)
ax.hist(current, 50, range =(1, 800))
ax.set_xlabel('Current /[mA]',size='x-small')
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title('Current')
#Watervalue histogram
ax = fig.add_subplot(4,3,7)
ax.hist(watervalue, 50, range =(1, 500))
ax.set_xlim(1, 500)
ax.set_xlabel('Watervalue /[mm]',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title("Watervalue; [mean, SD]={0}".format( [ round(numpy.mean(watervalue)), round(numpy.std(watervalue)) ]), size='small' )
#SID histogram
ax = fig.add_subplot(4,3,8)
ax.hist(SID, 50)
ax.set_xlabel('SID /[cm]',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title("SID; [mean, SD]={0}".format( [ round(numpy.mean(SID)), round(numpy.std(SID)) ]), size='small' )
#Zoom histogram
ax = fig.add_subplot(4,3,10)
ax.hist(zoom_F, 50, range =(0, 5))
ax.set_xlabel('Zoom',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
ax.set_xlim(0,5)
plt.title('Zoom (Fluoro)')
ax = fig.add_subplot(4,3,11)
ax.hist(zoom_A, 50, range =(0, 5))
ax.set_xlabel('Zoom',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
ax.set_xlim(0,5)
plt.title('Zoom (Acquisition)')
ax = fig.add_subplot(4,3,12)
ax.hist(zoom, 50, range =(0, 5))
ax.set_xlabel('Zoom',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title('Zoom')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part1'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_1.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#################################################################################
#part2
if self.cb2.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
#RAO-angle histogram
ax = fig.add_subplot(4,3,1)
ax.hist(rao, 50)
ax.set_xlabel('RAO-angle /[$\,^{\circ}$]',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title('RAO-angle')
#Cranial-angle histogram
ax = fig.add_subplot(4,3,2)
ax.hist(cran, 50, range=(-50, 50))
ax.set_xlabel('Cranial-angle /[$\,^{\circ}$]',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title('Cranial-angle')
#Pulse-power histogram
ax = fig.add_subplot(4,3,4)
ax.hist(pulsepower_F, 50)
ax.set_xlabel('Pulse-power /[kW]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Pulse-power (Fluoro)')
ax = fig.add_subplot(4,3,5)
ax.hist(pulsepower_A, 50)
ax.set_xlabel('Pulse-power /[kW]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
#ax.set_xlim(0, 50)
plt.title('Pulse-power (Acquisition)')
ax = fig.add_subplot(4,3,6)
ax.hist(pulsepower_nullfrei, 50)
ax.set_xlabel('Pulse-power /[kW]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
#ax.set_xlim(0, 50)
plt.title('Pulse-power')
#Pulse-rate histogram
ax = fig.add_subplot(4,3,7)
ax.hist(frequency_F, 50)
ax.set_xlabel('Pulse rate /[Hz]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Pulse rate (Fluoro)')
ax = fig.add_subplot(4,3,8)
ax.hist(frequency_A, 50)
ax.set_xlabel('Pulse rate /[Hz]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Pulse rate (Acquisition)')
ax = fig.add_subplot(4,3,9)
ax.hist(frequency, 50)
ax.set_xlabel('Pulse rate /[Hz]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Pulse rate')
#Watervalue-voltage plot
ax = fig.add_subplot(4,3,10)
ax.plot(watervalue_F, voltage_F, '.')
ax.set_xlabel('Watervalue /[mm]', size='x-small')
ax.set_ylabel('Voltage /[kV]', size='x-small')
ax.grid(True)
plt.title('Watervalue - voltage (Fluoro)')
ax = fig.add_subplot(4,3,11)
ax.plot(watervalue_A , voltage_A, '.')
ax.set_xlabel('Watervalue /[mm]', size='x-small')
ax.set_ylabel('Voltage /[kV]', size='x-small')
ax.grid(True)
plt.title('Watervalue - voltage (Acquisition)')
ax = fig.add_subplot(4,3,12)
ax.plot(watervalue, voltage , '.')
ax.set_xlabel('Watervalue /[mm]', size='x-small')
ax.set_ylabel('Voltage /[kV]', size='x-small')
ax.grid(True)
plt.title('Watervalue - voltage')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part2'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_2.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#################################################################################
#part3
if self.cb3.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)
plt.rc("axes", titlesize=12)
#Watervalue-current plot
ax = fig.add_subplot(4,3,1)
ax.plot(watervalue_F, current_F, '.')
ax.set_xlabel(r'Watervalue /[mm]', size='x-small')
ax.set_ylabel(r'Current /[mA]', size='x-small')
ax.grid(True)
plt.title(r'Watervalue - current (Fluoro)',size='small')
ax = fig.add_subplot(4,3,2)
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.current[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))] , '.', color='r', label='F1')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.current[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))] , '.', color='b', label='F2')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.current[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))] , '.', color='g', label='FG')
ax.set_xlabel(r'Watervalue /[mm]', size='x-small')
ax.set_ylabel(r'Current /[mA]', size='x-small')
ax.set_xlim(0,450)
ax.legend(loc=4, numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
plt.title(r'Watervalue - current (Acquisition)',size='small')
ax = fig.add_subplot(4,3,3)
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))] , '.', color='r', label='F1')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))] , '.', color='b', label='F2')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))] , '.', color='g', label='FG')
ax.set_xlabel(r'Watervalue /[mm]', size='x-small')
ax.set_ylabel(r'Voltage /[kV]', size='x-small')
ax.set_xlim(0,450)
ax.set_ylim(40,125)
ax.legend(loc=4, numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
plt.title(r'Watervalue - voltage (Acquisition)',size='small')
#Current-voltage plot
ax = fig.add_subplot(4,3,4)
ax.plot(current_F, voltage_F, '.',color='r')
ax.plot(current_A, voltage_A, '.',color='b')
ax.set_xlabel(r'Current /[mA]', size='x-small')
ax.set_ylabel(r'Voltage /[kV]', size='x-small')
ax.grid(True)
plt.title(r'Current - voltage (Fl(r),Acq(b))',size='small')
ax = fig.add_subplot(4,3,5)
if self.events>1:
ax.hist(self.myXEvent.gamma[:self.events])
ax.set_xlabel(r'Gamma', size='x-small')
ax.set_ylabel(r'Number of Occ.', size='x-small')
ax.grid(True)
plt.title(r'Histogramm Gamma [mean,std]=[%2.1f,%2.1f]'%(self.myXEvent.gamma[:self.events].mean(),self.myXEvent.gamma[:self.events].std()),size='small')
####midpoint x-ray
try:
MP=calc_midpoints_from_sample(self.myXEvent.tube_focal_spot_pos_table)
ax = fig.add_subplot(4,3,6)
ax.plot(MP[:,0], MP[:,1] , '.')
ax.set_xlabel(r'x pos', size='x-small')
ax.set_ylabel(r'z pos', size='x-small')
ax.grid(True)
plt.title(r'Distr. of x-ray interceptions (mean: [%2.1f,%2.1f,%2.1f])'%(MP[:,0].mean(),MP[:,1].mean(),MP[:,2].mean()),size='small')
except:
print "Error during calculation of interception points. Skipping plot..."
#Watervalue-SID plot
ax = fig.add_subplot(4,3,7)
ax.plot(watervalue, SID , '.')
ax.set_xlabel(r'Watervalue /[mm]', size='x-small')
ax.set_ylabel(r'SID /[cm]', size='x-small')
ax.grid(True)
plt.title(r'Watervalue - SID',size='small')
#Watervalue-Rao plot
ax = fig.add_subplot(4,3,8)
ax.plot(watervalue, rao , '.')
ax.set_xlabel(r'Watervalue /[mm]', size='x-small')
ax.set_ylabel(r'Rao-angle /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
plt.title(r'Watervalue - Rao',size='small')
#Watervalue-Cran plot
ax = fig.add_subplot(4,3,9)
ax.plot(watervalue, cran , '.')
ax.set_xlabel(r'Watervalue /[mm]', size='x-small')
ax.set_ylabel(r'Cran-angle /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
plt.title(r'Watervalue - Cran',size='small')
#Rao - cran plot
ax = fig.add_subplot(4,3,10)
ax.plot(rao, cran , '.')
ax.set_xlabel(r'Rao-angle /[$\,^{\circ}$]', size='x-small')
ax.set_ylabel(r'Cran-angle /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
plt.title('Rao - Cran',size='small')
#Rao - cran plot
ax = fig.add_subplot(4,3,11)
ax.plot(self.myXEvent.table_height, self.myXEvent.cran , '.')
ax.set_xlabel(r'Table height /[cm]', size='x-small')
ax.set_ylabel(r'Cran-angle /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
ax.set_xlim(-30,30)
plt.title(r'Table height - Cran',size='small')
#SID - cran plot
ax = fig.add_subplot(4,3,12)
ax.plot(self.myXEvent.SID, self.myXEvent.cran , '.')
ax.set_xlabel(r'SID /[cm]', size='x-small')
ax.set_ylabel(r'Cran-angle /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
ax.set_xlim(80,130)
plt.title(r'SID - Cran',size='small')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part3'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_results_3')
outputfile=os.path.join(self.resultsDirSN,name)
if (self.cb_png.GetValue()==False):
plt.savefig(outputfile+'.pdf')
else:
plt.savefig(outputfile+'.png')
plt.close()
#######################################################################################################################
#part4
if self.cb4.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
#Cu-filter histogram
ax = fig.add_subplot(4,3,1)
ax.hist(filter_F, 50)
ax.set_xlabel('Cu-filter /[mm]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Cu-filter (Fluoro)')
ax = fig.add_subplot(4,3,2)
ax.hist(filter_A, 50)
ax.set_xlabel('Cu-filter /[mm]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Cu-filter (Acquisition)')
ax = fig.add_subplot(4,3,3)
ax.hist(filter, 50)
ax.set_xlabel('Cu-filter /[mm]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Cu-filter')
#Skindoserate histogram
skindoserate_A_ = [] #dies dient nur zur besseren Skalierung der plots
skindoserate_F_ = []
skindoserate_nullfrei_ = []
for i in range(len(skindoserate_A)):
skindoserate_A_.append(skindoserate_A[i]/100.)
for i in range(len(skindoserate_nullfrei)):
skindoserate_nullfrei_.append(skindoserate_nullfrei[i]/100.)
for i in range(len(skindoserate_F)):
skindoserate_F_.append(skindoserate_F[i]/100.)
ax = fig.add_subplot(4,3,4)
ax.hist(skindoserate_F_, 50)
ax.set_xlabel('Skindoserate /[100*$\mu$Gy/s]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Skindoserate (Fluoro)')
ax = fig.add_subplot(4,3,5)
ax.hist(skindoserate_A_, 50)
ax.set_xlabel('Skindoserate /[100*$\mu$Gy/s]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Skindoserate (Acquisition)')
ax = fig.add_subplot(4,3,6)
ax.hist(skindoserate_nullfrei_, 50)
ax.set_xlabel('Skindoserate /[100*$\mu$Gy/s]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Skindoserate')
#Systemdose - histogram (Fluoro, <20nGy)
Datum = []
Datum.extend(Datum_array)
Datum.append(11) #hier wird eine Zahl angehängt, um in der Schleife darunter auch den letzten Tag zu erfassen
ModusF = [] #zählt, wie oft Modus F auftritt
ModusF_day = [] #gibt an, wie oft Modus F pro Tag auftritt
for i in range(len(Datum)-1):
if self.myXEvent.mode[i] == ord('F'):
ModusF.append(0)
if Datum[i] != Datum[i+1]:
ModusF_day.append(len(ModusF))
Kopie = []
for i in range(len(ModusF_day)):
Kopie.append(ModusF_day[i])
for i in range(1, len(ModusF_day)):
ModusF_day[i] = Kopie[i] - Kopie[i-1] #nur die Differenzen interessieren uns
Vektor2 = []
Vektor3 = []
for i in range(len(Datum)-1): #hier wird die Anzahl der Fluoro-Ereignisse <20nGy pro Tag ermittelt
if self.myXEvent.SysDose_with_ZDF[i] != 0:
if self.myXEvent.SysDose_with_ZDF[i] < 20: #<20nGy
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.wPawMode[i] == 5:
Vektor3.append(1)
if Datum[i] != Datum[i+1]:
Vektor2.append(len(Vektor3)) #gibt an, wie oft Modus F pro Tag auftritt
Kopie = []
for i in range(len(Vektor2)):
Kopie.append(Vektor2[i])
for i in range(1, len(Vektor2)):
Vektor2[i] = Kopie[i] - Kopie[i-1]
Vektor4 = []
Vektor5 = []
for i in range(len(Datum)-1): #hier wird die Anzahl der Fouoro-Ereignisse <20nGy bei 125 kV pro Tag ermittelt
if self.myXEvent.SysDose_with_ZDF[i] != 0:
if self.myXEvent.SysDose_with_ZDF[i] < 20: #<20nGy
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.wPawMode[i] == 5:
if self.myXEvent.voltage[i] == 125: #125kV
Vektor4.append(0)
if Datum[i] != Datum[i+1]:
Vektor5.append(len(Vektor4))
Kopie = []
for i in range(len(Vektor5)):
Kopie.append(Vektor5[i])
for i in range(1, len(Vektor5)):
Vektor5[i] = Kopie[i] - Kopie[i-1]
plotvektor = []
for i in range(len(time_F)):
if self.myXEvent.SysDose_with_ZDF[i] != 0:
if self.myXEvent.SysDose_with_ZDF[i] < 50: #<50nGy
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.wPawMode[i] == 5:
plotvektor.append(self.myXEvent.SysDose_with_ZDF[i])
if plotvektor.__len__()>0:
ax = fig.add_subplot(4,3,7)
ax.hist(plotvektor, 50)
ax.set_xlabel('Systemdose /[nGy]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Systemdose (<50nGy, Fluoro)')
#Pulse-duration histogram
ax = fig.add_subplot(4,3,8)
ax.hist(xtime, 50)
ax.set_xlabel('Pulse-duration /[ms]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Pulse-duration')
#Dutycycle-histogramm
ax = fig.add_subplot(4,3,9)
ax.hist(dutycycle, 50)
ax.set_xlabel('Dutycycle', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Dutycycle')
#Scenelength-histogramm
ax = fig.add_subplot(4,3,10)
ax.hist(scenelength_F, 50)
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Scenelength (Fluoro)')
ax = fig.add_subplot(4,3,11)
ax.hist(scenelength_A, 50)
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Scenelength (Acquisition)')
ax = fig.add_subplot(4,3,12)
ax.hist(scenelength, 50)
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Scenelength')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part4'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
if len(Vektor5) == 0:
vvv = 0
else:
vvv = round(numpy.mean(Vektor5))
fig.text(0.1, 0.05, 'Systemdose (Fluoro <20nGy @125kV/day): '+str(vvv)+' Systemdose (Fluoro <20nGy/day): '+str(round(numpy.mean(Vektor2)))+' Systemdose (Fluoro/day): '+str(round(numpy.mean(ModusF_day))) )
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_4.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#################################################################################################################################
#part5
if self.cb5.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)
plt.rc("axes", titlesize=12)
#Patient-studytime histogramm
aaa = []
ccc = []
ccc.append(Time[0]) #Beginn der Untersuchung des ersten Patienten
for i in range(1, len(SID)):
if self.myXEvent.pat_number[i]!=self.myXEvent.pat_number[i+1]:
ccc.append(Time[i-1]) #Ende der Untersuchung des bisherigen Patienten
ccc.append(Time[i]) #Beginn der Untersuchung des neuen Patienten
ccc.append(Time[len(Time)-1]) #Ende der Untersuchung des letzten Patienten
for i in range(0,len(ccc),2):
aaa.append(ccc[i+1]-ccc[i]) #Speichert die Zeit zwischen Beginn und Ende der Untersuchungszeit eines Patienten
for i in range(len(aaa)): #Umrechnung in Minuten
aaa[i] = aaa[i]/60.
ax = fig.add_subplot(4,3,1)
ax.hist(aaa, 50)
ax.set_xlabel('Patient-studytime /[min]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title("Patient-studytime [mean, patients]={0}".format([round(mean(aaa)), self.myXEvent.pat_number[len(SID)-1]]), size='x-small')
#BE/day
aaa = [0]
for i in range(len(Datum_array)-1):
if Datum_array[i] != Datum_array[i+1]:
aaa[-1]+=self.myXEvent.BE_total[i]
aaa.append(0)
else:
aaa[-1]+=self.myXEvent.BE_total[i]
aaa[-1]+=self.myXEvent.BE_total[i]
anzahl_Tage = len(aaa)
ax = fig.add_subplot(4,3,2)
ax.hist(aaa, 50)
ax.set_xlabel('BE/day', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title("BE/day [total BE, mean BE, days]={0}".format( [round(self.myXEvent.BE_total.sum()),round(numpy.mean(aaa)),anzahl_Tage] ), size='x-small')
#BE / focus /day
ax = fig.add_subplot(4,3,3)
small_BE_per_day = self.myXEvent.BE_F1.sum()/day_total #es soll der Wert pro Tag dargestellt werden
large_BE_per_day = self.myXEvent.BE_F2.sum()/day_total
micro_BE_per_day = self.myXEvent.BE_FG.sum()/day_total
ax.bar((1,2,3),(small_BE_per_day,large_BE_per_day,micro_BE_per_day),0.3)
ax.text(1, 1, round(small_BE_per_day),size='x-small',color='red')
ax.text(2, 1, round(large_BE_per_day),size='x-small',color='red')
ax.text(3, 1, round(micro_BE_per_day),size='x-small',color='red')
ax.set_xlabel('Focus', size='x-small')
ax.set_ylabel('Mean BE / day', size='x-small')
ax.grid(True)
ax.set_xlim(1,3.3)
plt.xticks([1, 2, 3], ['small', 'large', 'micro'])
plt.title("Total BE / day: {0} (all days)".format(round(small_BE_per_day+large_BE_per_day+micro_BE_per_day)),size='x-small')
#Scenelength - pulse-power
ax = fig.add_subplot(4,3,4)
ax.plot(scenelength_F ,pulsepower_F, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-power /[kW]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Pulse-power (F)')
ax = fig.add_subplot(4,3,5)
ax.plot(scenelength_A ,pulsepower_A, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-power /[kW]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Pulse-power (A)')
ax = fig.add_subplot(4,3,6)
ax.plot(scenelength, pulsepower_nullfrei, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-power /[kW]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Pulse-power')
#Scenelengt - mean-power
ax = fig.add_subplot(4,3,7)
ax.plot(scenelength_F, meanpower_F, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Mean power /[kW]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Mean power (F)')
ax = fig.add_subplot(4,3,8)
ax.plot(scenelength_A, meanpower_A, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Mean power /[kW]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Mean power (A)')
ax = fig.add_subplot(4,3,9)
ax.plot(scenelength, meanpower, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Mean power /[kW]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Mean power')
#Scenelength - dutycycle
ax = fig.add_subplot(4,3,10)
ax.plot(scenelength_F, dutycycle_F, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Dutycycle /[%]', size='x-small')
ax.grid(True)
plt.title('Scenelength - dutycycle (F)')
ax = fig.add_subplot(4,3,11)
ax.plot(scenelength_A , dutycycle_A, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Dutycycle /[%]', size='x-small')
ax.grid(True)
plt.title('Scenelength - dutycycle (A)')
ax = fig.add_subplot(4,3,12)
ax.plot(scenelength , dutycycle, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Dutycycle /[%]', size='x-small')
ax.grid(True)
plt.title('Scenelength - dutycycle')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part5'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_results_5.pdf')
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
###############################################################################################################
#part6
if self.cb6.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
#Scenelength - Pulse-duration
ax = fig.add_subplot(4,3,1)
ax.plot(scenelength_F , time_F, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-duration /[ms]', size='x-small')
ax.grid(True)
ax.set_ylim(min(time_F)-2, max(time_F)+2)
plt.title('Scenelength - Pulse-duration (F)')
ax = fig.add_subplot(4,3,2)
ax.plot(scenelength_A , time_A, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-duration /[ms]', size='x-small')
ax.set_ylim(0.5, max(self.myXEvent.time))
ax.grid(True)
plt.title('Scenelength - Pulse-duration (A)')
ax = fig.add_subplot(4,3,3)
ax.plot(scenelength, xtime, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-duration /[ms]', size='x-small')
ax.set_ylim(0.5, max(self.myXEvent.time))
ax.grid(True)
plt.title('Scenelength - Pulse-duration')
#Pulse-rate - Pulse-duration
ax = fig.add_subplot(4,3,4)
ax.plot(frequency_F, time_F, '.')
ax.set_xlabel('Pulse-rate /[Hz]', size='x-small')
ax.set_ylabel('Pulse-duration /[ms]', size='x-small')
ax.grid(True)
plt.title('Pulse-rate - Pulse-duration (F)')
ax = fig.add_subplot(4,3,5)
ax.plot(frequency_A , time_A, '.')
ax.set_xlabel('Pulse-rate /[Hz]', size='x-small')
ax.set_ylabel('Pulse-duration /[ms]', size='x-small')
ax.grid(True)
plt.title('Pulse-rate - Pulse-duration (A)')
ax = fig.add_subplot(4,3,6)
ax.plot(frequency, xtime, '.')
ax.set_xlabel('Pulse-rate /[Hz]', size='x-small')
ax.set_ylabel('Pulse-duration /[ms]', size='x-small')
ax.grid(True)
plt.title('Pulse-rate - Pulse-duration')
#Scenelength - Pulse-rate
ax = fig.add_subplot(4,3,7)
ax.plot(scenelength_F , frequency_F, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-rate /[Hz]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Pulse-rate (F)')
ax = fig.add_subplot(4,3,8)
ax.plot(scenelength_A , frequency_A, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-rate /[Hz]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Pulse-rate (A)')
ax = fig.add_subplot(4,3,9)
ax.plot(scenelength, frequency, '.')
ax.set_xlabel('Scenelength /[s]', size='x-small')
ax.set_ylabel('Pulse-rate /[Hz]', size='x-small')
ax.grid(True)
plt.title('Scenelength - Pulse-rate')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part6'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_6.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
######################################################################################################################
#part7
if self.cb7.GetValue() or self.cb0.GetValue():
num_events=len(SID)
fig = plt.figure(figsize=(14,19))
#skindose/study histogram
skindose_F_study = numpy.array([])
skindose_A_study = numpy.array([])
num_ACQ_study = []
fl_time_study = []
last_i=0
temp_numACQ =0
temp_fl_time =0
for i in range(0, num_events):
if self.myXEvent.mode[i]==ord('A'):
temp_numACQ+=1
if self.myXEvent.mode[i]==ord('F'):
temp_fl_time+=self.myXEvent.scenelength[i] #in sec
if self.myXEvent.pat_number[i]!=self.myXEvent.pat_number[i+1]:
tmp=self.myXEvent.skindose*(self.myXEvent.mode==ord('F'))
skindose_F_study=numpy.append(skindose_F_study,sum(tmp[last_i:i+1]))
tmp=self.myXEvent.skindose*(self.myXEvent.mode==ord('A'))
skindose_A_study=numpy.append(skindose_A_study,sum(tmp[last_i:i+1]))
num_ACQ_study.append(temp_numACQ)
temp_numACQ=0
fl_time_study.append(temp_fl_time)
temp_fl_time=0
last_i=i
skindose_A_study=skindose_A_study
skindose_F_study=skindose_F_study
skindose_total_study = skindose_A_study+skindose_F_study #in Gy
ax = fig.add_subplot(4,3,1)
ax.hist(skindose_total_study/1000000., 50)
ax.set_xlabel('Skindose/study /[Gy]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Skindose/study')
self.num_studies=skindose_total_study.__len__()
#Skindose/study Tortendiagramm
skindose_3D = []
_3D = []
DAP_3D = []
for i in range(len(SID)):
if self.myXEvent._3Dmode[i] != 'NO' and self.myXEvent._3Dmode[i] != 'no3d':
skindose_3D.append(self.myXEvent.skindose[i])
DAP_3D.append(self.myXEvent.DAP[i])
_3D.append(self.myXEvent.skindose[i])
fracs = []
fracs.append(sum(skindose_F)/sum(skindose))
fracs.append(sum(skindose_A)/sum(skindose))
fracs.append(sum(skindose_3D)/sum(skindose))
ax = fig.add_subplot(4,3,4)
labels = 'Fluoro', 'Acquisition', '3D'
ax.pie(fracs, labels=labels, colors=('r', 'g', 'y'), autopct='%1.1f%%', shadow=True)
plt.title('Skindose/study')
#skindose/study
s_F = sum(skindose_F)
s_F_study = s_F/self.num_studies #Division durch die Anzahl der untersuchtern Patienten
s_A = sum(skindose_A)
s_A_study = s_A/self.num_studies
s_3D = sum(_3D)
s_3D_study = s_3D/self.num_studies
total = sum(skindose)/self.num_studies
Vektor = []
for i in range(len(Datum_array)-1): #die Anzahl der Tage wird ermittelt; zunaechst anhand der "Tageswechsel"
if Datum_array[i] != Datum_array[i+1]:
Vektor.append(1)
Vektor.append(1) #Tage = Tageswechsel + 1
tage = len(Vektor)
ax = fig.add_subplot(4,3,7)
ax.axis('off')
ax.text(0.15, 0.90, u"FL /[mGy]: {0}".format(round(0.001*s_F_study, 2))) #von mikro auf milli-Gy umgerechnet
ax.text(0.15, 0.85, u"Percentage /[%]: {0}".format(round(100*(s_F_study/total)))) #in Prozent umgerechnet
ax.text(0.15, 0.75, u"ACQ /[mGy]: {0}".format(round(0.001*s_A_study, 2)))
ax.text(0.15, 0.70, u"Percentage /[%]: {0}".format(round(100*(s_A_study/total), 2)))
ax.text(0.15, 0.60, u"3D /[mGy]: {0}".format(round(0.001*s_3D_study, 2)))
ax.text(0.15, 0.55, U"Percentage /[%]: {0}".format(round(100*(s_3D_study/total), 2)))
ax.text(0.15, 0.45, u"--------------")
ax.text(0.15, 0.35, u"Total /[mGy]: {0}".format(round(0.001*total, 2)))
ax.text(0.15, 0.25, u"Skindose/day /[mGy]: {0}".format(round(0.001*sum(skindose)/tage, 2)))
ax.text(0.15, 0.15, u"Number of studies: {0}".format(self.num_studies))
plt.title('Skindose/study')
#DAP/study histogram
DAP_F_study = numpy.array([])
DAP_A_study = numpy.array([])
last_i=0
for i in range(0, num_events):
if self.myXEvent.pat_number[i]!=self.myXEvent.pat_number[i+1]:
tmp=self.myXEvent.DAP*(self.myXEvent.mode==ord('F'))
DAP_F_study=numpy.append(DAP_F_study,sum(tmp[last_i:i+1]))
tmp=self.myXEvent.DAP*(self.myXEvent.mode==ord('A'))
DAP_A_study=numpy.append(DAP_A_study,sum(tmp[last_i:i+1]))
last_i=i
DAP_A_study=DAP_A_study
DAP_F_study=DAP_F_study
DAP_total_study = DAP_A_study+DAP_F_study #in Gy
ax = fig.add_subplot(4,3,2)
ax.hist(DAP_total_study/1000./100., 50)
ax.set_xlabel('DAP/study /[mGy*m^2]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('DAP/study')
#DAP/study Tortendiagramm
fracs = []
fracs.append(sum(DAP_F)/sum(DAP))
fracs.append(sum(DAP_A)/sum(DAP))
fracs.append(sum(DAP_3D)/sum(DAP))
ax = fig.add_subplot(4,3,5)
labels = 'Fluoro', 'Acquisition', '3D'
ax.pie(fracs, labels=labels, colors=('r', 'g', 'y'), autopct='%1.1f%%', shadow=True)
plt.title('DAP/study')
#DAP/study
s_F = sum(DAP_F)
s_F_study = s_F/self.num_studies #Division durch die Anzahl der untersuchten Patienten
s_A = sum(DAP_A)
s_A_study = s_A/self.num_studies
_3D = []
for i in range(len(SID)):
if self.myXEvent._3Dmode[i] != 'NO' and self.myXEvent._3Dmode[i] != 'no3d':
_3D.append(self.myXEvent.DAP[i])
s_3D = sum(_3D)
s_3D_study = s_3D/self.num_studies
total = sum(DAP)/self.num_studies
ax = fig.add_subplot(4,3,8)
ax.axis('off')
ax.text(0.15, 0.90, u"FL /[uGy m²]: {0}".format(round(10.*s_F_study/1000., 2))) #0.01 stammt als Faktor aus der .csv-Datei
ax.text(0.15, 0.85, u"Percentage /[%]: {0}".format(round(100.*s_F_study/total)))
ax.text(0.15, 0.75, u"ACQ /[uGy m²]: {0}".format(round(10.*s_A_study/1000., 2)))
ax.text(0.15, 0.70, u"Percentage /[%]: {0}".format(round(100.*s_A_study/total, 2)))
ax.text(0.15, 0.65, u"3D /[uGy m²]: {0}".format(round(10.*s_3D_study/1000.), 2))
ax.text(0.15, 0.60, U"Percentage /[%]: {0}".format(round(100.*s_3D_study/total, 2)))
ax.text(0.15, 0.55, U"DAP/Fluoro /[uGy m²]: {0}".format(round(0.01*s_F/len(zoom_F), 2)))
ax.text(0.15, 0.50, U"DAP/Acq /[uGy m²]: {0}".format(round(0.01*s_A/len(zoom_A), 2)))
ax.text(0.15, 0.45, u"--------------")
ax.text(0.15, 0.35, u"Total /[uGy m²]: {0}".format(round(10.*total/1000., 2)))
ax.text(0.15, 0.25, u"DAP/day /[uGy m²]: {0}".format(round(10.*(sum(DAP)/tage)/1000., 2)))
plt.title('DAP/study')
#Textbox
_3D = []
for i in range(len(SID)):
if self.myXEvent._3Dmode[i] != 'NO' and self.myXEvent._3Dmode[i] != 'no3d':
_3D.append(1)
ax = fig.add_subplot(4,3,12)
ax.axis('off')
ax.text(0.15, 0.9, u"Mean FL-time/study /[s]: {0}".format(round(sum(scenelength_F)/self.num_studies)))
ax.text(0.15, 0.85, u"Mean # ACQ/study: {0}".format(round(len(scenelength_A)/self.num_studies)))
ax.text(0.15, 0.8, u"Mean # 3D/study: {0}".format(round(len(_3D)/self.num_studies)))
ax.text(0.15, 0.75, u"# studies: {0}".format(self.num_studies))
ax.text(0.15, 0.7, u"ACQ mean time /[s]: {0}".format(round(mean(scenelength_A))))
ax.text(0.15, 0.65, u"FL mean time /[s]: {0}".format(round(mean(scenelength_F))))
ax.text(0.15, 0.6, u"ACQ total time /[s]: {0}".format(round(sum(scenelength_A))))
ax.text(0.15, 0.55, u"FL total time /[s]: {0}".format(round(sum(scenelength_F))))
ax.text(0.15, 0.5, "ACQ events: {0}".format(len(zoom_A)))
ax.text(0.15, 0.45, "Fl events: {0}".format(len(zoom_F)))
ax.text(0.15, 0.4, "3D events: {0}".format(len(_3D)))
#10R/min FL Limit - 34cm in front of FD
_10R = []
for i in range(1, len(SID)):
if self.myXEvent._10Rlimit[i] != 0:
_10R.append(self.myXEvent._10Rlimit[i])
ax = fig.add_subplot(4,3,3)
ax.hist(_10R, 20)
ax.set_xlabel('Skindose /[R/min]', size='x-small')
ax.set_ylabel('Fluoro events /#', size='x-small')
ax.grid(True)
plt.title('10R/min FL limit - 34cm in front of FD')
#time/study histogram
ax = fig.add_subplot(4,3,9)
ax.hist(self.myXEvent.pat_time, 50)
ax.set_xlabel('time/study [min]', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title("time/study; [mean, SD]={0} min".format( [ round(numpy.mean(self.myXEvent.pat_time)), round(numpy.std(self.myXEvent.pat_time)) ]), size='small' )
#Spreading of radiation events
f_s = []
f_l = []
f_m = []
a_s = []
a_l = []
a_m = []
for i in range(len(SID)): #es wird nach focus und Fluoro/Acquisition aussortiert
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.focus[i] == ord('S'):
f_s.append(1)
elif self.myXEvent.focus[i] == ord('L'):
f_l.append(1)
else:
f_m.append(1)
if self.myXEvent.mode[i] == ord('A'):
if self.myXEvent.focus[i] == ord('S'):
a_s.append(1)
elif self.myXEvent.focus[i] == ord('L'):
a_l.append(1)
else:
a_m.append(1)
total = sum(f_s)+sum(f_l)+sum(f_m)+sum(a_s)+sum(a_l)+sum(a_m)
ax = fig.add_subplot(4,3,10)
ax.axis('off')
ax.text(0.15, 0.9, u"Small Focus /[%]" )
ax.text(0.30, 0.85, u"Fluoro: {0}".format(round(int(100*(sum(f_s)/total)),2))) #der Prozentsatz ergibt sich durch Summenbildung, da die Vektoren nur aus Eins-Einträgen bestehen
ax.text(0.30, 0.8, u"Aquisition: {0}".format(round(int(100*(sum(a_s)/total)),2)))
ax.text(0.15, 0.7, u"Large Focus /[%]")
ax.text(0.30, 0.65, u"Fluoro: {0}".format(round(int(100*(sum(f_l)/total)),2)))
ax.text(0.30, 0.6, u"Acquisition: {0}".format(round(int(100*(sum(a_l)/total)),2)))
ax.text(0.15, 0.5, u"Micro Focus /[%]")
ax.text(0.30, 0.45, u"Fluoro: {0}".format(round(int(100*(sum(f_m)/total)),2)))
ax.text(0.30, 0.4, u"Acquisition: {0}".format(round(int(100*(sum(a_m)/total)),2)))
plt.title('Spreading of radiation events')
#Summ. of Radiation time per focus & mode
f_s = []
f_l = []
f_m = []
a_s = []
a_l = []
a_m = []
for i in range(len(SID)): #es wird nach focus und Fluoro/Acquisition aussortiert
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.focus[i] == ord('S'):
f_s.append(self.myXEvent.scenelength[i])
elif self.myXEvent.focus[i] == ord('L'):
f_l.append(self.myXEvent.scenelength[i])
else:
f_m.append(self.myXEvent.scenelength[i])
if self.myXEvent.mode[i] == ord('A'):
if self.myXEvent.focus[i] == ord('S'):
a_s.append(self.myXEvent.scenelength[i])
elif self.myXEvent.focus[i] == ord('L'):
a_l.append(self.myXEvent.scenelength[i])
else:
a_m.append(self.myXEvent.scenelength[i])
ax = fig.add_subplot(4,3,11)
ax.axis('off')
ax.text(0.15, 0.9, u"Small Focus /[s]" )
ax.text(0.30, 0.85, u"Fluoro: {0}".format(round((sum(f_s)/1000./day_total),2)))
ax.text(0.30, 0.8, u"Aquisition: {0}".format(round(sum(a_s)/1000./day_total,2)))
ax.text(0.15, 0.7, u"Large Focus /[s]")
ax.text(0.30, 0.65, u"Fluoro: {0}".format(round(sum(f_l)/1000./day_total,2)))
ax.text(0.30, 0.6, u"Acquisition: {0}".format(round(sum(a_l)/1000./day_total,2)))
ax.text(0.15, 0.5, u"Micro Focus /[s]")
ax.text(0.30, 0.45, u"Fluoro: {0}".format(round(sum(f_m)/1000./day_total,2)))
ax.text(0.30, 0.4, u"Acquisition: {0}".format(round(sum(a_m)/1000./day_total,2)))
plt.title('Radiation time/day/focus (all days)')
#Altenative Acquisition
fracs = []
fracs.append(len(alternative_acquisition))
fracs.append(len(DAP_A)-len(alternative_acquisition))
ax = fig.add_subplot(4,3,6)
labels = 'ACQ 2', 'ACQ 1'
ax.pie(fracs, labels=labels, autopct='%1.1f%%', shadow=True)
plt.title('Alternative Acquisition')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part7'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_7.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#generate studyreport
filename='XA'+str(self.myXEvent.SN)+'_study_report_plane_'+self.plane+'.csv'
outputfile=os.path.join(self.resultsDirSN,filename)
fw = open(outputfile, "w")
datastr= 'study, Start time, End time, Duration /[min],Skindose F/[mGy], Skindose A/[mGy], Skindose Tot/[mGy], Fluoro time /[min], #Acq, DAP Fluoro/[uGy*m*m], DAP Acq /[uGy*m*m], DAP Total/[uGy*m*m]\n'
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
datastr=datastr.replace(',',';')
fw.write(datastr)
datastr=''
for study in range(0,self.num_studies):
datastr = '%d' % (study+1)
datastr+= ',%s' % time.ctime(self.myXEvent.pat_in_time[study])
datastr+= ',%s' % time.ctime(self.myXEvent.pat_out_time[study])
datastr+= ',%d' % int16(self.myXEvent.pat_time[study]) #in min
datastr+= ',%5.2f' % (skindose_F_study[study]/1000.)
datastr+= ',%5.2f' % (skindose_A_study[study]/1000.)
datastr+= ',%5.2f' % (skindose_total_study[study]/1000.)
datastr+= ',%5.2f' % (fl_time_study[study]/60./1000.) #min
datastr+= ',%d' % (num_ACQ_study[study])
datastr+= ',%5.2f' % (DAP_F_study[study]/100.)
datastr+= ',%5.2f' % (DAP_A_study[study]/100.)
datastr+= ',%5.2f' % (DAP_total_study[study]/100.)
datastr+= '\n'
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
datastr=datastr.replace(',',';').replace('.',',')
fw.write(datastr) #'%d,%s,%s,%d,%5.2f,%5.2f,%5.2f,%5.2f,%d,%5.2f,%5.2f,%5.2f\n',,studies_skindose(i,2)/1000.,(studies_skindose(i,1)+studies_skindose(i,2))/1000.,FL_time(i)/60,ACQ_sum(i),studies_doseareaprod(i,1)/100,studies_doseareaprod(i,2)/100.,(studies_doseareaprod(i,1)+studies_doseareaprod(i,2))/100);
fw.close()
################################################################
#part8
if self.cb8.GetValue() or self.cb0.GetValue():
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_results_8.pdf')
namef1 = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_F1_results_8.pdf')
namef2 = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_F2_results_8.pdf')
namefg = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_FG_results_8.pdf')
if (self.cb_png.GetValue()==False):
pdf = PdfPages(name)
#Verlauf Dosisausbeute F1, 125kV, 100 cm Abstand - Todo Dosisabfall ab 2000 BE?
fig = plt.figure(figsize=(14,10))
ax = fig.add_subplot(111)
datestrings = TIME
dosisausbeute = []
dosisausbeute_date=[]
tempy=[]
mean_dose=[]
std_dose=[]
mean_dose_date=[]
first_event=True
indx=numpy.nonzero(self.myXEvent.frequency[0:self.events]==0.01)
relevant_data=numpy.delete(self.myXEvent.dose_per_mAs[0:self.events],indx[0]) #remove Single Acq
relevant_data[np.isnan(relevant_data)]=0
tot_mean=relevant_data.mean()
tot_median=numpy.median(relevant_data)
tot_std=relevant_data.mean()
for i in range(len(SID)):
if self.myXEvent.focus[i] == ord('S'):
if self.myXEvent.scenelength[i] > 1000. and self.myXEvent._3Dmode[i]=='no3d':
if self.myXEvent.frequency[i] != 0.01 and self.myXEvent.skindoserate[i]>0 and abs(1.-self.myXEvent.current[i]/self.myXEvent.soll_mA[i])<0.1 and self.myXEvent.current[i]>20.:
if self.myXEvent.time[i] > 3:
dosisausbeute.append(self.myXEvent.dose_per_mAs[i])
dosisausbeute_date.append(TIME[i])
if first_event:
old_date=TIME[i]
first_event=False
if (TIME[i])[8:10]==old_date[8:10]: #same day
if math.fabs(self.myXEvent.dose_per_mAs[i]-tot_mean)<=2*tot_std: #nur Daten verwenden, die keine Ausreisser sind
tempy.append(self.myXEvent.dose_per_mAs[i])
else:
if len(tempy)>0:
mean_dose.append(numpy.array(tempy).mean())
std_dose.append(numpy.array(tempy).std())
mean_dose_date.append(old_date)
tempy=[]
old_date=TIME[i]
if len(tempy)>0: #last day
mean_dose.append(numpy.array(tempy).mean())
std_dose.append(numpy.array(tempy).std())
mean_dose_date.append(old_date)
NN=len(dosisausbeute)
soll=self.get_dose_efficiency_nominal()
#lineare Regression
if len(dosisausbeute)>0:
r = pylab.date2num([dateutil.parser.parse(s) for s in dosisausbeute_date])
t = pylab.date2num([dateutil.parser.parse(s) for s in mean_dose_date])
tt= linspace(pylab.date2num(dateutil.parser.parse(TIME[0])),pylab.date2num(dateutil.parser.parse(TIME[-1])), 100)
sollwerte = [soll for i in tt]
ax.plot_date(r, dosisausbeute,linestyle='.', color='b', label='Xray Events')
ax.plot_date(tt, sollwerte, marker='', linestyle='solid', color='g', linewidth=2.0, label='Nominal value')
if len(mean_dose)>1:
pol = numpy.polyfit(t, mean_dose , 1)
mean_value_fit = numpy.polyval(pol, tt)
ax.plot_date(t, mean_dose , linestyle='.',markersize=10.0, color='r', label='Day mean')
ax.plot_date(tt, mean_value_fit, marker='' , linestyle='--', color='r', linewidth=2.0, label='RMS Fit')
ax.set_xlabel('Date', size='x-small')
fig.autofmt_xdate()
ax.set_ylabel(r'Dose efficiency /[$\mu$Gy/mAs]', size='x-small')
ax.grid(True)
ax.set_ylim(0,max(max(dosisausbeute),soll)*1.2)
legend(bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0.)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
#Finger Filter
if len(fingerfilter_in)>0:
xxtime = [dateutil.parser.parse(z) for z in fingerfilter_in]
fingerfilter_in_val = [15 for z in fingerfilter_in]
fingerfilter_in_time = pylab.date2num(xxtime)
ax.plot_date(fingerfilter_in_time,fingerfilter_in_val, marker='+',markersize=6, linestyle='',color='green', alpha=0.5,label='Finger_filter_in')
#Filter reset
if len(filter_reset)>0:
xxtime = [dateutil.parser.parse(z) for z in filter_reset]
filter_reset_val = [15 for z in filter_reset]
filter_reset_time = pylab.date2num(xxtime)
ax.plot_date(filter_reset_time,filter_reset_val, marker='o',markersize=6, linestyle='',color='grey', alpha=0.5,label='Filter_reset')
#r = matplotlib.pyplot.scatter(pylab.date2num(dates), Dosisausbeute, colorbar_voltage)
plt.title('Time Trend Dose Efficiency F1, 125kV, 0.0mm Cu, 100 cm distance')
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
fig.text(0.85, 0.75,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.75-offset*0.02,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)
+' part8'
+' Radiation events on plane '
+str(self.plane)
+':'+' '+str(len(SID))
+' ('+str(len(total_events))
+' total)'+' Days: '+str(day_total)
+' Start: '+str(Startzeit[0])
+' End: '+str(Startzeit[len(Startzeit)-1])
+'\n Mean Value: %4.2f' %numpy.array(dosisausbeute).mean()
+r'$\pm$ %4.2f' %numpy.array(dosisausbeute).std()+r'$\mu$Gy/mAs'
+r' (Nominal: '+str(soll)+r'$\mu$Gy/mAs)'
+r' (Median: %4.2f $\mu$Gy/mAs)' %numpy.median(dosisausbeute)
, horizontalalignment='center', verticalalignment='center')
fig.subplots_adjust(left=None, bottom=None, right=0.8, top=None, wspace=None, hspace=0.5)
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(namef1[:-3]+'png')
#ramPlot = cStringIO.StringIO()
#fig.savefig(ramPlot)
#ramPlot.read()
#ramPlot.seek( 0 )
#img=Image.open( ramPlot )
#img.load()
#r, g, b, a = img.split()
#img = Image.merge("RGB", (r, g, b))
#img.save(namef1, "PDF", resolution=300.0)
del fig
############################################################################
#Verlauf Dosisausbeute F2, 125kV, 100 cm Abstand - Todo Dosisabfall ab 2000 BE?
fig = plt.figure(figsize=(14,10))
ax = fig.add_subplot(111)
datestrings = TIME
dosisausbeute = []
dosisausbeute_date=[]
tempy=[]
mean_dose=[]
std_dose=[]
mean_dose_date=[]
first_event=True
indx=numpy.nonzero(self.myXEvent.frequency[0:self.events]==0.01)
relevant_data=numpy.delete(self.myXEvent.dose_per_mAs[0:self.events],indx[0]) #remove Single Acq
relevant_data[np.isnan(relevant_data)]=0
tot_mean=relevant_data.mean()
tot_median=numpy.median(relevant_data)
tot_std=relevant_data.mean()
for i in range(len(SID)):
if self.myXEvent.focus[i] == ord('L'):
if self.myXEvent.scenelength[i] > 1000. and self.myXEvent._3Dmode[i]=='no3d':
if self.myXEvent.frequency[i] != 0.01 and self.myXEvent.skindoserate[i]>0 and abs(1.-self.myXEvent.current[i]/self.myXEvent.soll_mA[i])<0.1 and self.myXEvent.current[i]>20.:
if self.myXEvent.time[i] > 3:
dosisausbeute.append(self.myXEvent.dose_per_mAs[i])
dosisausbeute_date.append(TIME[i])
if first_event:
old_date=TIME[i]
first_event=False
if (TIME[i])[8:10]==old_date[8:10]: #same day
if math.fabs(self.myXEvent.dose_per_mAs[i]-tot_mean)<=2*tot_std: #nur Daten verwenden, die keine Ausreisser sind
tempy.append(self.myXEvent.dose_per_mAs[i])
else:
if len(tempy)>0:
mean_dose.append(numpy.array(tempy).mean())
std_dose.append(numpy.array(tempy).std())
mean_dose_date.append(old_date)
tempy=[]
old_date=TIME[i]
if len(tempy)>0: #last day
mean_dose.append(numpy.array(tempy).mean())
std_dose.append(numpy.array(tempy).std())
mean_dose_date.append(old_date)
NN=len(dosisausbeute)
soll=self.get_dose_efficiency_nominal()
#lineare Regression
if len(dosisausbeute)>0:
r = pylab.date2num([dateutil.parser.parse(s) for s in dosisausbeute_date])
t = pylab.date2num([dateutil.parser.parse(s) for s in mean_dose_date])
tt= linspace(pylab.date2num(dateutil.parser.parse(TIME[0])),pylab.date2num(dateutil.parser.parse(TIME[-1])), 100)
sollwerte = [soll for i in tt]
ax.plot_date(r, dosisausbeute,linestyle='.', color='b', label='Xray Events')
ax.plot_date(tt, sollwerte, marker='', linestyle='solid', color='g', linewidth=2.0, label='Nominal value')
if len(mean_dose)>1:
pol = numpy.polyfit(t, mean_dose , 1)
mean_value_fit = numpy.polyval(pol, tt)
ax.plot_date(t, mean_dose , linestyle='.',markersize=10.0, color='r', label='Day mean')
ax.plot_date(tt, mean_value_fit, marker='' , linestyle='--', color='r', linewidth=2.0, label='RMS Fit')
ax.set_xlabel('Date', size='x-small')
fig.autofmt_xdate()
ax.set_ylabel(r'Dose efficiency /[$\mu$Gy/mAs]', size='x-small')
ax.grid(True)
ax.set_ylim(0,max(max(dosisausbeute),soll)*1.2)
legend(bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0.)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
#r = matplotlib.pyplot.scatter(pylab.date2num(dates), Dosisausbeute, colorbar_voltage)
plt.title('Time Trend Dose Efficiency F2, 125kV, 0.0mm Cu, 100 cm distance')
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
fig.text(0.85, 0.75,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.75-offset*0.02,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)
+' part8'
+' Radiation events on plane '
+str(self.plane)
+':'+' '+str(len(SID))
+' ('+str(len(total_events))
+' total)'+' Days: '+str(day_total)
+' Start: '+str(Startzeit[0])
+' End: '+str(Startzeit[len(Startzeit)-1])
+'\n Mean Value: %4.2f' %numpy.array(dosisausbeute).mean()
+r'$\pm$ %4.2f' %numpy.array(dosisausbeute).std()+r'$\mu$Gy/mAs'
+r' (Nominal: '+str(soll)+r'$\mu$Gy/mAs)'
+r' (Median: %4.2f $\mu$Gy/mAs)' %numpy.median(dosisausbeute)
, horizontalalignment='center', verticalalignment='center')
fig.subplots_adjust(left=None, bottom=None, right=0.8, top=None, wspace=None, hspace=0.5)
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(namef2[:-3]+'png')
#ramPlot = cStringIO.StringIO()
#fig.savefig(ramPlot)
#ramPlot.read()
#ramPlot.seek( 0 )
#img=Image.open( ramPlot )
#img.load()
#r, g, b, a = img.split()
#img = Image.merge("RGB", (r, g, b))
#img.save(namef2, "PDF", resolution=300.0)
del fig
############################################################################
#Verlauf Dosisausbeute FG, 125kV, 100 cm Abstand - Todo Dosisabfall ab 2000 BE?
fig = plt.figure(figsize=(14,10))
ax = fig.add_subplot(111)
datestrings = TIME
dosisausbeute = []
dosisausbeute_date=[]
tempy=[]
mean_dose=[]
std_dose=[]
mean_dose_date=[]
first_event=True
indx=numpy.nonzero(self.myXEvent.frequency[0:self.events]==0.01)
relevant_data=numpy.delete(self.myXEvent.dose_per_mAs[0:self.events],indx[0]) #remove Single Acq
relevant_data[np.isnan(relevant_data)]=0
tot_mean=relevant_data.mean()
tot_median=numpy.median(relevant_data)
tot_std=relevant_data.mean()
for i in range(len(SID)):
if self.myXEvent.focus[i] == ord('M'):
if self.myXEvent.scenelength[i] > 1000. and self.myXEvent._3Dmode[i]=='no3d':
if self.myXEvent.frequency[i] != 0.01 and self.myXEvent.skindoserate[i]>0 and abs(1.-self.myXEvent.current[i]/self.myXEvent.soll_mA[i])<0.1 and self.myXEvent.current[i]>20.:
if self.myXEvent.time[i] > 3:
dosisausbeute.append(self.myXEvent.dose_per_mAs[i])
dosisausbeute_date.append(TIME[i])
if first_event:
old_date=TIME[i]
first_event=False
if (TIME[i])[8:10]==old_date[8:10]: #same day
if math.fabs(self.myXEvent.dose_per_mAs[i]-tot_mean)<=2*tot_std: #nur Daten verwenden, die keine Ausreisser sind
tempy.append(self.myXEvent.dose_per_mAs[i])
else:
if len(tempy)>0:
mean_dose.append(numpy.array(tempy).mean())
std_dose.append(numpy.array(tempy).std())
mean_dose_date.append(old_date)
tempy=[]
old_date=TIME[i]
if len(tempy)>0: #last day
mean_dose.append(numpy.array(tempy).mean())
std_dose.append(numpy.array(tempy).std())
mean_dose_date.append(old_date)
NN=len(dosisausbeute)
soll=self.get_dose_efficiency_nominal()
if len(dosisausbeute)>0:
r = pylab.date2num([dateutil.parser.parse(s) for s in dosisausbeute_date])
t = pylab.date2num([dateutil.parser.parse(s) for s in mean_dose_date])
tt= linspace(pylab.date2num(dateutil.parser.parse(TIME[0])),pylab.date2num(dateutil.parser.parse(TIME[-1])), 100)
sollwerte = [soll for i in tt]
ax.plot_date(r, dosisausbeute,linestyle='.', color='b', label='Xray Events')
ax.plot_date(tt, sollwerte, marker='', linestyle='solid', color='g', linewidth=2.0, label='Nominal value')
if len(mean_dose)>1:
pol = numpy.polyfit(t, mean_dose , 1)
mean_value_fit = numpy.polyval(pol, tt)
ax.plot_date(t, mean_dose , linestyle='.',markersize=10.0, color='r', label='Day mean')
ax.plot_date(tt, mean_value_fit, marker='' , linestyle='--', color='r', linewidth=2.0, label='RMS Fit')
ax.set_xlabel('Date', size='x-small')
fig.autofmt_xdate()
ax.set_ylabel(r'Dose efficiency /[$\mu$Gy/mAs]', size='x-small')
ax.grid(True)
ax.set_ylim(0,max(max(dosisausbeute),soll)*1.2)
legend(bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0.)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
#r = matplotlib.pyplot.scatter(pylab.date2num(dates), Dosisausbeute, colorbar_voltage)
plt.title('Time Trend Dose Efficiency FG, 125kV, 0.0mm Cu, 100 cm distance')
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
fig.text(0.85, 0.75,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.75-offset*0.02,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)
+' part8'
+' Radiation events on plane '
+str(self.plane)
+':'+' '+str(len(SID))
+' ('+str(len(total_events))
+' total)'+' Days: '+str(day_total)
+' Start: '+str(Startzeit[0])
+' End: '+str(Startzeit[len(Startzeit)-1])
+'\n Mean Value: %4.2f' %numpy.array(dosisausbeute).mean()
+r'$\pm$ %4.2f' %numpy.array(dosisausbeute).std()+r'$\mu$Gy/mAs'
+r' (Nominal: '+str(soll)+r'$\mu$Gy/mAs)'
+r' (Median: %4.2f $\mu$Gy/mAs)' %numpy.median(dosisausbeute)
, horizontalalignment='center', verticalalignment='center')
fig.subplots_adjust(left=None, bottom=None, right=0.8, top=None, wspace=None, hspace=0.5)
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(namef2[:-3]+'png')
del fig
if (self.cb_png.GetValue()==False):
pdf.close()
plt.close()
####################################################################
#part9
if self.cb9.GetValue() or self.cb0.GetValue():
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_results_9.pdf')
if (self.cb_png.GetValue()==False):
pdf = PdfPages(name)
fig = plt.figure(figsize=(14,10))
#Plot 27 des Matlab-Programms: Current-Offset im Zeitlichen Verlauf für verschiedene Foken
ax = fig.add_subplot(111)
offset_l = []
offset_s = []
offset_m = []
TIME_l = []
TIME_s = []
TIME_m = []
for i in range(len(SID)):
#if current[i] > 50:
if self.myXEvent.focus[i] == ord('S'):
offset_s.append(self.myXEvent.offset[i])
TIME_s.append(TIME[i])
if self.myXEvent.focus[i] == ord('L'):
offset_l.append(self.myXEvent.offset[i])
TIME_l.append(TIME[i])
if self.myXEvent.focus[i] == ord('M'):
offset_m.append(self.myXEvent.offset[i])
TIME_m.append(TIME[i])
dates_l = [dateutil.parser.parse(s) for s in TIME_l]
dates_s = [dateutil.parser.parse(s) for s in TIME_s]
dates_m = [dateutil.parser.parse(s) for s in TIME_m]
ax.plot_date(pylab.date2num(dates_l), offset_l, marker='.', linestyle='-', color='r')
#ax.plot_date(pylab.date2num(dates_l), offset_l, linestyle='.', color='r')
ax.plot_date(pylab.date2num(dates_s), offset_s, marker='.', linestyle='-', color='b')
#ax.plot_date(pylab.date2num(dates_s), offset_s, linestyle='.', color='b')
ax.plot_date(pylab.date2num(dates_m), offset_m, marker='.', linestyle='-', color='g')
#ax.plot_date(pylab.date2num(dates_m), offset_m, linestyle='.', color='g')
pylab.legend(('large', 'small', 'micro'))
ax.set_xlabel('Date', size='x-small')
ax.set_ylabel('Current Offset /[0.1mA]', size='x-small')
ax.grid(True)
fig.autofmt_xdate()
plt.title('Dynamic current offset vs time')
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part9'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p1.png')
#------Page 2--------
#Time Development of static Params
fig = plt.figure(figsize=(14,10))
L_time = [dateutil.parser.parse(s) for s in Lernparameter_datum]
LL_time = pylab.date2num(L_time)
currL = []
currS = []
currM = []
#minLength=min(len(L1),len(L2),len(L3))
for i in range(len(L1)):
currL.append( (300*int(L1[i])+int(L2[i])+int(L3[i]))/10. )
currS.append( (300*int(S1[i])+int(S2[i])+int(S3[i]))/10. )
if self.myXEvent.numFoken==3:
currM.append( (300*int(M1[i])+int(M2[i])+int(M3[i]))/10. )
#multiplicative stativ part
ax = fig.add_subplot(211)
ax.plot_date(LL_time, L1, marker='.', linestyle='-', color='b')
ax.plot_date(LL_time, S1, marker='.', linestyle='-', color='g')
if self.myXEvent.numFoken==3:
ax.plot_date(LL_time, M1, marker='.', linestyle='-', color='r')
ax.set_ylabel('Multiplicative factor', size='x-small')
ax.set_xlabel('Date', size='x-small')
if self.myXEvent.numFoken==3:
pylab.legend(('L1', 'S1', 'M1'))
else:
pylab.legend(('L1', 'S1'))
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
plt.title('Time development of static multiplicative factors L1,S1,(M1)')
#static offset
ax = fig.add_subplot(212)
ax.plot_date(LL_time, L2, marker='.', linestyle='-', color='b')
ax.plot_date(LL_time, S2, marker='.', linestyle='-', color='g')
if self.myXEvent.numFoken==3:
ax.plot_date(LL_time, M2, marker='.', linestyle='-', color='r')
fig.autofmt_xdate()
if self.myXEvent.numFoken==3:
pylab.legend(('L2', 'S2', 'M2'))
else:
pylab.legend(('L2', 'S2'))
plt.title('Time development of static offsets L2,S2,(M2)')
ax.set_ylabel('Static offset', size='x-small')
ax.set_xlabel('Date', size='x-small')
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part9'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
pdf.close()
else:
plt.savefig(name[:-3]+'_p2.png')
del fig
plt.close()
##################################################################################################
if self.cb10.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,10))
#Part8 des Matlab-Programms; Plotte fuer jede Zoom-Stude Watervalue gegen Voltage (nur für events mit: Acquisition, SID in [100,110], Cu = 0)
ax = fig.add_subplot(111)
voltage_a_0 = []
voltage_a_1 = []
voltage_a_2 = []
voltage_a_3 = []
voltage_a_4 = []
voltage_a_5 = []
water_a_0 = []
water_a_1 = []
water_a_2 = []
water_a_3 = []
water_a_4 = []
water_a_5 = []
for i in range(len(SID)):
if self.myXEvent.mode[i] == ord('A'):
if self.myXEvent.SID[i] <=110:
if self.myXEvent.SID[i] >=100:
if self.myXEvent.filt[i] == 0:
if self.myXEvent.zoom[i] == 0:
voltage_a_0.append(self.myXEvent.voltage[i])
water_a_0.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 1:
voltage_a_1.append(self.myXEvent.voltage[i])
water_a_1.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 2:
voltage_a_2.append(self.myXEvent.voltage[i])
water_a_2.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 3:
voltage_a_3.append(self.myXEvent.voltage[i])
water_a_3.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 4:
voltage_a_4.append(self.myXEvent.voltage[i])
water_a_4.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 5:
voltage_a_5.append(self.myXEvent.voltage[i])
water_a_5.append(self.myXEvent.was[i])
ax.plot(water_a_0, voltage_a_0, marker='.', linestyle='.', color='r')
ax.plot(water_a_1, voltage_a_1, marker='.', linestyle='.', color='g')
ax.plot(water_a_2, voltage_a_2, marker='.', linestyle='.', color='b')
ax.plot(water_a_3, voltage_a_3, marker='.', linestyle='.', color='k')
ax.plot(water_a_4, voltage_a_4, marker='.', linestyle='.', color='m')
ax.plot(water_a_5, voltage_a_5, marker='.', linestyle='.', color='y')
ax.set_xlabel('Watervalue /[mm]', size='x-small')
ax.set_ylabel('Voltage /[kV]', size='x-small')
ax.grid(True)
ax.set_xlim(100, 500)
ax.set_ylim(50,130)
pylab.legend(('Zoom=0', 'Zoom=1', 'Zoom=2', 'Zoom=3', 'Zoom=4', 'Zoom=5'))
plt.title('Watervalue -Voltage (Acquisition, 100<=SID<=110, Cu = 0)')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part10'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_10.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
##################################################################################################
#part11
if self.cb11.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,10))
#Part8 des Matlab-Programms; Plotte fuer jede Zoom-Stude Watervalue gegen Voltage (nur für events mit: Fluoro, SID in [100,110])
ax = fig.add_subplot(111)
voltage_fl_0 = []
voltage_fl_1 = []
voltage_fl_2 = []
voltage_fl_3 = []
voltage_fl_4 = []
voltage_fl_5 = []
water_fl_0 = []
water_fl_1 = []
water_fl_2 = []
water_fl_3 = []
water_fl_4 = []
water_fl_5 = []
for i in range(len(SID)):
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.SID[i] <=110:
if self.myXEvent.SID[i] >=100:
if self.myXEvent.zoom[i] == 0:
voltage_fl_0.append(self.myXEvent.voltage[i])
water_fl_0.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 1:
voltage_fl_1.append(self.myXEvent.voltage[i])
water_fl_1.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 2:
voltage_fl_2.append(self.myXEvent.voltage[i])
water_fl_2.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 3:
voltage_fl_3.append(self.myXEvent.voltage[i])
water_fl_3.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 4:
voltage_fl_4.append(self.myXEvent.voltage[i])
water_fl_4.append(self.myXEvent.was[i])
elif self.myXEvent.zoom[i] == 5:
voltage_fl_5.append(self.myXEvent.voltage[i])
water_fl_5.append(self.myXEvent.was[i])
ax.plot(water_fl_0, voltage_fl_0, marker='.', linestyle='.', color='r')
ax.plot(water_fl_1, voltage_fl_1, marker='.', linestyle='.', color='g')
ax.plot(water_fl_2, voltage_fl_2, marker='.', linestyle='.', color='b')
ax.plot(water_fl_3, voltage_fl_3, marker='.', linestyle='.', color='k')
ax.plot(water_fl_4, voltage_fl_4, marker='.', linestyle='.', color='m')
ax.plot(water_fl_5, voltage_fl_5, marker='.', linestyle='.', color='y')
ax.set_xlabel('Watervalue /[mm]', size='x-small')
ax.set_ylabel('Voltage /[kV]', size='x-small')
ax.grid(True)
ax.set_xlim(100, 500)
ax.set_ylim(50,130)
pylab.legend(('Zoom=0', 'Zoom=1', 'Zoom=2', 'Zoom=3', 'Zoom=4', 'Zoom=5'))
plt.title('Watervalue -Voltage (Fluoro, 100<=SID<=110, all Cu)')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part11'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_11.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
####################################################################################################
#part12
if self.cb12.GetValue() or self.cb0.GetValue():
#Part10 im Matlab-script
fig = plt.figure(figsize=(14, 19))
time_L = []
water_L = []
voltage_L = []
voltage_L_interpolation = []
water_L_interpolation = [] #dient nur als Hilfe zur Interpolation
time_L_interpolation = []
for i in range(len(SID)+1):
if self.myXEvent.focus[i] == ord('L'):
time_L.append(TIME[i-1])
water_L.append(self.myXEvent.was[i])
water_L_interpolation.append(self.myXEvent.was[i])
time_L_interpolation.append(TIME[i-1]) #hier wird der i-1.te Index verwendet, da bei TIME im gegensatz zu den "self.my..."-arrays die "Kopfzeile" fehlt
voltage_L.append(self.myXEvent.voltage[i])
voltage_L_interpolation.append(self.myXEvent.voltage[i])
if len(time_L)>0:
time_L.append(TIME[len(TIME)-1])
time_L.append(TIME[0])
water_L.append(-1) #es werden Werte hinzugefügt, die nicht im zu plottenden Bereich liegen; dient nur dazu, dass die Zeitachse mit Anfang und Ende der Messung übereinstimmt
water_L.append(-1)
voltage_L.append(-1)
voltage_L.append(-1)
if len(water_L_interpolation) == 1: #ein einzelner Punkt legt keine Gerade fest- man braucht mindestens derer zwei
for i in range(1, len(SID)+1): #wir brauchen also einen zweiten Punkt, der denselben Wert annimmt.
if self.myXEvent.was[i] != water_L_interpolation[0]: #diese Abfrage dient nur dazu, nicht den selben Punkt, den wir schon haben, zu erwischen
water_L_interpolation.append(water_L_interpolation[0])
time_L_interpolation.append(TIME[i-1])
voltage_L_interpolation.append(voltage_L_interpolation[0])
break
Time_L = [dateutil.parser.parse(s) for s in time_L]
Time_L_interpolation = [dateutil.parser.parse(s) for s in time_L_interpolation]
xxtime = [dateutil.parser.parse(s) for s in TIME]
s = pylab.date2num(xxtime)
t = pylab.date2num(Time_L_interpolation)
tt = linspace(min(s), max(s), 100)
pol_ww = numpy.polyfit(t, water_L_interpolation , 1)
pol_voltage = numpy.polyfit(t, voltage_L_interpolation,1)
WERTE_ww = numpy.polyval(pol_ww, tt)
WERTE_voltage = numpy.polyval(pol_voltage, tt)
ax = fig.add_subplot(4,1,1)
ax.plot(Time_L, water_L, marker='.', linestyle='.', color='r')
ax.plot(tt, WERTE_ww, marker='_', linestyle='-', color='b')
ax.set_ylim(0,600)
ax.set_ylabel('Watervalue /[mm]', size='x-small')
water_L.remove(-1)
water_L.remove(-1)
plt.title("Time series of watervalues for large focus, [mean(WW), delta(WW)]={0}".format([round(numpy.mean(water_L)),round(pol_ww[0]*(t[len(t)-1]-t[0]))]))
fig.autofmt_xdate()
ax = fig.add_subplot(4,1,2)
ax.plot(Time_L, voltage_L, marker='.', linestyle='.', color='r')
ax.plot(tt, WERTE_voltage, marker='_', linestyle='-', color='b')
ax.set_ylim(40,130)
ax.set_ylabel('Voltage /[kV]', size='x-small')
voltage_L.remove(-1)
voltage_L.remove(-1)
plt.title("Time series of voltage for large focus, [mean(kV), delta(kV)]={0}".format([round(numpy.mean(voltage_L)),round(pol_voltage[0]*(t[len(t)-1]-t[0]))]))
fig.autofmt_xdate()
time_S = []
water_S = []
voltage_S = []
voltage_S_interpolation = []
water_S_interpolation = [] #dient nur als Hilfe zur Interpolation
time_S_interpolation = []
for i in range(len(SID)+1):
if self.myXEvent.focus[i] == ord('S'):
time_S.append(TIME[i-1])
water_S.append(self.myXEvent.was[i])
water_S_interpolation.append(self.myXEvent.was[i])
time_S_interpolation.append(TIME[i-1])
voltage_S.append(self.myXEvent.voltage[i])
voltage_S_interpolation.append(self.myXEvent.voltage[i])
if len(time_S)>0:
time_S.append(TIME[len(TIME)-1])
time_S.append(TIME[0])
water_S.append(-1) #es werden Werte hinzugefügt, die nicht im zu plottenden Bereich liegen; dient nur dazu, dass die Zeitachse mit Anfang und Ende der Messung übereinstimmt
water_S.append(-1)
voltage_S.append(-1)
voltage_S.append(-1)
if len(water_S_interpolation) == 1: #ein einzelner Punkt legt keine Gerade fest- man braucht mindestens derer zwei
for i in range(1, len(SID)+1): #wir brauchen also einen zweiten Punkt, der denselben Wert annimmt.
if self.myXEvent.was[i] != water_S_interpolation[0]: #diese Abfrage dient nur dazu, nicht den selben Punkt, den wir schon haben, zu erwischen
water_S_interpolation.append(water_S_interpolation[0])
time_S_interpolation.append(TIME[i-1])
voltage_S_interpolation.append(voltage_S_interpolation[0])
break
Time_S = [dateutil.parser.parse(s) for s in time_S]
Time_S_interpolation = [dateutil.parser.parse(s) for s in time_S_interpolation]
xxtime = [dateutil.parser.parse(s) for s in TIME]
s = pylab.date2num(xxtime)
t = pylab.date2num(Time_S_interpolation)
tt = linspace(min(s), max(s), 100)
pol_ww = numpy.polyfit(t, water_S_interpolation , 1)
pol_voltage = numpy.polyfit(t, voltage_S_interpolation,1)
WERTE_ww = numpy.polyval(pol_ww, tt)
WERTE_voltage = numpy.polyval(pol_voltage, tt)
ax = fig.add_subplot(4,1,3)
ax.plot(Time_S, water_S, marker='.', linestyle='.', color='r')
ax.plot(tt, WERTE_ww, marker='_', linestyle='-', color='b')
ax.set_ylim(0,600)
ax.set_ylabel('Watervalue /[mm]', size='x-small')
water_S.remove(-1)
water_S.remove(-1)
plt.title("Time series of watervalues for small focus, [mean(WW), delta(WW)]={0}".format([round(numpy.mean(water_S)),round(pol_ww[0]*(t[len(t)-1]-t[0]))]))
fig.autofmt_xdate()
ax = fig.add_subplot(4,1,4)
ax.plot(Time_S, voltage_S, marker='.', linestyle='.', color='r')
ax.plot(tt, WERTE_voltage, marker='_', linestyle='-', color='b')
ax.set_ylim(40,130)
ax.set_ylabel('Voltage /[kV]', size='x-small')
voltage_S.remove(-1)
voltage_S.remove(-1)
plt.title("Time series of voltage for small focus, [mean(kV), delta(kV)]={0}".format([round(numpy.mean(voltage_S)),round(pol_voltage[0]*(t[len(t)-1]-t[0]))]))
fig.autofmt_xdate()
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part12'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_12.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#######################################################################################################################
#part13 - FG Analysis
if self.cb13.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,20))
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_results_13_FG_Analysis.pdf')
if (self.cb_png.GetValue()==False):
pdf = PdfPages(name)
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)
plt.rc("axes", titlesize=12)
#----1-----
# FG current vs volatage for F and A
ax = plt.subplot2grid((6, 2), (0, 0), rowspan=2)
idx_A=((self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))==True)
idx_F=((self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))==True)
Spannung_A_M=self.myXEvent.voltage[idx_A]
Spannung_F_M=self.myXEvent.voltage[idx_F]
Current_A_M=self.myXEvent.current[idx_A]
Current_F_M=self.myXEvent.current[idx_F]
##prom data
if (self.myXEvent.tubetype==2 and self.myXEvent.numFoken==3): #3F Gigalix
promdata=parseXMLTubeProm(3,"g253685.xml")
elif (self.myXEvent.tubetype==1 and self.myXEvent.numFoken==3): #3F Megalix Cat+
promdata=parseXMLTubeProm(3,"m204080_Draft_Olli.xml")
xrayVoltage=promdata[6]
maxCurrAcq=promdata[7]
maxCurrFluoro=promdata[8]
ax.plot(Spannung_A_M, Current_A_M, marker='.', linestyle='.', color='r', markeredgecolor='r', label='Acquisition')
ax.plot(Spannung_F_M, Current_F_M, marker='.', linestyle='.', color='b', markeredgecolor='b', label='Fluoro')
ax.plot(np.array(xrayVoltage['micro'])/1000.,np.array(maxCurrAcq['micro'])/1000.,marker='o',linestyle='-', color='black', label='punch-through')
ax.set_ylabel('Current /[mA]', size='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
plt.title('Voltage vs Current - Micro Focus', size='small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlim([40,130])
ax.grid(True)
#-----2-----
#Histogramm over tube currents (Fluoro)
ax = plt.subplot2grid((6, 2), (0, 1))
if len(Current_F_M)>0:
ax.hist(np.array(Current_F_M), color='b', edgecolor='b', bins=200,label='Fluoro')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlabel('Current /[mA]', size='x-small')
ax.set_ylabel('# Occurance', size='x-small')
ax.set_xlim([0,200])
ax.grid(True)
plt.title('Histogram Currents - Micro Focus', size='small')
#Histogramm over tube currents
ax = plt.subplot2grid((6, 2), (1, 1))
if len(Current_A_M)>0:
ax.hist(np.array(Current_A_M), color='r', edgecolor='r', bins=200,label='Acquisition')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlabel('Current /[mA]', size='x-small')
ax.set_ylabel('# Occurance', size='x-small')
ax.set_xlim([0,200])
ax.grid(True)
#plt.title('Histogram Currents Acq.- Micro Focus', size='small')
#-----3-----
#Histogramm over kVs
ax = plt.subplot2grid((6, 2), (2, 0))
if len(Spannung_F_M)>0:
ax.hist(Spannung_F_M, color='b', edgecolor='b', bins=86, label='Fluoro')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('# Occurance', size='x-small')
ax.set_xlim([40,130])
ax.grid(True)
plt.title('Histogram Voltages - Micro Focus', size='small')
ax = plt.subplot2grid((6, 2), (3, 0))
if len(Spannung_A_M)>0:
ax.hist(Spannung_A_M, color='r', edgecolor='r', bins=86, label='Acquisition')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('# Occurance', size='x-small')
ax.set_xlim([40,130])
ax.grid(True)
#plt.title('Histogram Voltages - Micro Focus', size='small')
#-----6-----
#BE time development of all foci
ax = plt.subplot2grid((6, 2), (4, 1), rowspan=2)
datesX = [dateutil.parser.parse(s) for s in TIME]
ATx = pylab.date2num(datesX)
onlyF1 =numpy.zeros(self.events)
onlyF2 =numpy.zeros(self.events)
onlyFG =numpy.zeros(self.events)
scan_F1=numpy.zeros(self.events)
scan_F2=numpy.zeros(self.events)
scan_FG=numpy.zeros(self.events)
Xevnt_F1=numpy.zeros(self.events)
Xevnt_F2=numpy.zeros(self.events)
Xevnt_FG=numpy.zeros(self.events)
scentime_F1=numpy.zeros(self.events)
scentime_F2=numpy.zeros(self.events)
scentime_FG=numpy.zeros(self.events)
for i in range(self.events):
if self.myXEvent.focus[i]==ord('S'):
onlyF1[i] +=onlyF1[i-1]+self.myXEvent.BE_F1[i]
scan_F1[i]+=scan_F1[i-1]+self.myXEvent.frames[i]*self.myXEvent.time[i]
Xevnt_F1[i]+=Xevnt_F1[i-1]+1
scentime_F1[i]=scentime_F1[i-1]+self.myXEvent.scenelength[i]/1000.
else:
onlyF1[i]+=onlyF1[i-1]
scan_F1[i]+=scan_F1[i-1]
Xevnt_F1[i]+=Xevnt_F1[i-1]
scentime_F1[i]+=scentime_F1[i-1]
if self.myXEvent.focus[i]==ord('L'):
onlyF2[i]+=onlyF2[i-1]+self.myXEvent.BE_F2[i]
scan_F2[i]+=scan_F2[i-1]+self.myXEvent.frames[i]*self.myXEvent.time[i]
Xevnt_F2[i]+=Xevnt_F2[i-1]+1
scentime_F2[i]=scentime_F2[i-1]+self.myXEvent.scenelength[i]/1000.
else:
onlyF2[i]+=onlyF2[i-1]
scan_F2[i]+=scan_F2[i-1]
Xevnt_F2[i]+=Xevnt_F2[i-1]
scentime_F2[i]+=scentime_F2[i-1]
if self.myXEvent.focus[i]==ord('M'):
onlyFG[i]+=onlyFG[i-1]+self.myXEvent.BE_FG[i]
scan_FG[i]+=scan_FG[i-1]+self.myXEvent.frames[i]*self.myXEvent.time[i]
Xevnt_FG[i]+=Xevnt_FG[i-1]+1
scentime_FG[i]=scentime_FG[i-1]+self.myXEvent.scenelength[i]/1000.
else:
onlyFG[i]+=onlyFG[i-1]
scan_FG[i]+=scan_FG[i-1]
Xevnt_FG[i]+=Xevnt_FG[i-1]
scentime_FG[i]+=scentime_FG[i-1]
BE_total=onlyF1+onlyF2+onlyFG
scan_tot=scan_F1+scan_F2+scan_FG
Xevnt_tot=Xevnt_F1+Xevnt_F2+Xevnt_FG
ax.plot_date(ATx, BE_total, marker='', linestyle='-',color='black', label='all (%d)'%BE_total[-1])
ax.plot_date(ATx, onlyF1, marker='', linestyle='-',color='blue', label="F1 (%d)"%onlyF1[-1])
ax.plot_date(ATx, onlyF2, marker='', linestyle='-',color='red', label="F2 (%d)"%onlyF2[-1])
ax.plot_date(ATx, onlyFG, marker='', linestyle='-',color='green', label="FG (%d)"%onlyFG[-1])
ax.set_ylabel('BE', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
rel_part_BE_FG=((self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))*self.myXEvent.BE_total).sum()*100./((self.myXEvent.focus==ord('M'))*self.myXEvent.BE_total).sum()
if np.isnan(rel_part_BE_FG):
rel_part_BE_FG=-1
plt.title('BE per focus, FG: Fluoro %2.1f%% Acq. %2.1f%% '%(rel_part_BE_FG,100.-rel_part_BE_FG),fontsize='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y\n %H:%M'))
#fig.autofmt_xdate()
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#---------Xevents--------------
ax = plt.subplot2grid((6, 2), (2, 1), rowspan=2)
ax.plot_date(ATx, Xevnt_tot, marker='', linestyle='-',color='black', label='all (%d)'%Xevnt_tot[-1])
ax.plot_date(ATx, Xevnt_F1, marker='', linestyle='-',color='blue', label="F1 (%d)"%Xevnt_F1[-1])
ax.plot_date(ATx, Xevnt_F2, marker='', linestyle='-',color='red', label="F2 (%d)"%Xevnt_F2[-1])
ax.plot_date(ATx, Xevnt_FG, marker='', linestyle='-',color='green', label="FG (%d)"%Xevnt_FG[-1])
ax.set_ylabel('X-ray events', size='x-small')
#ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
rel_part_FL_events_FG=((self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))).sum()*100./(self.myXEvent.focus==ord('M')).sum()
if np.isnan(rel_part_FL_events_FG):
rel_part_FL_events_FG=-1
plt.title('X-ray events per focus, FG: Fluoro %2.1f%% Acq. %2.1f%% '%(rel_part_FL_events_FG,100.-rel_part_FL_events_FG),fontsize='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y\n %H:%M'))
#fig.autofmt_xdate()
#labels = ax.get_xticklabels()
#setp(labels, rotation=90, fontsize=8)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
ax.set_xticklabels([])
#---------ScanSec--------------
ax = plt.subplot2grid((6, 2), (4, 0), rowspan=2)
ax.plot_date(ATx, scan_tot/1000., marker='', linestyle='-',color='black', label='all (%d)s'%(scan_tot[-1]/1000.))
ax.plot_date(ATx, scan_F1/1000., marker='', linestyle='-',color='blue', label="F1 (%d)s"%(scan_F1[-1]/1000.))
ax.plot_date(ATx, scan_F2/1000., marker='', linestyle='-',color='red', label="F2 (%d)s"%(scan_F2[-1]/1000.))
ax.plot_date(ATx, scan_FG/1000., marker='', linestyle='-',color='green', label="FG (%d)s"%(scan_FG[-1]/1000.))
ax.set_ylabel('Scan Sec [s]', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
rel_part_ss_FG=((self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))*self.myXEvent.time*self.myXEvent.frames).sum()*100./((self.myXEvent.focus==ord('M'))*self.myXEvent.time*self.myXEvent.frames).sum()
if np.isnan(rel_part_ss_FG):
rel_part_ss_FG=-1
plt.title('Scan sec per focus, FG: Fluoro %2.1f%% Acq. %2.1f%% '%(rel_part_ss_FG,100.-rel_part_ss_FG),fontsize='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y\n %H:%M'))
#fig.autofmt_xdate()
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
##Tube SNs
fig.text(0.85, 0.95,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.95-offset*0.01,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
#-----------page top and end-------------------
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part13 (FG Analysis)'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr), horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
plt.subplots_adjust(hspace=0.3)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p1.png')
#------------page 2--------------------
fig = plt.figure(figsize=(14,20))
ax = fig.add_subplot(3,1,1)
offset_l = []
offset_s = []
offset_m = []
TIME_l = []
TIME_s = []
TIME_m = []
for i in range(len(SID)):
#if current[i] > 50:
if self.myXEvent.focus[i] == ord('S'):
offset_s.append(self.myXEvent.offset[i])
TIME_s.append(TIME[i])
if self.myXEvent.focus[i] == ord('L'):
offset_l.append(self.myXEvent.offset[i])
TIME_l.append(TIME[i])
if self.myXEvent.focus[i] == ord('M'):
offset_m.append(self.myXEvent.offset[i])
TIME_m.append(TIME[i])
dates_l = [dateutil.parser.parse(s) for s in TIME_l]
dates_s = [dateutil.parser.parse(s) for s in TIME_s]
dates_m = [dateutil.parser.parse(s) for s in TIME_m]
ax.plot_date(pylab.date2num(dates_l), offset_l, marker='.', linestyle='-', color='r')
ax.plot_date(pylab.date2num(dates_s), offset_s, marker='.', linestyle='-', color='b')
ax.plot_date(pylab.date2num(dates_m), offset_m, marker='.', linestyle='-', color='g')
pylab.legend(('large', 'small', 'micro'))
ax.set_xlabel('Date', size='x-small')
ax.set_ylabel('Current Offset /[0.1mA]', size='x-small')
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
fig.autofmt_xdate()
plt.title('Dynamic current offset vs time', size='small')
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
# development of static params
ax = fig.add_subplot(3,1,2)
L_time = [dateutil.parser.parse(s) for s in Lernparameter_datum]
LL_time = pylab.date2num(L_time)
currL = []
currS = []
currM = []
for i in range(len(L1)):
currL.append( (300*int(L1[i])+int(L2[i])+int(L3[i]))/10. )
currS.append( (300*int(S1[i])+int(S2[i])+int(S3[i]))/10. )
if self.myXEvent.numFoken==3:
currM.append( (300*int(M1[i])+int(M2[i])+int(M3[i]))/10. )
#multiplicative static part
ax.plot_date(LL_time, L1, marker='.', linestyle='-', color='b')
ax.plot_date(LL_time, S1, marker='.', linestyle='-', color='g')
if self.myXEvent.numFoken==3:
ax.plot_date(LL_time, M1, marker='.', linestyle='-', color='r')
ax.set_ylabel('Multiplicative factor', size='x-small')
ax.set_xlabel('Date', size='x-small')
if self.myXEvent.numFoken==3:
pylab.legend(('L1', 'S1', 'M1'))
else:
pylab.legend(('L1', 'S1'))
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
fig.autofmt_xdate()
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
plt.title('Time development of static multiplicative factors', size='small')
#static offset
ax = fig.add_subplot(3,1,3)
ax.plot_date(LL_time, L2, marker='.', linestyle='-', color='b')
ax.plot_date(LL_time, S2, marker='.', linestyle='-', color='g')
if self.myXEvent.numFoken==3:
ax.plot_date(LL_time, M2, marker='.', linestyle='-', color='r')
fig.autofmt_xdate()
if self.myXEvent.numFoken==3:
pylab.legend(('L2', 'S2', 'M2'))
else:
pylab.legend(('L2', 'S2'))
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('Time development of static offsets', size='small')
ax.set_ylabel('Static offset', size='x-small')
ax.set_xlabel('Date', size='x-small')
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
labels = ax.get_yticklabels()
setp(labels, fontsize=8)
##Tube SNs
fig.text(0.85, 0.95,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.95-offset*0.01,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
fig.text(0.05, 0.95, u"ERR5115_TUBE_READJUST (A100) FG specific: {0}".format(ERR5115_TUBE_READJUST.count(2)),fontsize=8) #only FG events
#-----------page top and end-------------------
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part13 (FG Analysis)'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr), horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p2.png')
#------------page 3--------------------
fig = plt.figure(figsize=(14,20))
# used heat current vs tube current for different kV (from prom)
ax = fig.add_subplot(3,2,1)
##prom data
if (self.myXEvent.tubetype==2 and self.myXEvent.numFoken==3): #3F Gigalix
specpromdata=parseXMLTubeProm_special(3,"g253685_specific.xml")
elif (self.myXEvent.tubetype==1 and self.myXEvent.numFoken==3): #3F Megalix Cat+
specpromdata=parseXMLTubeProm_special(3,"m204080_specific_Draft_Olli.xml")
kVs =specpromdata[0]
tube_currents =specpromdata[1]
heating_currents =specpromdata[2]
kVs_FG=np.array(kVs['micro'])
tube_currents_FG=np.array(tube_currents['micro'])
heating_currents_FG_matrix=np.array(heating_currents['micro'])
heating_currents_FG=heating_currents_FG_matrix.reshape([1,-1])[0]
ax.set_color_cycle(['red', 'green', 'yellow', 'black', 'blue', 'grey'])
tube_current_temp=np.logspace(log2(0.5),log2(200.),num=100, base=2)
heat_current_temp=np.zeros(tube_current_temp.shape)
for kV in kVs_FG:
for i in range (len(tube_current_temp)):
heat_current_temp[i]=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,kV,tube_current_temp[i]*10.)/10.
#print i, kV, tube_current_temp[i]
ax.plot(heat_current_temp, tube_current_temp, marker='', linestyle='-', label=str(kV/1000.)+'kV')
for j in range(len(kVs_FG)):
ax.plot(heating_currents_FG_matrix[:,j]/10.,tube_currents_FG/10.,marker='.', linestyle='',color='black')
ax.set_ylabel('Tube Current /[mA]', size='x-small')
ax.set_xlabel('Heating Current /[mA]', size='x-small')
plt.title('Tube current vs heating current - FG (from spec. tube prom)',fontsize='small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlim([3000,5500])
ax.set_yscale('log')
ax.grid(True)
# Tube current vs emitter temp (real data)
ax = fig.add_subplot(3,2,2)
idx_fg=((self.myXEvent.focus==ord('M'))==True)
Current_M =self.myXEvent.current[idx_fg]
Emitter_temp_M =self.myXEvent.emitter_temp[idx_fg]
Tungst_eva =self.myXEvent.tungst_evaporation_rate[idx_fg]
Tungst_thick =self.myXEvent.tungst_thickness[idx_fg]
Voltage_M =self.myXEvent.voltage[idx_fg]
Tungst_thick_A =self.myXEvent.tungst_thickness[idx_A]
Tungst_thick_F =self.myXEvent.tungst_thickness[idx_F]
HeatCurr_M =self.myXEvent.heating_current[idx_fg]
maxCurrent_M =self.myXEvent.maxCurrentRev_punchthrough[idx_fg]
Scenetime_M =self.myXEvent.scenelength[idx_fg]
ax.plot(Current_M,Emitter_temp_M, marker='.', linestyle='')
ax.set_ylabel('Emitter temp /[Grad C]', size='x-small')
ax.set_xlabel('Tube current /[mA]', size='x-small')
plt.title('Tube current vs emitter temperature', size='small')
ax.grid(True)
#Emitter temp vs kV
ax = fig.add_subplot(3,2,3)
ax.plot(Voltage_M,Emitter_temp_M, marker='.', linestyle='')
ax.set_ylabel(u'Emitter temp /[°C]', size='x-small')
ax.set_xlabel('Tube voltage /[kV]', size='x-small')
plt.title('Tube voltage vs emitter temperature', size='small')
ax.grid(True)
#Emitter temp vs kV
ax = fig.add_subplot(3,2,4)
ax.plot(Emitter_temp_M,Tungst_eva, marker='.', linestyle='')
ax.set_ylabel(u'Tungsten evap. rate /[µm/h]', size='x-small')
ax.set_xlabel(u'Emitter temp /[°C]', size='x-small')
plt.title('Tungsten evap. rate vs tube current', size='small')
ax.set_yscale('log')
ax.grid(True)
#Emitter temp vs kV
ax = fig.add_subplot(3,2,5)
hist, bin_edges = np.histogram(Tungst_eva, bins=50, density=False)
bin_edges_mid=bin_edges+bin_edges[1]-bin_edges[0]
bin_edges_mid=bin_edges_mid[:-1]
idx_hist=(hist!=0)
hist=hist[idx_hist]
bin_edges_mid=bin_edges_mid[idx_hist]
ax.plot(bin_edges_mid, hist, marker='.', linestyle='')
ax.set_xlabel(u'Tungsten evap. rate /[µm/h]', size='x-small')
ax.set_ylabel('# Occurance', size='x-small')
plt.title('Histogram Tungsten evaporation rate', size='small')
ax.set_ylim([0.1,len(Tungst_eva)])
ax.set_yscale('log')
ax.grid(True)
#Evaporated Tungsten Thickness vs kV slot (Fluoro and Acquisition)
ax = fig.add_subplot(3,2,6)
sort_indices_kv = numpy.argsort(Voltage_M)
Voltage_M_sorted=Voltage_M[sort_indices_kv]
Tungst_thick_sorted=Tungst_thick[sort_indices_kv]
sort_indices_kv_A = numpy.argsort(Spannung_A_M)
Voltage_M_A_sorted=Spannung_A_M[sort_indices_kv_A]
Tungst_thick_A_sorted=Tungst_thick_A[sort_indices_kv_A]
sort_indices_kv_F = numpy.argsort(Spannung_F_M)
Voltage_M_F_sorted=Spannung_F_M[sort_indices_kv_F]
Tungst_thick_F_sorted=Tungst_thick_F[sort_indices_kv_F]
ax.plot(Voltage_M_A_sorted,Tungst_thick_A_sorted.cumsum()/Tungst_thick_sorted.sum(),label='Acq', color='red')
ax.plot(Voltage_M_F_sorted,Tungst_thick_F_sorted.cumsum()/Tungst_thick_sorted.sum(),label='Fluoro',color='blue')
ax.plot(Voltage_M_sorted,Tungst_thick_sorted.cumsum()/Tungst_thick_sorted.sum(),label='Total', color='black')
ax.plot(Voltage_M_sorted,Voltage_M_sorted.cumsum()/Voltage_M_sorted.sum(),label='norm. acc. kV', color='black', linestyle='dashed')
ax.set_xlabel('Tube Voltage /[kV] ', size='x-small')
ax.set_ylabel('rel. Tungsten thickness', size='x-small')
plt.title(u'Summed evaporated Tungsten thickness over voltage\nTungsten thickness: %2.1f µm'%Tungst_thick_sorted.sum(), size='small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
## Tube SNs
fig.text(0.85, 0.95,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.95-offset*0.01,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
#-----------page 3 top and end-------------------
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part13 (FG Analysis)'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr), horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p3.png')
#------------page 4--------------------
fig = plt.figure(figsize=(14,20))
# heating curve
ax = fig.add_subplot(3,2,1)
ax.plot(HeatCurr_M,Emitter_temp_M,marker='.', linestyle='')
ax.set_xlabel('heating current /[mA] ', size='x-small')
ax.set_ylabel(u'emitter temperature /[°C]', size='x-small')
plt.title(u'Heating Curve Megalix Cat+, FG (220µm thickness)', size='small')
ax.grid(True)
# Hist FG current/max current (from punch through)
ax = fig.add_subplot(3,2,2)
ax.hist(Current_M/maxCurrent_M,100)
ax.set_ylabel('# occurance', size='x-small')
ax.set_xlabel('current / max current power \n (based on punch-through tabe from default tube prom)', size='x-small')
plt.title('Histogram current/max_current for FG', size='small')
ax.set_xlim(0.0,1.0)
ax.grid(True)
# accumulated Tungsten thickness vs accumulated scenetime
ax = fig.add_subplot(3,2,3)
temp_array=numpy.array(self.myXEvent.maxPower_Istzeit)
ax.plot(Scenetime_M.cumsum()/1000./3600.,Tungst_thick.cumsum(),marker='.', linestyle='')
ax.set_ylabel(u'accum. Tungsten thickness /[µm]', size='x-small')
ax.set_xlabel('accum. scenetime /[h]', size='x-small')
plt.title(u'accumulated Tungsten thickness vs accumulated scenetime\n mean Tungsten evap. rate: %2.1f [µm/100h]'%(100.*Tungst_thick.sum()/(Scenetime_M.sum()/3600./1000.)), size='small')
ax.grid(True)
#---------Accum Scenetime--------------
ax = fig.add_subplot(3,2,4)
scentime_tot=scentime_F1+scentime_F2+scentime_FG
ax.plot_date(ATx, scentime_tot/3600., marker='', linestyle='-',color='black', label='all (%d h)'%(scentime_tot[-1]/3600.))
ax.plot_date(ATx, scentime_F1/3600., marker='', linestyle='-',color='blue', label="F1 (%d h)"%(scentime_F1[-1]/3600.))
ax.plot_date(ATx, scentime_F1/3600., marker='', linestyle='-',color='red', label="F2 (%d h)"%(scentime_F2[-1]/3600.))
ax.plot_date(ATx, scentime_FG/3600., marker='', linestyle='-',color='green', label="FG (%d h)"%(scentime_FG[-1]/3600.))
ax.set_ylabel('accu. scene time /[h]', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
rel_part_st_FG=((self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))*self.myXEvent.scenelength).sum()*100./((self.myXEvent.focus==ord('M'))*self.myXEvent.scenelength).sum()
plt.title('Accum. scenetime per focus, FG: Fluoro %2.1f%% Acq. %2.1f%% '%(rel_part_st_FG,100.-rel_part_st_FG),fontsize='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y\n %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#Histogramm Watervalue
ax = fig.add_subplot(3,2,5)
WV_FG=self.myXEvent.was[idx_fg]
ax.hist(WV_FG, 50, range =(1, 500))
ax.set_xlim(1, 500)
ax.set_xlabel('Watervalue /[mm]',size='x-small' )
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
plt.title("Watervalue FG; [mean, SD]={0}".format( [ round(numpy.mean(watervalue)), round(numpy.std(watervalue)) ]), size='small' )
# Hist FG heat current
ax = fig.add_subplot(3,2,6)
ax.hist(HeatCurr_M,100)
ax.set_ylabel('# occurance', size='x-small')
ax.set_xlabel('heating current /[mA]', size='x-small')
plt.title('Histogram heating current for FG', size='small')
ax.grid(True)
## Tube SNs
fig.text(0.85, 0.95,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.95-offset*0.01,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
#-----------page 4 top and end-------------------
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part13 (FG Analysis)'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr), horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p4.png')
#------------page 5--------------------
fig = plt.figure(figsize=(14,20))
# generate punch-throught table with const temp
Ts=[2300,2400,2450,2500,2550,2600,2650]
I_step=1
ax = fig.add_subplot(3,2,1)
for T0 in Ts:
maxCurrAcqT0=[]
heat_current=self.get_filament_heat_current(T0)
for kV in xrayVoltage['micro']:
mA_iter=tube_currents_FG[-1]
act_heat_curr=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,kV,mA_iter)/10.
while act_heat_curr>heat_current:
act_heat_curr=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,kV,mA_iter)/10.
mA_iter=mA_iter-I_step
maxCurrAcqT0.append(mA_iter/10.)
ax.plot(np.array(xrayVoltage['micro'])/1000.,np.array(maxCurrAcqT0),marker='o',linestyle='-')
if T0==Ts[-1]:
ax.text(77.,maxCurrAcqT0[-4],'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T0)), size='x-small')
else:
ax.text(100.,maxCurrAcqT0[-2],'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T0)), size='x-small')
ax.plot(Spannung_A_M, Current_A_M, marker='.', linestyle='.', color='r', markeredgecolor='r', label='Acquisition')
ax.plot(Spannung_F_M, Current_F_M, marker='.', linestyle='.', color='b', markeredgecolor='b', label='Fluoro')
ax.set_ylabel('Current /[mA]', size='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
plt.title('Voltage vs Current - Micro Focus', size='small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
leg.get_frame().set_alpha(0.5)
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlim([40,130])
ax.set_ylim([0,220])
ax.grid(True)
####test Langmuir-Schottky Raumladungsgesetz I~U^(3/2)
"""
ax = fig.add_subplot(3,2,2)
Ts=[2300,2400,2450,2500,2550,2600,2650]
I_step=1
for T in Ts:
maxCurrAcqT0=[]
heat_current=self.get_filament_heat_current(T)
for kV in xrayVoltage['micro']:
mA_iter=tube_currents_FG[-1]
act_heat_curr=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,kV,mA_iter)/10.
while act_heat_curr>heat_current:
act_heat_curr=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,kV,mA_iter)/10.
mA_iter=mA_iter-I_step
maxCurrAcqT0.append(mA_iter/10.)
ax.plot(np.log10(np.array(xrayVoltage['micro'])/1000.),np.log10(np.array(maxCurrAcqT0)),marker='o',linestyle='-')
#ax.text(np.log10(110.),np.log10(maxCurrAcqT0[-1]),'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T)), size='x-small')
ax.plot(np.log10(np.array(xrayVoltage['micro'])/1000.),2.5*np.log10(np.array(xrayVoltage['micro'])/1000.)-3., marker='',linestyle='dashed',label=r"$I \propto U^{3/2} $")
ax.set_ylabel('log 10 Current /[mA]', size='x-small')
ax.set_xlabel('log 10 Voltage /[kV]', size='x-small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
leg.get_frame().set_alpha(0.5)
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('Voltage vs Current (logarithmic) - Micro Focus', size='small')
#ax.set_xlim([40,130])
ax.grid(True)
"""
####test Richardson thermionic emission mit Schottky Potential (mirror charge and e-Field)
kB = 1.3806488e-23 # m2 kg s-2 K-1
d = 0.013 #m-distance anode/cathode
epsilon= 1.20173e+06 #A/m^2/K^2 Richardson Konstante
phi0=4.54 #eV ; Austrittsarbeit Elektronen aus Wolfram
emmit_surface=4.3e-6/3. #m^2 3.5
e_charge=1.6022e-19 #As
e_mass=9.1094e-31 #kg
epsilon0=8.8542e-12 #As/(Vm)
Ts=[2300,2400,2450,2500,2550,2600]
ax = fig.add_subplot(3,2,2)
for T0 in Ts:
TK=T0+273.15 #C->K - emitter Temp
Vs=np.array(xrayVoltage['micro']) # in Volt
Is=emmit_surface*epsilon*TK*TK*np.exp(-phi0*e_charge/kB/TK)*np.exp(e_charge/2/kB/TK*np.sqrt(e_charge*Vs/np.pi/epsilon0/d)) #in Ampere
ax.plot(Vs/1000.,Is*1000., marker='',linestyle='-')
if T0==Ts[-1]:
ax.text(50.,Is[-7]*1000.,'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T0)), size='x-small')
else:
ax.text(100.,Is[-2]*1000.,'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T0)), size='x-small')
plt.title('Theoretical emission curves\nRichardson\'s law of thermionic emission', size='small')
ax.set_xlim([40,130])
ax.set_ylim([0,220])
ax.grid(True)
###### with Schottky term for space charge shielding
ax = fig.add_subplot(3,2,3)
Vs=np.array([1000,2000,5000,10000,20000,25000,30000,35000,40000,45000,50000,60000,70000,80000,90000,100000,125000])
#Vs=np.array(xrayVoltage['micro']) # in Volt
I_sp=emmit_surface*epsilon0*np.sqrt(2*e_charge/e_mass)*4./9./d/d*np.power(Vs,1.5)
for T0 in Ts:
TK=T0+273.15 #C->K - emitter Temp
I_lim=emmit_surface*epsilon*TK*TK*np.exp(-phi0*e_charge/kB/TK)*np.exp(e_charge/2/kB/TK*np.sqrt(e_charge*Vs/np.pi/epsilon0/d)) #in Ampere
alpha=np.arctan(50.*(I_sp-I_lim))/(np.pi/2.)
I_res=(1.-alpha)*I_sp+alpha*I_lim
#ax.plot(Vs/1000.,I_lim*1000., marker='.',label=str(T0)+u'°C')
ax.plot(Vs/1000.,I_lim*1000., marker='',linestyle='-')
#ax.plot(Vs/1000.,alpha*100., marker='.',linestyle='-')
if T0==Ts[-1]:
ax.text(50.,I_lim[-7]*1000.,'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T0)), size='x-small')
else:
ax.text(100.,I_lim[-2]*1000.,'T='+str(T0)+u'°C (%2.1fmA)'%(self.get_filament_heat_current(T0)), size='x-small')
ax.plot(Vs/1000.,I_sp*1000., marker='.',linestyle='dashed',color='black')
ax.set_xlim([1,130])
ax.set_ylim([4,220])
ax.grid(True)
plt.title('Theoretical emission curves\nRichardson\'s law of thermionic emission with Schottky terms for space charge', size='small')
# different punch through tables
ax = fig.add_subplot(3,2,4)
ax.plot(Spannung_A_M, Current_A_M, marker='.', linestyle='.', color='r', markeredgecolor='r', label='Acquisition')
ax.plot(Spannung_F_M, Current_F_M, marker='.', linestyle='.', color='b', markeredgecolor='b', label='Fluoro')
# from 3F Megalix Cat Prom 154082.a Punch through:
# KV_MFTAB DW 400, 600, 770, 900, 1000, 1250
# MFMAX_FOCP DD 33000, 79000, 137000, 150000, 150000, 150000
# mA => 82.5 132 178 167 150 120
# from 3F Megalix Cat+ Prom 204080.a Punch through:
# KV_MFTAB DW 400, 600, 770, 900, 1000, 1250
# MFMAX_FOCP DD 52000, 108000, 146000, 170000, 170000, 170000
# => mA: 130 180 190 189 170 136
xrayVoltages=np.array([40.,60.,77.,90.,100.,125.])
max_curr_AX_table =np.array([82.5,132.,190.,189.,170.,136.])
max_curr_CV_table =np.array([82.5,132.,178.,189.,170.,136.])
max_curr_Cat_table=np.array([82.5,132.,178.,167.,150.,120.])
max_curr_Catplus_table=np.array([130.,180.,190.,189.,170.,136.])
ax.plot(xrayVoltages,max_curr_AX_table,marker='.',linestyle='-', color='black', label='new AX')
ax.plot(xrayVoltages,max_curr_CV_table,marker='+',linestyle='-', color='grey', label='new CV')
ax.plot(xrayVoltages,max_curr_Cat_table,marker='x',linestyle='-', color='green', label='Cat')
ax.plot(xrayVoltages,max_curr_Catplus_table,marker='*',linestyle='-', color='magenta', label='org Cat+')
ax.set_ylabel('Current /[mA]', size='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
plt.title('Voltage vs Current - Micro Focus', size='small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
leg.get_frame().set_alpha(0.5)
ax.set_xlim([40,130])
ax.grid(True)
plt.title('Punch through tables', size='small')
# accumulated evaporation vs accumulated scenetime with different punch through tables (just mA reduction to max allowed value)
ax = fig.add_subplot(3,2,5)
tungst_thickness_AX=numpy.zeros(self.myXEvent.range)
tungst_thickness_CV=numpy.zeros(self.myXEvent.range)
outputfile=os.path.join(self.resultsDirSN,'FG_data.csv')
fw = open(outputfile, "w")
datastr= 'kv, scenelength, tube_curr, heat_curr , em_temp, eva_rate, tube_curr_AX, heat_curr_AX, em_temp_AX, eva_rate_AX\n'
fw.write(datastr)
for i in range(self.events):
max_curr_AX=self.my_linear_interpol1d(xrayVoltages,max_curr_AX_table,self.myXEvent.voltage[i])
max_curr_CV=self.my_linear_interpol1d(xrayVoltages,max_curr_CV_table,self.myXEvent.voltage[i])
current_AX= min(self.myXEvent.current[i],max_curr_AX)
current_CV= min(self.myXEvent.current[i],max_curr_CV)
heat_curr_AX=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,self.myXEvent.voltage[i]*1000,current_AX*10.)/10.
heat_curr_CV=self.my_linear_interpol2d(kVs_FG,tube_currents_FG,heating_currents_FG,self.myXEvent.voltage[i]*1000,current_CV*10.)/10.
emitt_temp_AX=self.get_filament_temp(heat_curr_AX)
emitt_temp_CV=self.get_filament_temp(heat_curr_CV)
tungst_thickness_AX[i]=self.get_evap_rate(emitt_temp_AX)*self.myXEvent.scenelength[i]/60./60./1000.
tungst_thickness_CV[i]=self.get_evap_rate(emitt_temp_CV)*self.myXEvent.scenelength[i]/60./60./1000.
if self.myXEvent.mode[i]==ord('A') and self.myXEvent.focus[i]==ord('M'):
datastr= str(self.myXEvent.voltage[i])+','+str(self.myXEvent.scenelength[i]/1000.)+','+ str(self.myXEvent.current[i])+','+ str(self.myXEvent.heating_current[i])+',' +str(self.myXEvent.emitter_temp[i])+','+str(self.myXEvent.tungst_evaporation_rate[i])
datastr=datastr+','+str(current_AX)+','+str(heat_curr_AX)+','+str(emitt_temp_AX)+','+str(self.get_evap_rate(emitt_temp_AX))
datastr=datastr+','+str(current_CV)+','+str(heat_curr_CV)+','+str(emitt_temp_CV)+','+str(self.get_evap_rate(emitt_temp_CV))+'\n'
fw.write(datastr)
tungst_thickness_AX_M=tungst_thickness_AX[idx_fg]
tungst_thickness_CV_M=tungst_thickness_CV[idx_fg]
fw.close()
ax.plot(Scenetime_M.cumsum()/1000./3600.,tungst_thickness_AX_M.cumsum(),marker='', linestyle='-' ,color='blue' ,label=u'AX (%2.2fµm)'%(tungst_thickness_AX_M.sum()))
ax.plot(Scenetime_M.cumsum()/1000./3600.,tungst_thickness_CV_M.cumsum(),marker='', linestyle='dashed',color='green',label=u'CV (%2.2fµm)'%(tungst_thickness_CV_M.sum()))
ax.plot(Scenetime_M.cumsum()/1000./3600.,Tungst_thick.cumsum(),marker='', linestyle='-',color='black',label=u'org (%2.2fµm)'%(Tungst_thick.sum()))
ax.set_ylabel(u'accum. Tungsten thickness /[µm]', size='x-small')
ax.set_xlabel('accum. scenetime /[h]', size='x-small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title(u'accumulated Tungsten thickness vs accumulated scenetime\n mean Tungsten evap. rate AX: %2.1f [µm/100h]\nmean Tungsten evap. rate CV: %2.1f [µm/100h]'%(100.*tungst_thickness_AX_M.sum()/(Scenetime_M.sum()/3600./1000.),100.*tungst_thickness_CV_M.sum()/(Scenetime_M.sum()/3600./1000.)), size='x-small')
ax.grid(True)
#Histogram over evaporated Tungsten in kV interval
ax = fig.add_subplot(3,2,6)
kv_bins=[40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125]
tungst_sum_org=numpy.zeros(len(kv_bins)-1)
tungst_sum_AX=numpy.zeros(len(kv_bins)-1)
tungst_sum_CV=numpy.zeros(len(kv_bins)-1)
for i in range(len(kv_bins)-1):
tungst_sum_org[i]=((Voltage_M>=kv_bins[i])*(Voltage_M<kv_bins[i+1])*Tungst_thick).sum()
tungst_sum_AX[i] =((Voltage_M>=kv_bins[i])*(Voltage_M<kv_bins[i+1])*tungst_thickness_AX_M).sum()
tungst_sum_CV[i] =((Voltage_M>=kv_bins[i])*(Voltage_M<kv_bins[i+1])*tungst_thickness_CV_M).sum()
ax.plot(kv_bins[:-1], tungst_sum_org, marker='.', linestyle='-', color='black',label='Cat+ org')
ax.plot(kv_bins[:-1], tungst_sum_AX, marker='.', linestyle='-' ,color='blue',label='Cat+ AX')
ax.plot(kv_bins[:-1], tungst_sum_CV, marker='.', linestyle='dashed',color='green', label='Cat+ CV')
ax.set_ylabel(u'integral Tungsten thickness /[µm]', size='x-small')
ax.set_xlabel('kV interval (55 means 55-60)', size='x-small')
plt.title('Histogram over evaporated Tungsten in kV interval ', size='small')
ax.set_xlim([40,130])
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
"""
#Evaporated Tungsten Thickness vs kV slot (Fluoro and Acquisition) for alternative punch through tables
ax = fig.add_subplot(3,2,6)
Tungst_thick_sorted_AX_M=tungst_thickness_AX_M[sort_indices_kv]
Tungst_thick_sorted_CV_M=tungst_thickness_CV_M[sort_indices_kv]
ax.plot(Voltage_M_sorted,Tungst_thick_sorted_AX_M.cumsum(),label='Total AX', color='blue')
ax.plot(Voltage_M_sorted,Tungst_thick_sorted_CV_M.cumsum(),label='Total CV', linestyle='dashed', color='green')
ax.plot(Voltage_M_sorted,Tungst_thick_sorted.cumsum(),label='Total org', color='black')
ax.set_xlabel('Tube Voltage /[kV] ', size='x-small')
ax.set_ylabel('rel. Tungsten thickness', size='x-small')
plt.title(u'Summed evaporated Tungsten thickness over voltage', size='small')
ax.legend(loc=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
"""
#-----------page top and end-------------------
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part13 (FG Analysis)'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr), horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.05,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p5.png')
###
plt.close()
if (self.cb_png.GetValue()==False):
pdf.close()
######################################################################################################################
#part14
if self.cb14.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,10))
Dosisausbeute = []
Kupfer = []
Spannung = []
#Stromstaerke = []
for i in range(len(SID)+1):
if self.myXEvent.focus[i] == ord('S'):
# if self.myXEvent.scenelength[i] > 2:
if self.myXEvent.frequency[i] != 0.1:
if self.myXEvent.time[i] > 5:
Dosisausbeute.append(self.myXEvent.dose_per_mAs[i])
Kupfer.append(self.myXEvent.filt[i])
Spannung.append(self.myXEvent.voltage[i])
#Stromstaerke.append(self.myXEvent.current[i])
ax = Axes3D(fig)
f = ax.scatter(Kupfer, Spannung, Dosisausbeute)
ax.set_zlabel('Dosisausbeute /[$\mu$Gy/mAs]', size='x-small')
ax.set_xlabel('Cu-Filter ', size='x-small')
ax.set_ylabel('Voltage /[kV] ', size='x-small')
ax.grid(True)
plt.title('F1')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part14'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_14.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
######################################################################################################################
#part15
if self.cb15.GetValue() or self.cb0.GetValue():
#Part25 in Matlab
fig = plt.figure(figsize=(14, 19))
Spannung_A_L = []
Spannung_A_S = []
Spannung_A_M = []
Spannung_F_L = []
Spannung_F_M = []
Spannung_F_S = []
Current_A_L = []
Current_A_M = []
Current_A_S = []
Current_F_L = []
Current_F_M = []
Current_F_S = []
for i in range(len(SID)+1):
if self.myXEvent.mode[i] == ord('A'):
if self.myXEvent.focus[i] == ord('L'):
Spannung_A_L.append(self.myXEvent.voltage[i])
Current_A_L.append(self.myXEvent.current[i])
if self.myXEvent.focus[i] == ord('S'):
Spannung_A_S.append(self.myXEvent.voltage[i])
Current_A_S.append(self.myXEvent.current[i])
if self.myXEvent.focus[i] == ord('M'):
Spannung_A_M.append(self.myXEvent.voltage[i])
Current_A_M.append(self.myXEvent.current[i])
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.focus[i] == ord('L'):
Spannung_F_L.append(self.myXEvent.voltage[i])
Current_F_L.append(self.myXEvent.current[i])
if self.myXEvent.focus[i] == ord('S'):
Spannung_F_S.append(self.myXEvent.voltage[i])
Current_F_S.append(self.myXEvent.current[i])
if self.myXEvent.focus[i] == ord('M'):
Spannung_F_M.append(self.myXEvent.voltage[i])
Current_F_M.append(self.myXEvent.current[i])
ax = fig.add_subplot(3,1,1)
ax.plot(Spannung_A_S, Current_A_S, marker='.', linestyle='.', color='r')
ax.plot(Spannung_F_S, Current_F_S, marker='.', linestyle='.', color='b')
ax.set_ylabel('Current /[mA]', size='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
plt.title('Small Focus')
pylab.legend(('Acquisition', 'Fluoro'))
ax.set_xlim([40,130])
ax.grid(True)
ax = fig.add_subplot(3,1,2)
ax.plot(Spannung_A_L, Current_A_L, marker='.', linestyle='.', color='r')
ax.plot(Spannung_F_L, Current_F_L, marker='.', linestyle='.', color='b')
ax.set_ylabel('Current /[mA]', size='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
plt.title('Large Focus')
pylab.legend(('Acquisition', 'Fluoro'))
ax.set_xlim([40,130])
ax.grid(True)
ax = fig.add_subplot(3,1,3)
ax.plot(Spannung_A_M, Current_A_M, marker='.', linestyle='.', color='r')
ax.plot(Spannung_F_M, Current_F_M, marker='.', linestyle='.', color='b')
ax.set_ylabel('Current /[mA]', size='x-small')
ax.set_xlabel('Voltage /[kV]', size='x-small')
plt.title('Micro Focus')
pylab.legend(('Acquisition', 'Fluoro'))
ax.set_xlim([40,130])
ax.grid(True)
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part15'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_15.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#####################################################################################################################
#part16
if self.cb16.GetValue() or self.cb0.GetValue():
#Part24 in Matlab
fig = plt.figure(figsize=(14, 19))
xxtime = [dateutil.parser.parse(s) for s in TIME]
L_time = [dateutil.parser.parse(s) for s in Lernparameter_datum]
s = pylab.date2num(xxtime)
LL_time = pylab.date2num(L_time)
min_angle = 3
water_vertical = []
s_vertical = []
for i in range(len(SID)-1):
if numpy.abs(self.myXEvent.cran[i])<min_angle:
if numpy.abs(self.myXEvent.rao[i])<min_angle:
water_vertical.append(self.myXEvent.was[i])
s_vertical.append(s[i])
event_summe = [] #jedem event wird eine 1 zugeordnet; summiere anschließend auf
event_summe.append(1)
for i in range(1, len(SID)):
event_summe.append(event_summe[i-1]+1)
ax = fig.add_subplot(4,1,1)
ax.plot_date(s_vertical, water_vertical, marker='.', linestyle='.')
ax.set_ylabel('Watervalue /[mm]', size='x-small')
fig.autofmt_xdate()
#BE calculations
#---------------
#Inits BE Berechnung
sum_BE_green=[]
sum_BE_yellow=[]
sum_BE_red=[]
old_sum_BE_green=0;
old_sum_BE_yellow=0; #ca. 1600W
old_sum_BE_red=0; #ca. 3200W
if self.myXEvent.tubetype==0: #Cat
HU_yellow=50.
HU_red=75.
elif self.myXEvent.tubetype==1:
HU_yellow=44.
HU_red=74.
elif self.myXEvent.tubetype==2:
HU_yellow=45.
HU_red=75.
BE_A_green=2. #BE je Acq im grünen Bereich
BE_F_green=30. #BE je Fluoro im grünen Bereich
BE_A_yellow=2. #BE je Acq im gelben Bereich
BE_F_yellow=30. #BE je Fluoro im gelben Bereich
BE_A_red=2. #BE je Acq im roten Bereich
BE_F_red=30. #BE je Fluoro im roten Bereich
#HU specific BE calulation
k_green=0
k_yellow=0
k_red=0;
for i in range(self.events):
if(self.myXEvent.mode[i]==ord('A')):
if (self.myXEvent.HU[i]<HU_yellow):
k_green=1/BE_A_green
k_yellow=0
k_red=0
elif (self.myXEvent.HU[i]>HU_yellow and self.myXEvent.HU[i]<HU_red):
k_green=0
k_yellow=1/BE_A_yellow
k_red=0;
else: #HU>=HU_red)
k_green=0
k_yellow=0
k_red=1/BE_A_red
else: #Mode==Fluoro
if (self.myXEvent.HU[i]<HU_yellow):
k_green=1/BE_F_green
k_yellow=0
k_red=0
elif (self.myXEvent.HU[i]>HU_yellow and self.myXEvent.HU[i]<HU_red):
k_green=0
k_yellow=1/BE_F_yellow
k_red=0;
else: #HU>=HU_red)
k_green=0
k_yellow=0
k_red=1/BE_F_red
dt=self.myXEvent.scenelength[i]/1000.
sum_BE_green.append(old_sum_BE_green+k_green*dt)
sum_BE_yellow.append(old_sum_BE_yellow+k_yellow*dt)
sum_BE_red.append(old_sum_BE_red+k_red*dt)
old_sum_BE_green=sum_BE_green[i]
old_sum_BE_yellow=sum_BE_yellow[i]
old_sum_BE_red=sum_BE_red[i]
ax = fig.add_subplot(4,1,2)
ax.plot_date(s, np.array(sum_BE_green)+np.array(sum_BE_yellow)+np.array(sum_BE_red) , marker='', linestyle='--',color='black',label="BE_sum")
ax.plot_date(s, np.array(sum_BE_green) , marker='', linestyle='-',color='g',label="BE_green")
ax.plot_date(s, np.array(sum_BE_yellow) , marker='', linestyle='-',color='y',label="BE_yellow")
ax.plot_date(s, np.array(sum_BE_red) , marker='', linestyle='-',color='r',label="BE_red")
ax.set_ylabel('BE ', size='x-small')
ax.legend(loc=2)
fig.autofmt_xdate()
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax = fig.add_subplot(4,1,3)
ax.plot_date(s, event_summe, marker='', linestyle='-')
ax.set_ylabel('X-Rays ', size='x-small')
fig.autofmt_xdate()
#Heat-Current
L_time = [dateutil.parser.parse(s) for s in Lernparameter_datum]
LL_time = pylab.date2num(L_time)
currL = []
currS = []
currM = []
for i in range(len(L1)):
currL.append( (300*int(L1[i])+int(L2[i])+int(L3[i]))/10. )
currS.append( (300*int(S1[i])+int(S2[i])+int(S3[i]))/10. )
if self.myXEvent.numFoken==3:
currM.append( (300*int(M1[i])+int(M2[i])+int(M3[i]))/10. )
ax = fig.add_subplot(4,1,4)
ax.plot_date(LL_time, currL, marker='.', linestyle='-', color='b')
ax.plot_date(LL_time, currS, marker='.', linestyle='-', color='g')
if self.myXEvent.numFoken==3:
ax.plot_date(LL_time, currM, marker='.', linestyle='-', color='r')
ax.set_ylabel('Heat current /[mA]', size='x-small')
fig.autofmt_xdate()
if self.myXEvent.numFoken==3:
pylab.legend(('L', 'S', 'M'))
else:
pylab.legend(('L', 'S'))
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part16'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_16.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
######################################################################################################
#part17
if self.cb17.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
#Heat-Unit - time
ax = fig.add_subplot(2,1,1)
dates = [dateutil.parser.parse(s) for s in TIME]
_44 = [] #es soll eine Linie bei 74% und eine bei 44% eingezogen werden
_74 = []
for i in range(len(dates)):
_74.append(74)
_44.append(44)
ax.plot_date(pylab.date2num(dates), heatunit, marker='', linestyle='-')
ax.plot_date(pylab.date2num(dates), _74, marker='_', linestyle='-', color='r')
ax.plot_date(pylab.date2num(dates), _44, marker='_', linestyle='-', color='y')
ax.set_ylabel('Heat-Unit /[%]', size='x-small')
ax.set_xlabel('Datum', size='x-small')
ax.set_ylim((0,100))
ax.grid(True)
fig.autofmt_xdate()
plt.title('Heat-Unit - time')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part17'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_17.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
############################################################################################
#part18 Arcing Analysis
if self.cb18.GetValue() or self.cb0.GetValue():
self.do_part18()
##################################################################################################################
#part19
if self.cb19.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14, 19))
haufigkeit = []
bezeichnung = []
d = {}
for i in set(self.myXEvent.OGP):
d[i] = self.myXEvent.OGP.count(i)
a = sorted(d.items(), key=itemgetter(1))
for i in range(len(a)):
bezeichnung.append(a[i][0])
s = a[i][1]
for j in range(s):
haufigkeit.append(i+1)
c = []
for i in range(len(bezeichnung)):
c.append(i+1)
ax = fig.add_subplot(1,1,1)
ax.hist(haufigkeit, 100)
#ax.set_xlabel('', size='x-small')
ax.set_ylabel('Occurance /#', size='x-small')
ax.grid(True)
plt.title('Radiation events')
plt.xticks(c, bezeichnung, rotation=90)
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part19'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(total_events))+' ('+str(len(SID))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_19.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#######################################################################################################################
#part20
if self.cb20.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
ax = fig.add_subplot(2,1,1)
xi = numpy.linspace(min(rao), max(rao), 100)
yi = numpy.linspace(min(cran), max(cran), 100)
zi = griddata(cran, rao, skindose, xi, yi)
plt.contour(xi, yi, zi, 15, cmap=plt.cm.jet)
cbar = plt.colorbar()
cbar.set_label('Skindose /[$\mu$Gy]')
ax.set_xlabel('Cran /[$\,^{\circ}$]', size='x-small')
ax.set_ylabel('Rao /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
ax = fig.add_subplot(2,1,2)
ax.plot(rao, cran, '.')
ax.set_xlabel('Cran /[$\,^{\circ}$]', size='x-small')
ax.set_ylabel('Rao /[$\,^{\circ}$]', size='x-small')
ax.grid(True)
plt.title('Cran vs Rao-angle')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part20'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(total_events))+' ('+str(len(SID))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_20.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#####################################################################################################################
#part21
if self.cb21.GetValue() or self.cb0.GetValue():
#Soll-Szenenlaenge; nur für Acq-events
fig = plt.figure(figsize=(14,14))
#Soll-Szenenlaenge vs. Szenenlaenge
ax = fig.add_subplot(1,1,1)
ax.plot(self.myXEvent.soll_Szenenlaenge , self.myXEvent.ist_Szenenlaenge, '.')
ax.set_xlabel('Soll-Szenenlaenge /[s]', size='x-small')
ax.set_ylabel('Szenenlaenge /[s]', size='x-small')
ax.grid(True)
plt.title('Soll-Szenenlaenge vs. Szenenlaenge')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part21'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(total_events))+' ('+str(len(SID))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_21.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#####################################################################################################################
#part22
if self.cb22.GetValue() or self.cb0.GetValue():
#Soll-FD.Dosis; nur für Acq-events
fig = plt.figure(figsize=(14,14))
aaa = []
bbb = []
for i in range(len(self.myXEvent.soll_fd_dosis)):
aaa.append(self.myXEvent.soll_fd_dosis[i]/1000.)
bbb.append(systemdose[i]/1000.)
ax = fig.add_subplot(1,1,1)
ax.plot(aaa , bbb, '.')
ax.set_xlabel('Soll-FD-Dosis /[$\mu$Gy]', size='x-small')
ax.set_ylabel('Ist-FD-Dosis /[$\mu$Gy]', size='x-small')
ax.grid(True)
plt.title('Soll-FD-Dosis vs. Ist-FD-Dosis')
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part22'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(total_events))+' ('+str(len(SID))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_22.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
######################################################################################################################
#part23
if (self.cb23.GetValue() or self.cb0.GetValue()) and self.events>1:
print "Creating Cons report"
num_studies=patient_number[-1]
num_events=len(SID)
fig = plt.figure(figsize=(14,19))
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+str(self.plane)+'_Cons.pdf')
pdf = PdfPages(name)
font = FontProperties()
font = font.copy()
font.set_family('monospace')
fig.text(0.5, 0.95,'Analysis of system XA'+str(self.myXEvent.SN), horizontalalignment='center', verticalalignment='center')
#fig.text(0.49, 0.94,'Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)', horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.98,'Radiation events on plane '+str(self.plane)+':'+' '+str(len(TIME))+' ('+str(len(total_events))+' total)'+'\n System SW:'+self.myXEvent.SW[-1][0]+' - Tube Type:'+self.myXEvent.tubetype_str+' - FD Type:'+self.myXEvent.FDtype+' - System Type: '+self.myXEvent.SystemType, horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.96,'Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
#fig.text(0.5, 0.93,str(Startzeit[0])+' - '+str(Startzeit[-1]), horizontalalignment='center', verticalalignment='center')
#skindose/study histogram
aaa=[x/1000. for x in self.myXEvent.pat_skindose]
ax = fig.add_subplot(4,3,1)
if len(aaa)>0:
ax.hist(aaa+[-1], range =(0, max(aaa)), bins=20)
ax.set_xlabel('Skindose/study [mGy]', size='x-small')
ax.set_ylabel('Occurance', size='x-small')
ax.set_xlim(0, max(aaa))
ax.grid(True)
plt.xticks(rotation=10, size='x-small')
plt.title('Skindose/study', size='small')
#Skindose/study Tortendiagramm
skindose_3D = []
_3D = []
DAP_3D = []
for i in range(len(SID)):
if self.myXEvent._3Dmode[i] != 'no3d':
skindose_3D.append(self.myXEvent.skindose[i])
DAP_3D.append(self.myXEvent.DAP[i])
_3D.append(self.myXEvent.skindose[i])
fracs = []
if sum(skindose)>0:
fracs.append(sum(skindose_F)/sum(skindose))
fracs.append((sum(skindose_A)-sum(skindose_3D))/sum(skindose))
fracs.append(sum(skindose_3D)/sum(skindose))
ax = fig.add_subplot(4,3,2)
labels = 'Fluoro', 'Acquisition', '3D'
ax.pie(fracs, labels=labels, colors=('r', 'g', 'y'), autopct='%1.0f%%', shadow=False)
plt.title('Skindose/study', size='small')
#skindose/study
s_F = sum(skindose_F)
s_F_study = s_F/num_studies #Division durch die Anzahl der untersuchtern Patienten
s_A = sum(skindose_A)
s_A_study = s_A/num_studies
s_3D = sum(_3D)
s_3D_study = s_3D/num_studies
#total = sum(skindose)/num_studies
total = (s_F + s_A)/num_studies
Vektor = []
for i in range(len(Datum_array)-1): #die Anzahl der Tage wird ermittelt; zunaechst anhand der "Tageswechsel"
if Datum_array[i] != Datum_array[i+1]:
Vektor.append(1)
Vektor.append(1) #Tage = Tageswechsel + 1
tage = len(Vektor)
ax = fig.add_subplot(4,3,3)
ax.axis('off')
ax.text(0.15, 0.90, u"FL [mGy]: {0}".format(round(0.001*s_F_study, 2)), fontproperties=font) #von mykro auf milli-Gy umgerechnet
ax.text(0.15, 0.85, u"Percentage [%]: {0}".format(round(100*(s_F_study/total))), fontproperties=font) #in Prozent umgerechnet
ax.text(0.15, 0.75, u"ACQ [mGy]: {0}".format(round(0.001*(s_A_study-s_3D_study), 2)), fontproperties=font)
ax.text(0.15, 0.70, u"Percentage [%]: {0}".format(round(100*((s_A_study-s_3D_study)/total), 2)), fontproperties=font)
ax.text(0.15, 0.60, u"3D [mGy]: {0}".format(round(0.001*s_3D_study, 2)), fontproperties=font)
ax.text(0.15, 0.55, u"Percentage [%]: {0}".format(round(100*(s_3D_study/total), 2)), fontproperties=font)
ax.text(0.15, 0.50, u"----------------------------------------", fontproperties=font)
ax.text(0.15, 0.40, u"Total skindose/study [mGy]: {0}".format(round(0.001*total, 2)), fontproperties=font)
#ax.text(0.15, 0.35, u"Average skindose/day [mGy]: {0}".format(round(0.001*sum(skindose)/tage, 2)), fontproperties=font)
ax.text(0.15, 0.30, U"Avg. skind./Fluoro [mGy] : {0}".format(round(0.01*s_F_study/len(zoom_F) * num_studies / 10, 2)), fontproperties=font)
ax.text(0.15, 0.25, U"Avg. skind./Acq [mGy] : {0}".format(round(0.01*s_A_study/len(zoom_A) * num_studies / 10, 2)), fontproperties=font)
ax.text(0.15, 0.15, U"Avg. skind./sec Fluoro [mGy/s]: {0}".format(round(0.01*s_F/ sum(scenelength_F) / 10, 2)), fontproperties=font)
ax.text(0.15, 0.10, U"Avg. skind./sec Acq [mGy/s]: {0}".format(round(0.01*s_A/ sum(scenelength_A) / 10, 2)), fontproperties=font)
plt.title('Skindose/study', size='small')
#DAP/study histogram
aaa=[x/100. for x in self.myXEvent.pat_dap]
ax = fig.add_subplot(4,3,4)
if len(aaa)>0:
ax.hist(aaa+[-1], range =(0, max(aaa)), bins=20)
ax.set_xlabel('DAP/study [$\mu$Gym^2]', size='x-small')
ax.set_ylabel('Occurance', size='x-small')
ax.set_xlim(0, max(aaa))
ax.grid(True)
plt.xticks(rotation=10, size='x-small')
plt.title('DAP/study', size='small')
#DAP/study Tortendiagramm
fracs = []
if sum(DAP)>0:
fracs.append(sum(DAP_F)/sum(DAP))
fracs.append((sum(DAP_A)-sum(DAP_3D))/sum(DAP))
fracs.append(sum(DAP_3D)/sum(DAP))
ax = fig.add_subplot(4,3,5)
labels = 'Fluoro', 'Acquisition', '3D'
ax.pie(fracs, labels=labels, colors=('r', 'g', 'y'), autopct='%1.0f%%', shadow=False)
plt.title('DAP/study', size='small')
#DAP/study
s_F = sum(DAP_F)
s_F_study = s_F/num_studies #Division durch die Anzahl der untersuchten Patienten
s_A = sum(DAP_A)
s_A_study = s_A/num_studies
_3D = []
for i in range(len(SID)):
if self.myXEvent._3Dmode[i] != 'no3d':
_3D.append(self.myXEvent.DAP[i])
s_3D = sum(_3D)
s_3D_study = s_3D/num_studies
#total = sum(DAP)/num_studies
total = (s_F + s_A)/num_studies
ax = fig.add_subplot(4,3,6)
ax.axis('off')
ax.text(0.15, 0.90, u"FL [µGym²]: {0}".format(round(0.01*s_F_study, 2)), fontproperties=font) #0.01 stammt als Faktor aus der .csv-Datei
ax.text(0.15, 0.85, u"Percentage [%]: {0}".format(round(100*s_F_study/total)), fontproperties=font)
ax.text(0.15, 0.75, u"ACQ [µGym²]: {0}".format(round(0.01*(s_A_study-s_3D_study), 2)), fontproperties=font)
ax.text(0.15, 0.70, u"Percentage [%]: {0}".format(round(100*(s_A_study-s_3D_study)/total, 2)), fontproperties=font)
ax.text(0.15, 0.60, u"3D [µGym²]: {0}".format(round(0.01*s_3D_study), 2), fontproperties=font)
ax.text(0.15, 0.55, U"Percentage [%]: {0}".format(round(100*s_3D_study/total, 2)), fontproperties=font)
ax.text(0.15, 0.50, u"------------------------------------", fontproperties=font)
ax.text(0.15, 0.40, u"Total DAP/study [µGym²]: {0}".format(round(0.01*total, 2)), fontproperties=font)
#ax.text(0.15, 0.35, u"Average DAP/day [µGym²]: {0}".format(round(0.01*(sum(DAP)/tage), 2)), fontproperties=font)
ax.text(0.15, 0.30, u"Avg. DAP/Fluoro [µGy m²] : {0}".format(round(0.01*s_F/len(zoom_F), 2)), fontproperties=font)
ax.text(0.15, 0.25, u"Avg. DAP/Acq [µGy m²] : {0}".format(round(0.01*s_A/len(zoom_A), 2)), fontproperties=font)
ax.text(0.15, 0.15, u"Avg. DAP/sec Fluoro [µGy m²/s]: {0}".format(round(0.01*s_F/ sum(scenelength_F), 2)), fontproperties=font)
ax.text(0.15, 0.10, u"Avg. DAP/sec Acq [µGy m²/s]: {0}".format(round(0.01*s_A/ sum(scenelength_A), 2)), fontproperties=font)
num_F_A=((self.myXEvent.mode[0:self.events]==ord('A'))*self.myXEvent.frames[0:self.events]).sum()
ax.text(0.15, 0.05, u"Avg. DAP/frame Acq [µGy m²/f]: {0}".format(round(0.01*s_A/num_F_A, 2)), fontproperties=font)
plt.title('DAP/study', size='small')
#10R/min FL Limit - 34cm in front of FD
_10R = []
for i in range(1, len(SID)):
if self.myXEvent._10Rlimit[i] != 0:
_10R.append(self.myXEvent._10Rlimit[i])
if sum(skindose)>0:
ax = fig.add_subplot(4,3,7)
try:
ax.hist(_10R, 25)
ax.set_xlabel('Skindose [R/min]', size='x-small')
ax.set_ylabel('Fluoro events', size='x-small')
ax.grid(True)
plt.xticks(rotation=10, size='x-small')
plt.title('10R/min FL limit - 34cm in front of FD', size='small')
except:
True
#Events & time vs. focus
#events vs focus
f_s = []
f_l = []
f_m = []
a_s = []
a_l = []
a_m = []
#time vs focus
f_s_S = []
f_l_S = []
f_m_S = []
a_s_S = []
a_l_S = []
a_m_S = []
for i in range(len(SID)): #es wird nach focus und Fluoro/Acquisition aussortiert
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.focus[i] == ord('S'):
f_s.append(1)
elif self.myXEvent.focus[i] == ord('L'):
f_l.append(1)
else:
f_m.append(1)
if self.myXEvent.mode[i] == ord('A'):
if self.myXEvent.focus[i] == ord('S'):
a_s.append(1)
elif self.myXEvent.focus[i] == ord('L'):
a_l.append(1)
else:
a_m.append(1)
total = sum(f_s)+sum(f_l)+sum(f_m)+sum(a_s)+sum(a_l)+sum(a_m)
for i in range(self.myXEvent.range): #es wird nach focus und Fluoro/Acquisition aussortiert
if self.myXEvent.mode[i] == ord('F'):
if self.myXEvent.focus[i] == ord('S'):
f_s_S.append(self.myXEvent.scenelength[i])
elif self.myXEvent.focus[i] == ord('L'):
f_l_S.append(self.myXEvent.scenelength[i])
else:
f_m_S.append(self.myXEvent.scenelength[i])
if self.myXEvent.mode[i] == ord('A'):
if self.myXEvent.focus[i] == ord('S'):
a_s_S.append(self.myXEvent.scenelength[i])
elif self.myXEvent.focus[i] == ord('L'):
a_l_S.append(self.myXEvent.scenelength[i])
else:
a_m_S.append(self.myXEvent.scenelength[i])
#Summary Text1
_3D = []
for i in range(len(SID)):
if self.myXEvent._3Dmode[i] != 'no3d':
_3D.append(1)
ax = fig.add_subplot(4,3,8)
ax.axis('off')
ax.text(0.1, 0.90, u"Number of studies : {0}".format(int(num_studies)), fontproperties=font)
ax.text(0.1, 0.85, u"Days system was used : {0}".format(tage), fontproperties=font)
ax.text(0.1, 0.80, u"Number of studies/day : {0}".format(round(num_studies/float(tage),2)),fontproperties=font)
ax.text(0.1, 0.65, u"Avg. skind./sec Fluoro [mGy/s]: {0}".format(round(0.01*sum(skindose_F)/ sum(scenelength_F) / 10, 2)), fontproperties=font)
ax.text(0.1, 0.60, u"Avg. skind./sec Acq [mGy/s]: {0}".format(round(0.01*sum(skindose_A)/ sum(scenelength_A) / 10, 2)), fontproperties=font)
ax.text(0.1, 0.55, u"Avg. DAP/sec Fluoro [µGy m²/s]: {0}".format(round(0.01*sum(DAP_F)/ sum(scenelength_F), 2)), fontproperties=font)
ax.text(0.1, 0.50, u"Avg. DAP/sec Acq [µGy m²/s]: {0}".format(round(0.01*sum(DAP_A)/ sum(scenelength_A), 2)), fontproperties=font)
ax.text(0.1, 0.45, u"Watervalue mean : {0}".format(round(numpy.mean(watervalue),1)), fontproperties=font)
ax.text(0.1, 0.40, u"Watervalue SD : {0}".format(round(numpy.std(watervalue),1)), fontproperties=font)
ax.text(0.1, 0.30, u"Fluoro mean kV : {0}".format(round(numpy.mean(voltage_F),1)), fontproperties=font)
ax.text(0.1, 0.25, u"Fluoro SD of kV : {0}".format(round(numpy.std(voltage_F),1)), fontproperties=font)
ax.text(0.1, 0.15, u"Acquisition mean kV : {0}".format(round(numpy.mean(voltage_A),1)), fontproperties=font)
ax.text(0.1, 0.10, u"Acquisition SD of kV : {0}".format(round(numpy.std(voltage_A),1)), fontproperties=font)
ax.text(0.1, 0.00, u"Prev Pos = Rev Pos : {0}%".format(round(100.*np.mean(preview_review),1)), fontproperties=font)
ax.text(0.1,-0.05, u"mean delta kV (Prev - Rev) : {0}".format(round((np.array(self.myXEvent.soll_kV)-self.myXEvent.voltage[0:self.events]).mean(),1)), fontproperties=font)
plt.title('Summary 1', size='small')
# Summary Text 2
ax = fig.add_subplot(4,3,9)
ax.axis('off')
ax.text(0.15, 0.90, "Mean FL time [s]: {0}".format(round(mean(scenelength_F), 1)), fontproperties=font)
ax.text(0.15, 0.85, "Mean FL time/study[min]: {0}".format(round(sum(scenelength_F)/num_studies/60., 1)), fontproperties=font)
ax.text(0.15, 0.80, "Fl events/study : {0}".format(round(len(zoom_F)/num_studies, 1)), fontproperties=font)
ax.text(0.15, 0.70, "Mean ACQ time [s]: {0}".format(round(mean(scenelength_A), 1)), fontproperties=font)
ax.text(0.15, 0.65, "ACQ events/study : {0}".format(round(len(scenelength_A)/num_studies, 1)), fontproperties=font)
ax.text(0.15, 0.55, "Mean 3D events/study : {0}".format(round(len(_3D)/num_studies, 1)), fontproperties=font)
ax.text(0.15, 0.45, "Fl events : {0}".format(len(zoom_F)), fontproperties=font)
ax.text(0.15, 0.40, "Total ACQ events : {0}".format(len(zoom_A)), fontproperties=font)
ax.text(0.15, 0.35, "- ACQ : {0}".format(len(DAP_A)-len(alternative_acquisition)-len(_3D)), fontproperties=font)
ax.text(0.15, 0.30, "- ALT-ACQ : {0}".format(len(alternative_acquisition)), fontproperties=font)
ax.text(0.15, 0.25, "3D events : {0}".format(len(_3D)), fontproperties=font)
ax.text(0.15, 0.15, u"Micro Focus FL, ACQ(%): {0}".format([round(int(100*(sum(f_m)/total)),2), round(int(100*(sum(a_m)/total)),2)]), fontproperties=font)
ax.text(0.15, 0.10, u"Small Focus FL, ACQ(%): {0}".format([round(int(100*(sum(f_s)/total)),2), round(int(100*(sum(a_s)/total)),2)]), fontproperties=font)
ax.text(0.15, 0.05, u"Large Focus FL, ACQ(%): {0}".format([round(int(100*(sum(f_l)/total)),2), round(int(100*(sum(a_l)/total)),2)]), fontproperties=font)
ax.text(0.15, 0.00, u"BE/day : %2.1f"%(self.myXEvent.BE_total.sum()/day_total), fontproperties=font)
ax.text(0.15,-0.05, u"Line resistance : %s"%(self.line_resistance), fontproperties=font)
ax.text(0.15,-0.10, u"Line voltage : %s"%(self.line_voltage), fontproperties=font)
#ax.text(0.15, -0.05, u"Line resistance : "+self.line_resistance)
#ax.text(0.15, -0.10, u"Line voltage : "+self.line_voltage)
plt.title('Summary 2', size='small')
#SID histogram
ax = fig.add_subplot(4,3,10)
if len(SID)>0:
ax.hist(SID, 15)
ax.set_xlabel('SID [cm]',size='x-small' )
ax.set_ylabel('Occurance',size='x-small' )
ax.grid(True)
plt.title("SID; [mean, SD]={0}".format( [ round(numpy.mean(SID)), round(numpy.std(SID)) ]), size='small' )
#Watervalue histogram
ax = fig.add_subplot(4,3,11)
if len(watervalue)>0:
ax.hist(watervalue, 25)
#ax.set_xlim(1, 500)
ax.set_xlabel('Watervalue [mm]',size='x-small' )
ax.set_ylabel('Occurance', size='x-small' )
ax.grid(True)
plt.xticks(rotation=10, size='x-small')
plt.title("Watervalue [mean, SD]={0}".format( [ round(numpy.mean(watervalue)), round(numpy.std(watervalue)) ]), size='small')
#Zoom histogram
try:
ax = fig.add_subplot(4,6,23)
ax.hist(zoom_F, 12, range =(0, 5))
ax.set_xlabel('Zoom',size='x-small' )
ax.set_ylabel('Occurance',size='x-small' )
ax.grid(True)
ax.set_xlim(0,5)
plt.title('Zoom (Fluoro)')
except:
True
try:
ax = fig.add_subplot(4,6,24)
ax.hist(zoom_A, 12, range =(0, 5))
ax.set_xlabel('Zoom',size='x-small' )
ax.set_ylabel('Occurance',size='x-small' )
ax.grid(True)
ax.set_xlim(0,5)
plt.title('Zoom (Acquisition)')
except:
True
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
ramPlot = cStringIO.StringIO()
fig.savefig(ramPlot, format='png')
#ramPlot.read()
ramPlot.seek( 0 ) #rewind data
img=Image.open( ramPlot )
im=np.asarray(img)
ramPlot.close()
fig1 = plt.figure(figsize=(14,19))
canvas=FigureCanvasPdf(fig1)
fig1.figimage(im, 0, -530, zorder = 1)
pdf.savefig(fig1, dpi=100)
del fig1
del fig
#
# # page 2
fig = plt.figure(figsize=(14,19))
#Voltage histogram
ax = fig.add_subplot(6, 2, 1)
if len (voltage_F)>0:
ax.hist(voltage_F, 50, range = (50, 130))
ax.set_xlabel('Voltage (Fluoro) [kV]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
#plt.title('Fluoro')
plt.title("Fluoro [mean kV, SD kV]={0}".format( [ round(numpy.mean(voltage_F)), round(numpy.std(voltage_F)) ]))
ax = fig.add_subplot(6, 2, 2)
if len (voltage_A)>0:
ax.hist(voltage_A, 50, range = (50, 130))
ax.set_xlabel('Voltage (Acq) [kV]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
#plt.title('Acquisition')
plt.title("Acquisition [mean kV, SD kV]={0}".format( [ round(numpy.mean(voltage_A)), round(numpy.std(voltage_A)) ]))
#Current histogram
ax = fig.add_subplot(6, 2, 3)
if len(current_F)>0:
ax.hist(current_F, 50, range = (0, 250))
ax.set_xlabel('Current (Fluoro) [mA]',size='x-small')
ax.set_ylabel('Occurance /#',size='x-small' )
ax.grid(True)
#plt.title('Current (Fluoro)')
ax = fig.add_subplot(6, 2, 4)
if len (current_A)>0:
ax.hist(current_A, 50, range = (0, 1000))
ax.set_xlabel('Current (Acq) [mA]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.grid(True)
#plt.title('Current (Acquisition)')
#Watervalue-voltage Fluoro
ax = fig.add_subplot(6,2,5)
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('F'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('F'))] , '.', color='b', label='F1')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('F'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('F'))] , '.', color='r', label='F2')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))] , '.', color='g', label='FG')
ax.set_xlabel(r'Watervalue (fluoro) /[mm]', size='x-small')
ax.set_ylabel(r'Voltage /[kV]', size='x-small')
ax.set_xlim(0,450)
ax.set_ylim(40,125)
ax.legend(loc=4, numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
#plt.title('Watervalue - voltage (Fluoro)')
#Watervalue-voltage Acq
ax = fig.add_subplot(6,2,6)
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))] , '.', color='b', label='F1')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))] , '.', color='r', label='F2')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.voltage[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))] , '.', color='g', label='FG')
ax.set_xlabel(r'Watervalue (Acq) /[mm]', size='x-small')
ax.set_ylabel(r'Voltage /[kV]', size='x-small')
ax.set_xlim(0,450)
ax.set_ylim(40,125)
ax.legend(loc=4, numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
#plt.title(r'Watervalue - voltage (Acquisition)',size='small')
#Watervalue-current Fluoro
ax = fig.add_subplot(6,2,7)
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('F'))], self.myXEvent.current[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('F'))] , '.', color='b', label='F1')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('F'))], self.myXEvent.current[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('F'))] , '.', color='r', label='F2')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))], self.myXEvent.current[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('F'))] , '.', color='g', label='FG')
ax.set_xlabel(r'Watervalue (Fluoro) /[mm]', size='x-small')
ax.set_ylabel(r'Current /[mA]', size='x-small')
ax.set_xlim(0,450)
ax.legend(loc=4, numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
#plt.title('Watervalue - current (Fluoro)')
#Watervalue-current Acq
ax = fig.add_subplot(6,2,8)
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.current[(self.myXEvent.focus==ord('S'))*(self.myXEvent.mode==ord('A'))] , '.', color='b', label='F1')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.current[(self.myXEvent.focus==ord('L'))*(self.myXEvent.mode==ord('A'))] , '.', color='r', label='F2')
ax.plot(self.myXEvent.was[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))], self.myXEvent.current[(self.myXEvent.focus==ord('M'))*(self.myXEvent.mode==ord('A'))] , '.', color='g', label='FG')
ax.set_xlabel(r'Watervalue (Acq) /[mm]', size='x-small')
ax.set_ylabel(r'Current /[mA]', size='x-small')
ax.set_xlim(0,450)
ax.legend(loc=4, numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
#plt.title(r'Watervalue - current (Acquisition)',size='small')
#Cu-filter histogram
ax = fig.add_subplot(6, 2, 9)
if len(filter_F)>0:
ax.hist(filter_F, 10, range = (0, 10))
ax.set_xlabel('Cu-filter (Fluoro) [1/10 mm]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
ax.set_autoscale_on(False)
xlim([0,10])
#plt.title('Cu-filter (Fluoro)')
ax = fig.add_subplot(6, 2, 10)
if len(filter_A)>0:
ax.hist(filter_A, 10, range = (0, 10))
ax.set_xlabel('Cu-filter (Acq) [1/10 mm]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
ax.set_autoscale_on(False)
xlim([0,10])
#plt.title('Cu-filter (Acquisition)')
xtime_F = numpy.array([])
xtime_A = numpy.array([])
for i in xrange(len(xtime)):
if modus[i] == ord('F'):
xtime_F = numpy.append(xtime_F, xtime[i])
elif modus[i] == ord('A'):
xtime_A = numpy.append(xtime_A, xtime[i])
else:
pass
#print "keine Zuodnung: " + str(modus[i]) + " - " + str(xtime[i])
#Pulse-duration histogram
ax = fig.add_subplot(6, 2, 11)
if len(xtime_F)>0:
ax.hist(list(xtime_F)+[-1], 50)
ax.set_xlabel('Pulse-duration (fluoro) [ms]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
xlim([0,max(xtime_F)])
ax.grid(True)
#plt.title('Pulse-duration')
ax = fig.add_subplot(6, 2, 12)
if len(xtime_A)>0:
ax.hist(list(xtime_A)+[-1], 50)
ax.set_xlabel('Pulse-duration (Acq) [ms]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
xlim([0,max(xtime_A)])
ax.grid(True)
#plt.title('Pulse-duration')
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
ramPlot = cStringIO.StringIO()
fig.savefig(ramPlot, format='png')
#ramPlot.read()
ramPlot.seek( 0 ) #rewind data
img=Image.open( ramPlot )
im=np.asarray(img)
ramPlot.close()
fig1 = plt.figure(figsize=(14,19))
canvas=FigureCanvasPdf(fig1)
fig1.figimage(im, 0, -530, zorder = 1)
pdf.savefig(fig1, dpi=100)
del fig1
del fig
# page 3
fig = plt.figure(figsize=(14,19))
#system dose histogram /maxed out
ende=self.events
#Histogramm used system doses
ax = fig.add_subplot(6, 2, 1)
try:
tempstr='FL - used system dose, range = 0..100 #FL <20nGy: ' +str((self.myXEvent.mode[:ende]==ord('F')*(self.myXEvent.system_dose[:ende]<=20)).sum())
ax.hist( (self.myXEvent.mode[:ende]==ord('F')) *self.myXEvent.system_dose[:ende], 50, range = (1, 100),label=tempstr)
ax.set_xlabel('System Dose (Fluoro) [nGy]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
ax.set_autoscale_on(False)
xlim([1,100])
except:
True
ax = fig.add_subplot(6, 2, 2)
try:
tempstr='ACQ - used system dose, range = max #ACQ <70nGy: ' +str((self.myXEvent.mode[:ende]==ord('A')*(self.myXEvent.system_dose[:ende]<=70)).sum())
ax.hist( (self.myXEvent.mode[:ende]==ord('A')) *self.myXEvent.system_dose[:ende], 50, range = (1, self.myXEvent.system_dose.max()),label=tempstr)
ax.set_xlabel('System Dose (Acq) [nGy]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.legend(loc=9)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
ax.set_autoscale_on(False)
xlim([1, max(3600,self.myXEvent.system_dose.max())])
except:
True
ax = fig.add_subplot(6, 2, 3)
try:
tempstr='FL - used system dose, range = 0..45 #FL <20nGy: ' +str((self.myXEvent.mode[:ende]==ord('F')*(self.myXEvent.system_dose[:ende]<=20)).sum())
ax.hist( (self.myXEvent.mode[:ende]==ord('F')) *self.myXEvent.system_dose[:ende], 50, range = (1, 45),label=tempstr)
ax.set_xlabel('System Dose (Fluoro) [nGy]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
ax.set_autoscale_on(False)
xlim([1, 45])
except:
True
ax = fig.add_subplot(6, 2, 4)
try:
tempstr='ACQ - used system dose, range = 0..300 #ACQ <70nGy: ' +str((self.myXEvent.mode[:ende]==ord('A')*(self.myXEvent.system_dose[:ende]<=70)).sum())
ax.hist( (self.myXEvent.mode[:ende]==ord('A')) *self.myXEvent.system_dose[:ende], 50, range = (1, 300),label=tempstr)
ax.set_xlabel('System Dose (Acq) [nGy]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.legend(loc=9)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
ax.set_autoscale_on(False)
xlim([1, 300])
except:
True
#Histogramm Gamma
ax = fig.add_subplot(6, 2, 5)
try:
temp_gamma_F1=(self.myXEvent.mode[:ende]==ord('F'))*self.myXEvent.gamma[:ende]*(self.myXEvent.focus[:ende]==ord('S'))
temp_gamma_F1=np.delete(temp_gamma_F1,np.where(temp_gamma_F1==0))
temp_gamma_F2=(self.myXEvent.mode[:ende]==ord('F'))*self.myXEvent.gamma[:ende]*(self.myXEvent.focus[:ende]==ord('L'))
temp_gamma_F2=np.delete(temp_gamma_F1,np.where(temp_gamma_F2==0))
temp_gamma_FG=(self.myXEvent.mode[:ende]==ord('F'))*self.myXEvent.gamma[:ende]*(self.myXEvent.focus[:ende]==ord('M'))
temp_gamma_FG=np.delete(temp_gamma_FG,np.where(temp_gamma_FG==0))
temp_gamma=np.concatenate((temp_gamma_F1,temp_gamma_F2,temp_gamma_FG))
tempstr='[mean,sd]=%4.2f,%4.2f'%(temp_gamma_F1.mean(),temp_gamma.std())
ax.hist( [temp_gamma_F1,temp_gamma_F2,temp_gamma_FG], 50, range = (0.5, 2),stacked='true',label=['SF','LF',u'µF'])
ax.set_xlabel('Gamma (Fluoro) '+tempstr,size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
except:
True
ax = fig.add_subplot(6, 2, 6)
try:
temp_gamma_F1=(self.myXEvent.mode[:ende]==ord('A'))*self.myXEvent.gamma[:ende]*(self.myXEvent.focus[:ende]==ord('S'))
temp_gamma_F1=np.delete(temp_gamma_F1,np.where(temp_gamma_F1==0))
temp_gamma_F2=(self.myXEvent.mode[:ende]==ord('A'))*self.myXEvent.gamma[:ende]*(self.myXEvent.focus[:ende]==ord('L'))
temp_gamma_F2=np.delete(temp_gamma_F2,np.where(temp_gamma_F2==0))
temp_gamma_FG=(self.myXEvent.mode[:ende]==ord('A'))*self.myXEvent.gamma[:ende]*(self.myXEvent.focus[:ende]==ord('M'))
temp_gamma_FG=np.delete(temp_gamma_FG,np.where(temp_gamma_FG==0))
temp_gamma=np.concatenate((temp_gamma_F1,temp_gamma_F2,temp_gamma_FG))
tempstr='[mean,sd]=%4.1f,%4.1f'%(temp_gamma.mean(),temp_gamma.std())
ax.hist( [temp_gamma_F1,temp_gamma_F2,temp_gamma_FG], 50, range = (0.5, 2),stacked='true',label=['SF','LF',u'µF'])
ax.set_xlabel('Gamma (Acq) '+tempstr,size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.grid(True)
except:
True
#Histogramm Pulse-duration FL and ACQ
ax = fig.add_subplot(6,2,7)
fps_bins=[0.5,1.0,1.88,3.0,3.75,5.0,6.0,7.5,10.0,15.0,30.0,60.0,61.0]
width=0.2
fps_bin_label=[str(a) for a in fps_bins[:-1]]
try:
data=(self.myXEvent.mode[:ende]==ord('F')) *self.myXEvent.frequency[:ende]
data=data[data!=0]
haufigkeit,ind=np.histogram(data,bins=fps_bins)
x=np.arange(len(ind)-1)
ax.bar(x, haufigkeit, width)
ax.set_xlabel('Pulse rate (Fluoro) / [fps]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
#ax.set_xlim(-1, (len(ind)))
plt.xticks(x+width/2, fps_bin_label)
ax.grid(True)
#plt.title('FL - fps')
except:
True
ax = fig.add_subplot(6,2,8)
try:
data=(self.myXEvent.mode[:ende]==ord('A')) *self.myXEvent.frequency[:ende]
data=data[data!=0]
haufigkeit,ind=np.histogram(data,bins=fps_bins)
x=np.arange(len(ind)-1)
ax.bar(x, haufigkeit, width)
ax.set_xlabel('Pulse rate (Acq) / [fps]',size='x-small')
ax.set_ylabel('Occurance #',size='x-small' )
#ax.set_xlim(-1, (len(ind)))
plt.xticks(x+width/2, fps_bin_label)
ax.grid(True)
#plt.title('ACQ - fps')
except:
True
#Pulse Power histogram
ax = fig.add_subplot(6, 2, 9)
if len (pulsepower_F)>0:
ax.hist(pulsepower_F+[-1], 50, range = (0, 100))
ax.set_xlabel('Pulse Power (Fluoro) [kW]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
#plt.title('Fluoro')
#plt.title("Pulse Power Fluoro")
ax = fig.add_subplot(6, 2, 10)
if len (pulsepower_A)>0:
ax.hist(pulsepower_A+[-1], 50, range = (0, 100))
ax.set_xlabel('Pulse Power (Acq) [kW]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
#plt.title("Pulse Power Acquisition")
#Scene time histogram
ax = fig.add_subplot(6, 2, 11)
if len (scenelength_F)>0:
ax.hist(scenelength_F+[-1], 50, range = (0, 100))
ax.set_xlabel('Scene time (Fluoro) [s]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
#ax.set_xlim(set_xlim(right=0))
ax.grid(True)
#plt.title('Fluoro')
#plt.title("Pulse Power Fluoro")
ax = fig.add_subplot(6, 2, 12)
if len (scenelength_A)>0:
ax.hist(scenelength_A+[-1], 50, range = (0, 40))
ax.set_xlabel('Scene time (Acq) [s]', size='x-small')
ax.set_ylabel('Occurance #', size='x-small')
ax.grid(True)
#plt.title("Pulse Power Acquisition")
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
ramPlot = cStringIO.StringIO()
fig.savefig(ramPlot, format='png')
#ramPlot.read()
ramPlot.seek( 0 ) #rewind data
img=Image.open( ramPlot )
im=np.asarray(img)
ramPlot.close()
fig1 = plt.figure(figsize=(14,19))
canvas=FigureCanvasPdf(fig1)
fig1.figimage(im, 0, -530, zorder = 1)
pdf.savefig(fig1, dpi=100)
del fig1
del fig
# page 4
fig = plt.figure(figsize=(14,19))
#Skindose per OGP
d = {}
d_mode={}
haufigkeit = []
bezeichnung = []
colorslist=[]
for i in range(len(SID)):
if self.myXEvent.SID[i] != 0:
ogpName = self.myXEvent.OGP[i]
d_mode[ogpName]=chr(int(self.myXEvent.mode[i]))
if d.has_key(ogpName):
d[ogpName] += self.myXEvent.skindose[i]# /1000000
else:
d[ogpName] = self.myXEvent.skindose[i] #/1000000
#print d
else:
print "ignored:" + str(i)
a = sorted(d.items(), key=itemgetter(1))
#find maximum value
max_a = 0
for i in range(len(a)):
if a[i][1] > max_a:
max_a = a[i][1]
for i in range(len(a)):
if a[i][1] > max_a/50:
if d_mode[a[i][0]]=='F':
colorslist.append('blue')
else:
colorslist.append('red')
bezeichnung.append(a[i][0])
haufigkeit.append(a[i][1])
ax = fig.add_subplot(2,1,1)
ind = np.arange(len(haufigkeit)) # the x locations for the groups
width = 0.2 # the width of the bars: can also be len(x) sequence
try:
ax.bar(ind, np.array(haufigkeit)/1000., width)
ax.set_xlabel('', size='small')
ax.set_ylabel('Skindose [mGy]', size='small')
ax.grid(True)
plt.title('Skindose per OGP', size='large')
plt.xticks(ind+width/2, bezeichnung, rotation=90)
[i.set_color(colorslist[k]) for k,i in enumerate(plt.gca().get_xticklabels())]
except:
True
#Used OGPs
haufigkeit = []
bezeichnung = []
d = {}
for i in set(self.myXEvent.OGP):
d[i] = self.myXEvent.OGP.count(i)
a = sorted(d.items(), key=itemgetter(1))
sorted_ogps=sorted(d.items(), key=itemgetter(1),reverse=True)
#find maximum value an only use used OGPs that are > 1/200 of the maximum
max_a = 0
for i in range(len(a)):
if a[i][1] > max_a:
max_a = a[i][1]
i_skipped = 0
colorslist=[]
for i in range(len(a)):
#print i
if a[i][1] > max_a / 200:
if d_mode[a[i][0]]=='F':
colorslist.append('blue')
else:
colorslist.append('red')
bezeichnung.append(a[i][0])
s = a[i][1]
for j in range(s):
haufigkeit.append(i+1 - i_skipped)
else:
i_skipped += 1
c = []
for i in range(len(bezeichnung)):
c.append(i+1)
ax = fig.add_subplot(2,1,2)
try:
ax.hist(haufigkeit, 60,orientation = 'horizontal')
ax.set_xlabel('Occurance', size='small')
#ax.set_ylabel('Occurance', size='small')
ax.grid(True)
plt.title('Used OGPs (min 0.5% usage)', size='large')
plt.yticks(c, bezeichnung, rotation=0, size='small')
[i.set_color(colorslist[k]) for k,i in enumerate(plt.gca().get_yticklabels())]
except:
True
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
ramPlot = cStringIO.StringIO()
fig.savefig(ramPlot, format='png')
#ramPlot.read()
ramPlot.seek( 0 ) #rewind data
img=Image.open( ramPlot )
im=np.asarray(img)
ramPlot.close()
fig1 = plt.figure(figsize=(14,19))
canvas=FigureCanvasPdf(fig1)
fig1.figimage(im, 0, -530, zorder = 1)
pdf.savefig(fig1, dpi=100)
del fig1
del fig
# page 5
fig = plt.figure(figsize=(14,19))
##################
#OGP timeline plot
##################
ogpDict = {}
ogpDictItems = []
ogpNumber = 1
usedOgpNumber = []
usedOgpDates = []
ogpIgnoreList = []# ['Service', 'Konstanz', 'IQAP']
dates = [dateutil.parser.parse(s) for s in TIME]
usedOgpNumber.append(0)
usedOgpDates.append(dates[0])
for i in range(len(SID)):
if self.myXEvent.SID[i] != 0:
currentOgp = self.myXEvent.OGP[i]
ignoreFlag = 0
#check empty entries
if currentOgp == "":
ignoreFlag = 1
print "Empty OGP name"
#check ignore list
for j in ogpIgnoreList:
if j in currentOgp:
ignoreFlag = 1
#count if not ignored
if ignoreFlag == 0:
if ogpDict.has_key(currentOgp):
pass
else:
ogpDict[currentOgp] = ogpNumber
ogpNumber += 1
usedOgpNumber.append(ogpDict[currentOgp])
usedOgpDates.append(dates[i])
usedOgpNumber.append(ogpNumber) # add one additional at the right top corner to make output look nicer
usedOgpDates.append(dates[-1])
# calculate the y-axis labels
for i in xrange (len(ogpDict)+1):
for key,value in ogpDict.items():
if value == i:
ogpDictItems.append (key)
# do the plot
ax = fig.add_subplot(1, 1, 1)
ax.plot(xrange(0, len(usedOgpNumber)) ,usedOgpNumber, '.')
ax.set_xlabel('Event nr.', size='small')
fig.autofmt_xdate()
ax.set_ylabel('OGP', size='small')
ax.grid(False)
plt.title('OGP timeline plot', size='large')
# create additional y-axis description (OGP names)
y_pos = 1
for myString in ogpDictItems:
y_value = y_pos + 0.1
ax.text (0.0, y_value, (myString), fontproperties=font)
y_pos +=1
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
ramPlot = cStringIO.StringIO()
fig.savefig(ramPlot, format='png')
#ramPlot.read()
ramPlot.seek( 0 ) #rewind data
img=Image.open( ramPlot )
im=np.asarray(img)
ramPlot.close()
fig1 = plt.figure(figsize=(14,19))
canvas=FigureCanvasPdf(fig1)
fig1.figimage(im, 0, -530, zorder = 1)
pdf.savefig(fig1, dpi=100)
del fig1
del fig
# page 6
fig = plt.figure(figsize=(14,19))
# do the plot
ax = fig.add_subplot(1, 1, 1)
if len(usedOgpDates) == len(usedOgpNumber):
ax.plot_date(pylab.date2num(usedOgpDates), usedOgpNumber, linestyle='.', xdate=True)
#ax.set_axis_off()
# Set major x ticks on Mondays.
#ax.xaxis.set_major_locator(matplotlib.dates.WeekdayLocator(byweekday=matplotlib.dates.MO))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%b.%Y\n%H:%M'))
else:
ax.plot(xrange(0, len(usedOgpNumber)) ,usedOgpNumber, '.')
print len(usedOgpDates)
print len(usedOgpNumber)
ax.set_xlabel('Event', size='small')
fig.autofmt_xdate()
ax.set_ylabel('OGP', size='small')
ax.grid(True)
plt.title('OGP timeline plot', size='large')
# create additional y-axis description (OGP names)
y_pos = 1
for myString in ogpDictItems:
y_value = y_pos + 0.1
ax.text (pylab.date2num(usedOgpDates[0]), y_value, (myString), fontproperties=font)
y_pos +=1
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
pdf.savefig(fig)
close()
#save top 3 examsets
if self.cb_examsets.GetValue()==False or self.success_examsets==False:
pdf.close()
else:
ACQ_top3=[]
FL_top3=[]
RM_top3=[]
ALT_top3=[]
for ogp in sorted_ogps:
if ogp[0] in self.ACQ_set.keys() and len(ACQ_top3)<3:
ACQ_top3.append(ogp[0])
if ogp[0] in self.FL_set.keys() and len(FL_top3)<3:
FL_top3.append(ogp[0])
if ogp[0] in self.RM_set.keys() and len(RM_top3)<3:
RM_top3.append(ogp[0])
if ogp[0] in self.ALT_set.keys() and len(ALT_top3)<3:
ALT_top3.append(ogp[0])
try:
exam_str='ACQUISITION\n#########################################\n'
for ogp in ACQ_top3:
exam_str+=ogp+' (%2.2f'%(100.*self.myXEvent.OGP.count(ogp)/float(self.events))+'%)\n-----\n'
for param in self.acq_params:
#print str(param.replace(u'\u00b5','M'))+';'+(ACQ_set[ogp][param]).replace(u'\u00b5','M')
exam_str+=str(param.replace(u'\u00b5','M'))+';'+(self.ACQ_set[ogp][param]).replace(u'\u00b5','M')+'\n'
exam_str+='\n-----------------------------------------\n\n'
except:
print 'Problem ACQ!'
try:
exam_str+='FLUORO\n#########################################\n'
for ogp in FL_top3:
exam_str+=ogp+' (%2.2f'%(100.*self.myXEvent.OGP.count(ogp)/float(self.events))+'%)\n-----\n'
for param in self.fl_params:
exam_str+=str(param.replace(u'\u00b5','M'))+';'+(self.FL_set[ogp][param]).replace(u'\u00b5','M')+'\n'
exam_str+='\n-----------------------------------------\n\n'
except:
print 'Problem FL!'
True
try:
exam_str+='ROADMAP\n#########################################\n'
for ogp in RM_top3:
exam_str+=ogp+' (%2.2f'%(100.*self.myXEvent.OGP.count(ogp)/float(self.events))+'%)\n-----\n'
for param in self.rm_params:
exam_str+=str(param.replace(u'\u00b5','M'))+';'+(self.RM_set[ogp][param]).replace(u'\u00b5','M')+'\n'
exam_str+='\n-----------------------------------------\n\n'
except:
print 'Problem RM!'
True
try:
exam_str+='AltAcq\n#########################################\n'
for ogp in ALT_top3:
exam_str+=ogp+' (%2.2f'%(100.*self.myXEvent.OGP.count(ogp)/float(self.events))+'%)\n-----\n'
for param in self.alt_params:
exam_str+=str(param.replace(u'\u00b5','M'))+';'+(self.ALT_set[ogp][param]).replace(u'\u00b5','M')+'\n'
exam_str+='\n-----------------------------------------\n\n'
except:
print 'Problem AltAcq!'
True
#print "exam_str:\n"+exam_str
outputfile=os.path.join(self.resultsDirSN,'Artis-' + str(self.myXEvent.SN) +'_' + fromDate +'_'+ toDate+ '_plane_' +str(self.plane)+'_top_exam_sets.csv')
fp = open(outputfile, "w")
try:
fp.write(exam_str)
except:
exam_str=exam_str.encode('utf-8')
fp.write(exam_str)
fp.close()
fig = plt.figure(figsize=(14,19))
#ax = fig.add_subplot(1, 1, 1)
txtstr=u"OGP abnormalities\n(same OGP name with different content)\n"
txtstr+='=================\n'
for elem in self.ogp_diff:
txtstr+=unicode(elem)+'\n'
txtstr+='\n'
fig.text(0.7, 0.1, txtstr,fontsize=8)
txtstr=u"deleted OGPs\n"
txtstr+='=================\n'
for elem in sorted(self.ogp_del):
if self.ogp_new[elem]!=[]:
txtstr+='\n'+str(elem)+':\n\n'
for x in self.ogp_del[elem]:
txtstr+=unicode(x)+'\n'
txtstr+='\n'
fig.text(0.3, 0.1, txtstr,fontsize=8)
txtstr=u"new OGPs\n"
txtstr+='=================\n'
for elem in sorted(self.ogp_new):
if self.ogp_new[elem]!=[]:
txtstr+='\n'+str(elem)+':\n\n'
for x in self.ogp_new[elem]:
txtstr+=unicode(x)+'\n'
txtstr+='\n'
fig.text(0.1, 0.1, txtstr,fontsize=8)
txtstr=u"changed OGPs\n"
txtstr+='=================\n'
for elem,mode in sorted(self.ogp_change):
if self.ogp_change[elem,mode]!=[]:
txtstr+='\n'+str(elem)+' ('+str(mode)+'):\n\n'
for diffs in self.ogp_change[elem,mode]:
print diffs[0]
#txtstr+= diffs[0].encode('utf8', 'replace')+':\n'
txtstr+= unicode(diffs[0])+':\n'
for fff in diffs[1]:
txtstr+=' '+unicode(fff[0])+':'+ unicode(fff[1])+ '->' +unicode(fff[2])+ '\n'
txtstr+='\n'
fig.text(0.5, 0.1, txtstr,fontsize=8)
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
ramPlot = cStringIO.StringIO()
fig.savefig(ramPlot, format='png')
#ramPlot.read()
ramPlot.seek( 0 ) #rewind data
img=Image.open( ramPlot )
im=np.asarray(img)
ramPlot.close()
fig1 = plt.figure(figsize=(14,19))
canvas=FigureCanvasPdf(fig1)
fig1.figimage(im, 0, -530, zorder = 1)
pdf.savefig(fig1, dpi=100)
del fig1
del fig
pdf.close()
print 'Finished Cons report'
#-------------------------------------------------------------
#generate studyreport
# filename='XA'+str(self.myXEvent.SN)+'_study_report_plane_'+self.plane+'.csv'
filename = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate +'_plane_'+str(self.plane)+'_studies.csv')
outputfile=os.path.join(self.resultsDirSN, filename)
fw = open(outputfile, "w")
#first line
datastr='study'
datastr+=', Start time'
datastr+=', End time'
datastr+=', Duration / [min]'
datastr+=', Skindose F/ [mGy]'
datastr+=', Skindose A/ [mGy]'
datastr+=', Skindose Tot/ [mGy]'
datastr+=', Fluoro time / [min]'
datastr+=', #Fluoro'
datastr+=', #Fluoro Biplane'
datastr+=', #Acq'
datastr+=', #Acq Biplane'
datastr+=', DAP Fluoro/ [uGy*m*m]'
datastr+=', DAP Acq / [uGy*m*m]'
datastr+=', DAP Total/ [uGy*m*m]'
datastr+=', mean WV /[mm]'
datastr+=', max WV /[mm]'
datastr+=', mean sys dose F/[nGy]'
datastr+=', mean sys dose A/[nGy]'
datastr+=', mean freq Fluoro/[Hz]'
datastr+=', mean freq Acq/[Hz]'
datastr+=', mean Zoom'
datastr+=', max Zoom'
datastr+=', min Zoom'
datastr+=', mean SID'
datastr+=', max SID'
datastr+=', min SID'
datastr+=', mean scene time Fluoro'
datastr+=', mean scene time Acq'
datastr+=', # Fluoro<20nGy'
datastr+=', mean Gamma'
#datastr+=', # 3D'
datastr+=', # Lat<-10 Cran>10'
datastr+=', # Lat<-10 Cran<10>-10'
datastr+=', # Lat<-10 Cran<-10'
datastr+=', # Lat>-10<10 Cran>10'
datastr+=', # Lat>-10<10 Cran<10>-10'
datastr+=', # Lat>-10<10 Cran<-10'
datastr+=', # Lat>10 Cran>10'
datastr+=', # Lat>10 Cran<10>-10'
datastr+=', # Lat>10 Cran<-10'
datastr+=', # CARD'
datastr+=', # DR'
datastr+=', # DSA'
datastr+=', # FLUORO'
datastr+=', # RDMP'
datastr+=', # 3D_DR'
datastr+=', # 3D_DSA'
datastr+=', # 3D_CARD'
datastr+=', # 3D_DRLV'
datastr+=', # 3D_DRLF'
datastr+=', # 3D_CORO'
datastr+=', # DYNA'
datastr+=', # DRDYNA'
datastr+=', # PERI'
datastr+=', # DRSTEP'
datastr+=', # unknown'
datastr+='\n'
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
datastr=datastr.replace(',',';')
fw.write(datastr)
datastr=''
_F=np.where(self.myXEvent.mode==ord('F'))
BP=np.where(self.myXEvent.biplane>0.)
#is_3D=np.array([1 if x!='no3d' else 0 for x in self.myXEvent._3Dmode])
for study in range(0, int(num_studies)):
datastr = '%d' % (study+1)
study_idxs=range(self.myXEvent.pat_idx[study],self.myXEvent.pat_idx[study+1])
study_idxs_F=list(set.intersection(set(study_idxs),set(_F[0]))) #indices of Fluoro events in current study
study_idxs_A=list(set(study_idxs).difference(set(study_idxs_F))) #indices of Acq events in current stud
tot_num=float(len(study_idxs))
study_idxs_F_BP=list(set.intersection(set(study_idxs_F),set(BP[0])))
study_idxs_A_BP=list(set.intersection(set(study_idxs_A),set(BP[0]))) #Biplane
exp_type={}
exp_type['CARD']=0
exp_type['DR']=0
exp_type['DSA']=0
exp_type['RDMP']=0
exp_type['FLUORO']=0
exp_type['3D-DR']=0
exp_type['3D-DSA']=0
exp_type['3D-CARD']=0
exp_type['3D-DRLV']=0
exp_type['3D-DRLF']=0
exp_type['3D-CORO']=0
exp_type['DYNA']=0
exp_type['DRDYNA']=0
exp_type['PERI']=0
exp_type['DRSTEP']=0
exp_type['unknown']=0
for i in study_idxs:
try:
if self.myXEvent.OGP[i] in self.ACQ_set.keys():
exp_type[self.ACQ_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
elif self.myXEvent.OGP[i] in self.FL_set.keys():
exp_type[self.FL_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
elif self.myXEvent.OGP[i] in self.RM_set.keys():
exp_type[self.RM_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
elif self.myXEvent.OGP[i] in self.ALT_set.keys():
exp_type[self.ALT_set[self.myXEvent.OGP[i]]['E X P O S U R E']]+=1
else: #could happen if OGP is deleted,...
best_matches_acq=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.ACQ_ogps))
best_matches_fl=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.FL_ogps))
best_matches_rm=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.RM_ogps))
best_matches_alt=difflib.get_close_matches(self.myXEvent.OGP[i],list(self.ALT_ogps))
found=False
if len(best_matches_acq)>0 and not found:
for ogp in best_matches_acq:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.ACQ_set[ogp]['E X P O S U R E']]+=1
found=True
if len(best_matches_fl)>0 and not found:
for ogp in best_matches_fl:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.FL_set[ogp]['E X P O S U R E']]+=1
found=True
if len(best_matches_rm)>0 and not found:
for ogp in best_matches_rm:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.RM_set[ogp]['E X P O S U R E']]+=1
found=True
if len(best_matches_alt)>0 and not found:
for ogp in best_matches_rm:
if ogp.replace(u'\xb5','_')==self.myXEvent.OGP[i]:
exp_type[self.ALT_set[ogp]['E X P O S U R E']]+=1
found=True
if not found:
exp_type['unknown']+=1
except:
exp_type['unknown']+=1 #might happen if the Examset file in Ziplog is missing or corrupt; or IQAP, DEX OGPs
try:
datastr+= ',%s' % time.ctime(self.myXEvent.pat_in_time[study])
datastr+= ',%s' % time.ctime(self.myXEvent.pat_out_time[study])
datastr+= ',%d' % int16(self.myXEvent.pat_time[study]) #in min
datastr+= ',%5.2f' % (self.myXEvent.skindose[study_idxs_F].sum()/1000.)
datastr+= ',%5.2f' % (self.myXEvent.skindose[study_idxs_A].sum()/1000.)
datastr+= ',%5.2f' % (self.myXEvent.skindose[study_idxs].sum()/1000.)
datastr+= ',%5.2f' % (self.myXEvent.scenelength[study_idxs_F].sum()/60./1000.) #min
datastr+= ',%d' % (len(study_idxs_F))
datastr+= ',%d' % (len(study_idxs_F_BP))
datastr+= ',%d' % (len(study_idxs_A))
datastr+= ',%d' % (len(study_idxs_A_BP))
datastr+= ',%5.2f' % (self.myXEvent.DAP[study_idxs_F].sum()/100.)
datastr+= ',%5.2f' % (self.myXEvent.DAP[study_idxs_A].sum()/100.)
datastr+= ',%5.2f' % (self.myXEvent.DAP[study_idxs].sum()/100.)
datastr+= ',%5.2f' % (self.myXEvent.was[study_idxs].mean())
datastr+= ',%5.2f' % (self.myXEvent.was[study_idxs].max())
datastr+= ',%5.2f' % (self.myXEvent.system_dose[study_idxs_F].mean())
datastr+= ',%5.2f' % (self.myXEvent.system_dose[study_idxs_A].mean())
datastr+= ',%5.2f' % (self.myXEvent.frequency[study_idxs_F].mean())
datastr+= ',%5.2f' % (self.myXEvent.frequency[study_idxs_A].mean())
datastr+= ',%5.2f' % (self.myXEvent.zoom[study_idxs].mean())
datastr+= ',%5.2f' % (self.myXEvent.zoom[study_idxs].max())
datastr+= ',%5.2f' % (self.myXEvent.zoom[study_idxs].min())
datastr+= ',%5.2f' % (self.myXEvent.SID[study_idxs].mean())
datastr+= ',%5.2f' % (self.myXEvent.SID[study_idxs].max())
datastr+= ',%5.2f' % (self.myXEvent.SID[study_idxs].min())
datastr+= ',%5.2f' % (self.myXEvent.scenelength[study_idxs_F].mean())
datastr+= ',%5.2f' % (self.myXEvent.scenelength[study_idxs_A].mean())
datastr+= ',%5.2f' % ((self.myXEvent.system_dose[study_idxs_F]<20).sum())
datastr+= ',%5.2f' % (self.myXEvent.gamma[study_idxs].mean())
#datastr+= ',%5.2f' % (is_3D[study_idxs].sum())
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]<-10.)*(self.myXEvent.cran[study_idxs]>10.)).sum()/tot_num) # Lat<-10 Cran>10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]<-10.)*(self.myXEvent.cran[study_idxs]>-10.)*(self.myXEvent.cran[study_idxs]<=10.)).sum()/tot_num) # Lat<-10 Cran<10>-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]<-10.)*(self.myXEvent.cran[study_idxs]<=-10.)).sum()/tot_num) # Lat<-10 Cran<-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]>=-10.)*(self.myXEvent.rao[study_idxs]<10.)*(self.myXEvent.cran[study_idxs]>10.)).sum()/tot_num) # Lat>-10<10 Cran>10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]>=-10.)*(self.myXEvent.rao[study_idxs]<10.)*(self.myXEvent.cran[study_idxs]>-10.)*(self.myXEvent.cran[study_idxs]<=10.)).sum()/tot_num) # Lat>-10<10 Cran<10>-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]>=-10.)*(self.myXEvent.rao[study_idxs]<10.)*(self.myXEvent.cran[study_idxs]<=-10.)).sum()/tot_num) # Lat>-10<10 Cran<-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]>=10.)*(self.myXEvent.cran[study_idxs]>10.)).sum()/tot_num) # Lat>10 Cran>10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]>=10.)*(self.myXEvent.cran[study_idxs]>-10.)*(self.myXEvent.cran[study_idxs]<=10.)).sum()/tot_num) # Lat>10 Cran<10>-10'
datastr+= ',%5.2f' % (((self.myXEvent.rao[study_idxs]>=10.)*(self.myXEvent.cran[study_idxs]<=-10.)).sum()/tot_num) # Lat>10 Cran<-10
datastr+= ',%d' %(exp_type['CARD'])
datastr+= ',%d' %(exp_type['DR'])
datastr+= ',%d' %(exp_type['DSA'])
datastr+= ',%d' %(exp_type['FLUORO'])
datastr+= ',%d' %(exp_type['RDMP'])
datastr+= ',%d' %(exp_type['3D-DR'])
datastr+= ',%d' %(exp_type['3D-DSA'])
datastr+= ',%d' %(exp_type['3D-CARD'])
datastr+= ',%d' %(exp_type['3D-DRLV'])
datastr+= ',%d' %(exp_type['3D-DRLF'])
datastr+= ',%d' %(exp_type['3D-CORO'])
datastr+= ',%d' %(exp_type['DYNA'])
datastr+= ',%d' %(exp_type['DRDYNA'])
datastr+= ',%d' %(exp_type['PERI'])
datastr+= ',%d' %(exp_type['DRSTEP'])
datastr+= ',%d' %(exp_type['unknown'])
datastr+= '\n'
#SID, angulation with secors, RM,DSA,DR,
if self.cb_CSVstyle.GetValue(): #semikolon als Trenner, Komma anstatt Dezimalpunkt
datastr=datastr.replace(',',';').replace('.',',')
fw.write(datastr) #'%d,%s,%s,%d,%5.2f,%5.2f,%5.2f,%5.2f,%d,%5.2f,%5.2f,%5.2f\n',,studies_skindose(i,2)/1000.,(studies_skindose(i,1)+studies_skindose(i,2))/1000.,FL_time(i)/60,ACQ_sum(i),studies_doseareaprod(i,1)/100,studies_doseareaprod(i,2)/100.,(studies_doseareaprod(i,1)+studies_doseareaprod(i,2))/100);
except:
pass
fw.close()
if tab==0 or (tab==3 and len(self.SNzips.keys())==1) and IcConsMode==1:
if self.os_type.find('linux')==-1:
1
#os.system("start " + name)
print "Fertig!"
#part24 Averaged Power
if self.cb24.GetValue() or self.cb0.GetValue():
fig = plt.figure(figsize=(14,19))
#ax = plt.subplotgrid((3,1),(0,0),rowspan=2)
#bx = plt.subplotgrid((3,1),(1,0),rowspan=1)
#correct dates
for i in range(self.events-1,0,-1):
if event_dates[i]<event_dates[i-1]:
event_dates[i-1]=event_dates[i-1].replace(day=event_dates[i].day)
sim_time=[]
starttime=event_dates[0]-datetime.timedelta(0,0,0,0,30,0) #init 60min earlier
endtime =event_dates[self.events-1]+datetime.timedelta(0,0,0,0,30,0) #end 60min alter
delta_t= 60. #60s
difftime=endtime-starttime
num_entries=int((difftime.seconds+difftime.days*86400.)/delta_t)
energy_input=numpy.zeros(num_entries) #minute base
energy_input_peak=numpy.zeros(num_entries)
target_input=numpy.zeros(num_entries)
scene_length=numpy.zeros(num_entries)
actual_index=0
num_time_intervalls=energy_input.__len__()
input_time=event_dates[0]
sim_time.append(starttime)
E_count=0
allEvents=0
###Danger!!!! Do no edit (default 1.0)
pow_fact=1.0 #Megalix2Gigalix power increase - for worst case estimation set to 1.3
###Danger!!!! Do not edit
#1. Schritt: Aufteilung der Schussenergie auf den Zeitbereich
illegal_timeseries=False
for tt in range(1,num_time_intervalls):
sim_time.append(sim_time[-1]+datetime.timedelta(0,0,0,0,1,0))
energy_input[tt]=0
while(sim_time[tt]>=input_time and actual_index<self.events):
energy=self.myXEvent.current[actual_index]*self.myXEvent.voltage[actual_index]*self.myXEvent.time[actual_index]*self.myXEvent.frames[actual_index] #mJ
actual_scene_length=self.myXEvent.scenelength[actual_index]/1000. #sec
scene_length[tt]=actual_scene_length
#Umverteilung
num_bins=int(ceil(actual_scene_length/delta_t))
energy_per_bin=energy/num_bins
energy_input_peak[tt]+=energy
for s in range(0,num_bins):
energy_input[tt-s]+=energy_per_bin
actual_index=actual_index+1
#print actual_index
if actual_index==self.events:
break
if event_dates[actual_index-1]>event_dates[actual_index]:
illegal_timeseries=True
print "illegal time step!"
break
input_time=event_dates[actual_index]
energy_input=energy_input*pow_fact
#calculation of mean powera
mean_power_5= numpy.convolve(energy_input,numpy.ones(5)/5.,'same')/delta_t/1000./1000.
mean_power_10= numpy.convolve(energy_input,numpy.ones(10)/10.,'same')/delta_t/1000./1000. #mittlere Leistung über 10 min in kW
mean_power_20= numpy.convolve(energy_input,numpy.ones(20)/20.,'same')/delta_t/1000./1000.
mean_power_30= numpy.convolve(energy_input,numpy.ones(30)/30.,'same')/delta_t/1000./1000.
ax = fig.add_subplot(2,1,1)
#ax.plot_date(pylab.date2num(sim_time),energy_input/60./1000./1000. , marker='', linestyle='-',color='black', label=' 1min')
ax.plot_date(pylab.date2num(sim_time),mean_power_10, marker='', linestyle='-',color='red', label='10min')
ax.plot_date(pylab.date2num(sim_time),mean_power_20, marker='', linestyle='-',color='green', label='20min')
ax.plot_date(pylab.date2num(sim_time),mean_power_30, marker='', linestyle='-',color='blue', label='30min')
ax.set_ylabel('Averaged tube power /[kW]', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.grid(True)
ax.legend()
plt.title('Tube power averaged on various time scales (EXPERIMENTAL!) w/o driving power')
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#labels = ax.get_yticklabels()
#setp(labels, rotation=0, fontsize=8)
#-------------------
bx = fig.add_subplot(2,1,2)
z=numpy.zeros((num_entries,3))
z[:,0]=mean_power_10
z[:,1]=mean_power_20
z[:,2]=mean_power_30
#bx.hist(mean_power_10, 20,normed=1, range=(0.001,5.0))
bx.hist(z, 20,normed=1, range=(0.001,5.0),label=['10min','20min','30min'], color=['red','green','blue'])
#bx.hist(z, 40, range=(0.001,5.0), normed=1, histtype='step', cumulative=True)
bx.set_xlim(0, 4)
bx.legend()
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
bx.set_xlabel('Averaged tube power /[kW]', size='x-small')
bx.set_ylabel('Rel. occurance # ', size='x-small')
#ax.hist(mean_power_20, 20,alpha=0.5)
#ax.set_xlabel('Occurance', size='small')
#-------------------
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part24'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(SID))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]), horizontalalignment='center', verticalalignment='center')
name = 'XA'+str(self.myXEvent.SN)+'_plane_'+str(self.plane)+'_results_24.pdf'
outputfile=os.path.join(self.resultsDirSN,name)
plt.savefig(outputfile)
plt.close()
#text output
outputfile=os.path.join(self.resultsDirSN,'tube_load_'+str(self.plane)+'.csv')
fw = open(outputfile, "w")
fw.write("Index,sim_time,scene_length,energy_input_peak,energy_input,power[kW]\n")
for i in xrange(len(energy_input)):
datastring = str(i)+','+str(sim_time[i])+','+str(scene_length[i]) + ',' + str(energy_input_peak[i]) + ',' + str(energy_input[i])+','+str(energy_input[i]/delta_t/1000./1000.)+'\n'
print datastring
fw.write(datastring)
fw.close()
datastring=''
for i in xrange(self.events):
try:
datastring =datastring+str((100.+self.myXEvent.prevHU[i])/200.*self.myXEvent.voltage[i]*self.myXEvent.current[i]/1000./self.myXEvent.maxPower_Istzeit[i]*self.myXEvent.scenelength[i]/1000.)+'\n'
except:
blubb=1
outputfile=os.path.join(self.resultsDirSN,'tube_load_2'+str(self.plane)+'.csv')
fw = open(outputfile, "w")
fw.write("factor\n")
fw.write(datastring)
fw.close()
#
return
#------------------------------------------------------------------
def calcStromDurchgriff(self, kv, mode, focus):
if(focus==ord('S')):
xrayVoltage=self.xrayVoltage['small']
maxCurrAcq=self.maxCurrAcq['small']
maxCurrFluoro=self.maxCurrFluoro['small']
if(focus==ord('L')):
xrayVoltage=self.xrayVoltage['large']
maxCurrAcq=self.maxCurrAcq['large']
maxCurrFluoro=self.maxCurrFluoro['large']
if(focus==ord('M')):
xrayVoltage=self.xrayVoltage['micro']
maxCurrAcq=self.maxCurrAcq['micro']
maxCurrFluoro=self.maxCurrFluoro['micro']
if (kv*1000 < int(xrayVoltage[0]) or kv*1000 > int(xrayVoltage[-1])):
#print "XrayVoltage out of range!"
return -1
# interpolation starting
voltalt = 0
currAcq_alt = 0
currFluoro_alt = 0
for volt, currAcq, currFluoro in zip(xrayVoltage, maxCurrAcq, maxCurrFluoro):
if int(volt) >= int(kv*1000):
break
voltalt = float(volt)
currAcq_alt = float(currAcq)
currFluoro_alt = float(currFluoro)
# just float-cast
volt = float(volt)
currAcq = float(currAcq)
currFluoro = float(currFluoro)
anzStuetz = volt - voltalt
valueACQ = (currAcq - currAcq_alt) / float(anzStuetz) * ((kv*1000) - voltalt) + currAcq_alt
valueFluoro = (currFluoro - currFluoro_alt) / float(anzStuetz) * ((kv*1000) - voltalt) + currFluoro_alt
#TODO Auswahl fuer Fluoro
if mode==ord('F'):
return valueFluoro/1000.0 # uA->mA
else :
return valueACQ/1000.0 # uA->mA
#------------------------------------------------------------------
def calcConstantLoad(self, ms, focus):
if(focus==ord('S')):
CL_kWs=self.ConstantLoad['small'] #0.1kWs
CL_ms =self.PulseDuration['small'] #0.1ms
if(focus==ord('L')):
CL_kWs=self.ConstantLoad['large'] #0.1kWs
CL_ms =self.PulseDuration['large'] #0.1ms
if(focus==ord('M')):
CL_kWs=self.ConstantLoad['micro'] #0.1kWs
CL_ms =self.PulseDuration['micro'] #0.1ms
# interpolation starting
ms_alt = 0
kWs_alt = 0
for ms_, kWs_ in zip(CL_ms, CL_kWs):
if int(ms_/10.) >= int(ms):
break
ms_alt = float(ms_/10.)
kWs_alt = float(kWs_/10.)
# just float-cast
ms_ = float(ms_/10.)
kWs_ = float(kWs_/10.)
anzStuetz = ms_ - ms_alt
ConstLoad = (kWs_-kWs_alt)/float(anzStuetz) * (ms - ms_alt) + kWs_alt
return ConstLoad/ms #kW
################################################################
def get_power_from_HU(self, HU):
Energy_content=HU/100.*1500000 #[Ws]
cooling_power= Energy_content*Energy_content * 2.49e-9 + Energy_content * 9.33e-4 #[W]
return cooling_power
#------------------------------------------------------------------
def calcStromSerie(self, X, Y, focus): #X=Dutycycle Y=Scenetime
#print X,Y,focus
if X < self.myDutyCycle[0]:
X=self.myDutyCycle[0]
if X > self.myDutyCycle[-1]:
X=self.myDutyCycle[-1]
if Y < self.mySceneTime[0]:
Y=self.mySceneTime[0]
if Y > self.mySceneTime[-1]:
Y=self.mySceneTime[-1]
#Y=int(Y)
#X=int(X)
if(focus==ord('S')):
SerialLoadTable=self.SerialLoadTable['small']
if(focus==ord('L')):
SerialLoadTable=self.SerialLoadTable['large']
if(focus==ord('M')):
SerialLoadTable=self.SerialLoadTable['micro']
################### INTERPOLATION ####################
if (SerialLoadTable[Y][X] == 0): #interpolation
x_iter_max = 0
x_iter_min = 0
y_iter_max = 0
y_iter_min = 0
# get xmin & xmax coordinates
for i in range(0, len(self.myDutyCycle)):
if (int(self.myDutyCycle[i]) >= int(X)):
x_iter_max = float(self.myDutyCycle[i])
break
x_iter_min = float(self.myDutyCycle[i])
# get ymin & ymax coordinates
for i in range(0, len(self.mySceneTime)):
if (float(self.mySceneTime[i]) >= int(Y)):
y_iter_max = float(self.mySceneTime[i])
break
y_iter_min = float(self.mySceneTime[i])
############## calculate x-interpolations (x_intx_interpol2pol1 & x2)
x_AnzStuetz = x_iter_max - x_iter_min
x_interpol1 = SerialLoadTable[y_iter_min][x_iter_max] - SerialLoadTable[y_iter_min][x_iter_min]
x_interpol1 = x_interpol1 / float(x_AnzStuetz) * (X - x_iter_min) + SerialLoadTable[y_iter_min][x_iter_min]
x_interpol2 = SerialLoadTable[y_iter_max][x_iter_max] - SerialLoadTable[y_iter_max][x_iter_min]
x_interpol2 = x_interpol2 / float(x_AnzStuetz) * (X - x_iter_min) + SerialLoadTable[y_iter_max][x_iter_min]
############## calculate y-interpolation
y_AnzStuetz = y_iter_max - y_iter_min
y_interpol = x_interpol2 - x_interpol1
y_interpol = y_interpol / float(y_AnzStuetz) * (Y - y_iter_min) + x_interpol1
#print "dutycycle: " + str(X) + " len: " + str(Y) + " value: " + str(y_interpol) + " - interpolated"
return y_interpol / 10.0
################## INTERPOLATION END #################
#print "dutycycle: " + str(X) + " len: " + str(Y) + " value: " + str(SerialLoadTable[Y][X])
return SerialLoadTable[Y][X] / 10.0
#------------------------------------------------------------------
def calcStromSerieDyn(self, X, Y, focus, cooling_pow):
#print X,Y,focus
if X < self.myDutyCycle[0]:
X=self.myDutyCycle[0]
if X > self.myDutyCycle[-1]:
X=self.myDutyCycle[-1]
if Y < self.mySceneTime[0]:
Y=self.mySceneTime[0]
if Y > self.mySceneTime[-1]:
Y=self.mySceneTime[-1]
#Y=int(Y)
#X=int(X)
if(focus==ord('S')):
SerialLoadTable=self.SerialLoadTable['small']
SerialLoadTable200=self.SerialLoadTable200['small']
if(focus==ord('L')):
SerialLoadTable=self.SerialLoadTable['large']
SerialLoadTable200=self.SerialLoadTable200['large']
if(focus==ord('M')):
SerialLoadTable=self.SerialLoadTable['micro']
SerialLoadTable200=self.SerialLoadTable200['micro']
################### INTERPOLATION ####################
if (SerialLoadTable[Y][X] == 0): #interpolation
x_iter_max = 0
x_iter_min = 0
y_iter_max = 0
y_iter_min = 0
# get xmin & xmax coordinates
for i in range(0, len(self.myDutyCycle)):
if (int(self.myDutyCycle[i]) >= int(X)):
x_iter_max = float(self.myDutyCycle[i])
break
x_iter_min = float(self.myDutyCycle[i])
# get ymin & ymax coordinates
for i in range(0, len(self.mySceneTime)):
if (float(self.mySceneTime[i]) >= int(Y)):
y_iter_max = float(self.mySceneTime[i])
break
y_iter_min = float(self.mySceneTime[i])
############## calculate x-interpolations (x_intx_interpol2pol1 & x2)
x_AnzStuetz = x_iter_max - x_iter_min
x_interpol1 = SerialLoadTable[y_iter_min][x_iter_max] - SerialLoadTable[y_iter_min][x_iter_min]
x_interpol1 = x_interpol1 / float(x_AnzStuetz) * (X - x_iter_min) + SerialLoadTable[y_iter_min][x_iter_min]
x_interpol1_200 = SerialLoadTable200[y_iter_min][x_iter_max] - SerialLoadTable200[y_iter_min][x_iter_min]
x_interpol1_200 = x_interpol1_200 / float(x_AnzStuetz) * (X - x_iter_min) + SerialLoadTable200[y_iter_min][x_iter_min]
x_interpol2 = SerialLoadTable[y_iter_max][x_iter_max] - SerialLoadTable[y_iter_max][x_iter_min]
x_interpol2 = x_interpol2 / float(x_AnzStuetz) * (X - x_iter_min) + SerialLoadTable[y_iter_max][x_iter_min]
x_interpol2_200 = SerialLoadTable200[y_iter_max][x_iter_max] - SerialLoadTable200[y_iter_max][x_iter_min]
x_interpol2_200 = x_interpol2_200 / float(x_AnzStuetz) * (X - x_iter_min) + SerialLoadTable200[y_iter_max][x_iter_min]
############## calculate y-interpolation
y_AnzStuetz = y_iter_max - y_iter_min
y_interpol = x_interpol2 - x_interpol1
y_interpol = y_interpol / float(y_AnzStuetz) * (Y - y_iter_min) + x_interpol1
y_interpol_200 = x_interpol2_200 - x_interpol1_200
y_interpol_200 = y_interpol_200 / float(y_AnzStuetz) * (Y - y_iter_min) + x_interpol1_200
#print "dutycycle: " + str(X) + " len: " + str(Y) + " value: " + str(y_interpol) + " - interpolated"
y_interpol_out=(y_interpol-y_interpol_200)/800.*(cooling_pow-200.)+y_interpol_200 #power in watt
return y_interpol_out / 10.0
################## INTERPOLATION END #################
#print "dutycycle: " + str(X) + " len: " + str(Y) + " value: " + str(SerialLoadTable[Y][X])
return ((SerialLoadTable[Y][X]-SerialLoadTable200[Y][X])/800.*(cooling_pow-200.)+SerialLoadTable200[Y][X])/ 10.0
###########################################################################
def do_part18(self):
global Startzeit
fromDate = (str(self.start__datum))[0:10].replace('/','-')
toDate = (str(self.ende__datum))[0:10].replace('/','-')
day_total = (self.ende__datum-self.start__datum).days
#part18 Arcing Analysis
if self.cb18.GetValue() or self.cb0.GetValue():
all_arcs_n=0
all_arcs_p=0
fig = plt.figure(figsize=(14,19))
name = os.path.join(self.resultsDirSN, 'Artis-' + str(self.myXEvent.SN) + '_' + fromDate + '-' + toDate + '_plane_'+self.plane+'_results_18.pdf')
if (self.cb_png.GetValue()==False):
pdf = PdfPages(name)
plt.rc('xtick', labelsize=10)
plt.rc('ytick', labelsize=10)
plt.rc("axes", titlesize=12)
#PUN Error-Warnings
ax = fig.add_subplot(4,3,4)
ax.axis('off')
ax.text(0.15, 0.75, u'PUN-Errors & Warnings', fontweight='bold',fontsize=8)
ypos=0.05
for i,pun_err_type in enumerate(PUN_ERR.keys()):
if len(PUN_ERR[pun_err_type])>0:
ax.text(0.15, ypos+i*0.05, pun_err_type+' :'+str(len(PUN_ERR[pun_err_type])),fontsize=8)
ax.text(0.15, 0.00, u'('+self.myXEvent.PUN_SW+')',fontsize=8)
#----------------------------
#BE
if len(TIME)>0:
datesX = [dateutil.parser.parse(s) for s in TIME]
ATx = pylab.date2num(datesX)
onlyF1 =numpy.zeros(self.events)
onlyF2 =numpy.zeros(self.events)
onlyFG =numpy.zeros(self.events)
for i in range(self.events):
if self.myXEvent.focus[i]==ord('S'):
onlyF1[i]+=onlyF1[i-1]+self.myXEvent.BE_F1[i]
else:
onlyF1[i]+=onlyF1[i-1]
if self.myXEvent.focus[i]==ord('L'):
onlyF2[i]+=onlyF2[i-1]+self.myXEvent.BE_F2[i]
else:
onlyF2[i]+=onlyF2[i-1]
if self.myXEvent.focus[i]==ord('M'):
onlyFG[i]+=onlyFG[i-1]+self.myXEvent.BE_FG[i]
else:
onlyFG[i]+=onlyFG[i-1]
BE_total=onlyF1+onlyF2+onlyFG
ax = fig.add_subplot(4,3,11)
ax.plot_date(ATx, BE_total, marker='', linestyle='-',color='black', label='all (%d)'%BE_total[-1])
ax.plot_date(ATx, onlyF1, marker='', linestyle='-',color='blue', label="F1 (%d)"%onlyF1[-1])
ax.plot_date(ATx, onlyF2, marker='', linestyle='-',color='red', label="F2 (%d)"%onlyF2[-1])
ax.plot_date(ATx, onlyFG, marker='', linestyle='-',color='green', label="FG (%d)"%onlyFG[-1])
ax.set_ylabel('BE', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('summed BE per focus')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
#fig.autofmt_xdate()
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#----------------------------
#Arcing-events
temp_all=0
if len(arcing_time_global) != 0:
Arcing_Time=[]
#Arcing_Time = [dateutil.parser.parse(s) for s in arcing_time_global]
#AT = pylab.date2num(Arcing_Time)
num_arcs= num_arcing.__len__()-num_arcing.count(0)
temp_0x001A=0
temp_0x001B=0
temp_0x001C=0
temp_0x001D=0
temp_0x001E=0
temp_0x0018=0
temp_0x000A=0
temp_0x000B=0
temp_0x000C=0
temp_0x0008=0
temp_0x0007=0
temp_0x0006=0
temp_0x0005=0
temp_0x0004=0
temp_0x0003=0
temp_0x0002=0
temp_0x0001=0
temp_0x0000=0
temp_other =0
temp_all =0
all_arcs =numpy.zeros(num_arcs)
only_0x001A =numpy.zeros(num_arcs)
only_0x001B =numpy.zeros(num_arcs)
only_0x001C =numpy.zeros(num_arcs)
only_0x001D =numpy.zeros(num_arcs)
only_0x001E =numpy.zeros(num_arcs)
only_0x000A =numpy.zeros(num_arcs)
only_0x000B =numpy.zeros(num_arcs)
only_0x000C =numpy.zeros(num_arcs)
only_0x0018 =numpy.zeros(num_arcs)
only_0x0008 =numpy.zeros(num_arcs)
only_0x0007 =numpy.zeros(num_arcs)
only_0x0006 =numpy.zeros(num_arcs)
only_0x0005 =numpy.zeros(num_arcs)
only_0x0004 =numpy.zeros(num_arcs)
only_0x0003 =numpy.zeros(num_arcs)
only_0x0002 =numpy.zeros(num_arcs)
only_0x0001 =numpy.zeros(num_arcs)
only_0x0000 =numpy.zeros(num_arcs)
other_arcs =numpy.zeros(num_arcs)
arc_idx=0
all_arcs_p=0
only_0x001A_p=0
only_0x001B_p=0
only_0x001C_p=0
only_0x001D_p=0
only_0x001E_p=0
only_0x0018_p=0
only_0x000A_p=0
only_0x000B_p=0
only_0x000C_p=0
only_0x0008_p=0
only_0x0007_p=0
only_0x0006_p=0
only_0x0005_p=0
only_0x0004_p=0
only_0x0003_p=0
only_0x0002_p=0
only_0x0001_p=0
only_0x0000_p=0
only_0x001A_n=0
only_0x001B_n=0
only_0x001C_n=0
only_0x001D_n=0
only_0x001E_n=0
only_0x0018_n=0
only_0x000A_n=0
only_0x000B_n=0
only_0x000C_n=0
only_0x0008_n=0
only_0x0007_n=0
only_0x0006_n=0
only_0x0005_n=0
only_0x0004_n=0
only_0x0003_n=0
only_0x0002_n=0
only_0x0001_n=0
only_0x0000_n=0
for i in range(self.events):
if num_arcing[i]>0:
Arcing_Time.append(dateutil.parser.parse(TIME[i]))
if self.myXEvent.arc_0x001A[i]>0:
temp_0x001A+=self.myXEvent.arc_0x001A[i]
if self.myXEvent.arc_0x001B[i]>0:
temp_0x001B+=self.myXEvent.arc_0x001B[i]
if self.myXEvent.arc_0x001C[i]>0:
temp_0x001C+=self.myXEvent.arc_0x001C[i]
if self.myXEvent.arc_0x001D[i]>0:
temp_0x001D+=self.myXEvent.arc_0x001D[i]
if self.myXEvent.arc_0x001E[i]>0:
temp_0x001E+=self.myXEvent.arc_0x001E[i]
if self.myXEvent.arc_0x0018[i]>0:
temp_0x0018+=self.myXEvent.arc_0x0018[i]
if self.myXEvent.arc_0x000A[i]>0:
temp_0x000A+=self.myXEvent.arc_0x000A[i]
if self.myXEvent.arc_0x000B[i]>0:
temp_0x000B+=self.myXEvent.arc_0x000B[i]
if self.myXEvent.arc_0x000C[i]>0:
temp_0x000C+=self.myXEvent.arc_0x000C[i]
if self.myXEvent.arc_0x0008[i]>0:
temp_0x0008+=self.myXEvent.arc_0x0008[i]
if self.myXEvent.arc_0x0007[i]>0:
temp_0x0007+=self.myXEvent.arc_0x0007[i]
if self.myXEvent.arc_0x0006[i]>0:
temp_0x0006+=self.myXEvent.arc_0x0006[i]
if self.myXEvent.arc_0x0005[i]>0:
temp_0x0005+=self.myXEvent.arc_0x0005[i]
if self.myXEvent.arc_0x0004[i]>0:
temp_0x0004+=self.myXEvent.arc_0x0004[i]
if self.myXEvent.arc_0x0003[i]>0:
temp_0x0003+=self.myXEvent.arc_0x0003[i]
if self.myXEvent.arc_0x0002[i]>0:
temp_0x0002+=self.myXEvent.arc_0x0002[i]
if self.myXEvent.arc_0x0001[i]>0:
temp_0x0001+=self.myXEvent.arc_0x0001[i]
if self.myXEvent.arc_0x0000[i]>0:
temp_0x0000+=self.myXEvent.arc_0x0000[i]
if self.myXEvent.arc_other[i]>0:
temp_other+=self.myXEvent.arc_other[i]
temp_all+=num_arcing[i]
only_0x001A_p+=self.myXEvent.arc_0x001A_frame[i].count('+')
only_0x001B_p+=self.myXEvent.arc_0x001B_frame[i].count('+')
only_0x001C_p+=self.myXEvent.arc_0x001C_frame[i].count('+')
only_0x001D_p+=self.myXEvent.arc_0x001D_frame[i].count('+')
only_0x001E_p+=self.myXEvent.arc_0x001E_frame[i].count('+')
only_0x0018_p+=self.myXEvent.arc_0x0018_frame[i].count('+')
only_0x000A_p+=self.myXEvent.arc_0x000A_frame[i].count('+')
only_0x000B_p+=self.myXEvent.arc_0x000B_frame[i].count('+')
only_0x000C_p+=self.myXEvent.arc_0x000C_frame[i].count('+')
only_0x0008_p+=self.myXEvent.arc_0x0008_frame[i].count('+')
only_0x0007_p+=self.myXEvent.arc_0x0007_frame[i].count('+')
only_0x0006_p+=self.myXEvent.arc_0x0006_frame[i].count('+')
only_0x0005_p+=self.myXEvent.arc_0x0005_frame[i].count('+')
only_0x0004_p+=self.myXEvent.arc_0x0004_frame[i].count('+')
only_0x0003_p+=self.myXEvent.arc_0x0003_frame[i].count('+')
only_0x0002_p+=self.myXEvent.arc_0x0002_frame[i].count('+')
only_0x0001_p+=self.myXEvent.arc_0x0001_frame[i].count('+')
only_0x0000_p+=self.myXEvent.arc_0x0000_frame[i].count('+')
only_0x001A_n+=self.myXEvent.arc_0x001A_frame[i].count('-')
only_0x001B_n+=self.myXEvent.arc_0x001B_frame[i].count('-')
only_0x001C_n+=self.myXEvent.arc_0x001C_frame[i].count('-')
only_0x001D_n+=self.myXEvent.arc_0x001D_frame[i].count('-')
only_0x001E_n+=self.myXEvent.arc_0x001E_frame[i].count('-')
only_0x0018_n+=self.myXEvent.arc_0x0018_frame[i].count('-')
only_0x000A_n+=self.myXEvent.arc_0x000A_frame[i].count('-')
only_0x000B_n+=self.myXEvent.arc_0x000B_frame[i].count('-')
only_0x000C_n+=self.myXEvent.arc_0x000C_frame[i].count('-')
only_0x0008_n+=self.myXEvent.arc_0x0008_frame[i].count('-')
only_0x0007_n+=self.myXEvent.arc_0x0007_frame[i].count('-')
only_0x0006_n+=self.myXEvent.arc_0x0006_frame[i].count('-')
only_0x0005_n+=self.myXEvent.arc_0x0005_frame[i].count('-')
only_0x0004_n+=self.myXEvent.arc_0x0004_frame[i].count('-')
only_0x0003_n+=self.myXEvent.arc_0x0003_frame[i].count('-')
only_0x0002_n+=self.myXEvent.arc_0x0002_frame[i].count('-')
only_0x0001_n+=self.myXEvent.arc_0x0001_frame[i].count('-')
only_0x0000_n+=self.myXEvent.arc_0x0000_frame[i].count('-')
all_arcs[arc_idx] =temp_all
only_0x001A[arc_idx] =temp_0x001A
only_0x001B[arc_idx] =temp_0x001B
only_0x001C[arc_idx] =temp_0x001C
only_0x001D[arc_idx] =temp_0x001D
only_0x001E[arc_idx] =temp_0x001E
only_0x0018[arc_idx] =temp_0x0018
only_0x000A[arc_idx] =temp_0x000A
only_0x000B[arc_idx] =temp_0x000B
only_0x000C[arc_idx] =temp_0x000C
only_0x0008[arc_idx] =temp_0x0008
only_0x0007[arc_idx] =temp_0x0007
only_0x0006[arc_idx] =temp_0x0006
only_0x0005[arc_idx] =temp_0x0005
only_0x0004[arc_idx] =temp_0x0004
only_0x0003[arc_idx] =temp_0x0003
only_0x0002[arc_idx] =temp_0x0002
only_0x0001[arc_idx] =temp_0x0001
only_0x0000[arc_idx] =temp_0x0000
other_arcs[arc_idx] =temp_other
arc_idx+=1
all_arcs_p=( only_0x001A_p
+only_0x001B_p
+only_0x001C_p
+only_0x001D_p
+only_0x001E_p
+only_0x0018_p
+only_0x000A_p
+only_0x000B_p
+only_0x000C_p
+only_0x0008_p
+only_0x0007_p
+only_0x0006_p
+only_0x0005_p
+only_0x0004_p
+only_0x0003_p
+only_0x0002_p
+only_0x0001_p
+only_0x0000_p)
all_arcs_n=( only_0x001A_n
+only_0x001B_n
+only_0x001C_n
+only_0x001D_n
+only_0x001E_n
+only_0x0018_n
+only_0x000A_n
+only_0x000B_n
+only_0x000C_n
+only_0x0008_n
+only_0x0007_n
+only_0x0006_n
+only_0x0005_n
+only_0x0004_n
+only_0x0003_n
+only_0x0002_n
+only_0x0001_n
+only_0x0000_n)
if all_arcs_n==0 and all_arcs_p==0: # evtl. alte SW ohne #
only_0x001A_p=self.myXEvent.arc_0x001A.sum()
only_0x001B_p=self.myXEvent.arc_0x001B.sum()
only_0x001C_p=self.myXEvent.arc_0x001C.sum()
only_0x001D_p=self.myXEvent.arc_0x001D.sum()
only_0x001E_p=self.myXEvent.arc_0x001E.sum()
only_0x0018_p=self.myXEvent.arc_0x0018.sum()
only_0x000A_p=self.myXEvent.arc_0x000A.sum()
only_0x000B_p=self.myXEvent.arc_0x000B.sum()
only_0x000C_p=self.myXEvent.arc_0x000C.sum()
only_0x0008_p=self.myXEvent.arc_0x0008.sum()
only_0x0007_p=self.myXEvent.arc_0x0007.sum()
only_0x0006_p=self.myXEvent.arc_0x0006.sum()
only_0x0005_p=self.myXEvent.arc_0x0005.sum()
only_0x0004_p=self.myXEvent.arc_0x0004.sum()
only_0x0003_p=self.myXEvent.arc_0x0003.sum()
only_0x0002_p=self.myXEvent.arc_0x0002.sum()
only_0x0001_p=self.myXEvent.arc_0x0001.sum()
only_0x0000_p=self.myXEvent.arc_0x0000.sum()
AT=pylab.date2num(Arcing_Time)
ax = fig.add_subplot(4,3,1)
ax.plot_date(AT, all_arcs, marker='.', linestyle='-',label='all_arcs (+%d,-%d)'%(temp_all-all_arcs_n,all_arcs_n) , color='black')
ax.plot_date(AT, only_0x001E, marker='.', linestyle='-',label='0x001E (+%d,-%d)'%(only_0x001E_p,only_0x001E_n) +' Oneside Arcing FPGA Cathode' , color='blueviolet')
ax.plot_date(AT, only_0x001D, marker='.', linestyle='-',label='0x001D (+%d,-%d)'%(only_0x001D_p,only_0x001D_n) +' Oneside Arcing FPGA Anode' , color='darkgray')
ax.plot_date(AT, only_0x001C, marker='.', linestyle='-',label='0x001C (+%d,-%d)'%(only_0x001C_p,only_0x001C_n) +' Warn. Bothside Arcing FPGA' , color='darkgreen')
ax.plot_date(AT, only_0x001B, marker='.', linestyle='-',label='0x001B (+%d,-%d)'%(only_0x001B_p,only_0x001B_n) +' Max kV sum kV detected by FPGA' , color='magenta')
ax.plot_date(AT, only_0x001A, marker='.', linestyle='-',label='0x001A (+%d,-%d)'%(only_0x001A_p,only_0x001A_n) +' Warn. Oneside Arcing' , color='lavender')
ax.plot_date(AT, only_0x0018, marker='.', linestyle='-',label='0x0018 (+%d,-%d)'%(only_0x0018_p,only_0x0018_n) +' Warn. Bothside Arcing' , color='red')
ax.plot_date(AT, only_0x000C, marker='.', linestyle='-',label='0x000C (+%d,-%d)'%(only_0x000C_p,only_0x000C_n) +' Warn. Powersupply' , color='darkred')
ax.plot_date(AT, only_0x000B, marker='.', linestyle='-',label='0x000B (+%d,-%d)'%(only_0x000B_p,only_0x000B_n) +' Warn. Fault Inverter' , color='darkorchid')
ax.plot_date(AT, only_0x000A, marker='.', linestyle='-',label='0x000A (+%d,-%d)'%(only_0x000A_p,only_0x000A_n) +' Warn. I_load' , color='darkmagenta')
ax.plot_date(AT, only_0x0008, marker='.', linestyle='-',label='0x0008 (+%d,-%d)'%(only_0x0008_p,only_0x0008_n) +' Warn. UBmax Inverter' , color='green')
ax.plot_date(AT, only_0x0007, marker='.', linestyle='-',label='0x0007 (+%d,-%d)'%(only_0x0007_p,only_0x0007_n) +' Warn. Imax Inverter' , color='blue')
ax.plot_date(AT, only_0x0006, marker='.', linestyle='-',label='0x0006 (+%d,-%d)'%(only_0x0006_p,only_0x0006_n) +' Warn. Delta kV negative kV' , color='limegreen')
ax.plot_date(AT, only_0x0005, marker='.', linestyle='-',label='0x0005 (+%d,-%d)'%(only_0x0005_p,only_0x0005_n) +' Warn. Delta kV positive kV' , color='maroon')
ax.plot_date(AT, only_0x0004, marker='.', linestyle='-',label='0x0004 (+%d,-%d)'%(only_0x0004_p,only_0x0004_n) +' Warn. max kV negative kV' , color='gray')
ax.plot_date(AT, only_0x0003, marker='.', linestyle='-',label='0x0003 (+%d,-%d)'%(only_0x0003_p,only_0x0003_n) +' Warn. max kV positive kV' , color='indigo')
ax.plot_date(AT, only_0x0002, marker='.', linestyle='-',label='0x0002 (+%d,-%d)'%(only_0x0002_p,only_0x0002_n) +' Warn. during startc inverter adjust' , color='yellow')
ax.plot_date(AT, only_0x0001, marker='.', linestyle='-',label='0x0001 (+%d,-%d)'%(only_0x0001_p,only_0x0001_n) +' Warn. during static inverter adjust' , color='cyan')
ax.plot_date(AT, only_0x0000, marker='.', linestyle='-',label='0x0000 (+%d,-%d)'%(only_0x0000_p,only_0x0000_n) +' No SWR within 10s' , color='hotpink')
ax.plot_date(AT, other_arcs , marker='.', linestyle='-',label='other (%d)'%temp_other , color='firebrick')
ax.set_ylabel('occurance /# ', size='x-small')
ax.set_xlabel('Time', size='x-small')
legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.title("Arcing events (PUD 5016)- Sum:{0}".format(len(arcing_time_global)) + "\nTotal Arcing events: {0}".format(num_arcing_tot), size='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
datesX = [dateutil.parser.parse(s) for s in TIME]
datemin = datesX[0] #Zeitpunkt erster Xray Event (nicht Grid Warning Event)
datemin =datetime.datetime(datemin.year,datemin.month,datemin.day,0,0,0)
datemax = datesX[-1] #Zeitpunkt letzter Xray Event (nicht Grid Warning Event
datemax = datetime.datetime(datemax.year,datemax.month,datemax.day,23,59,59)
ax.set_xlim(datemin, datemax)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
else:
ax = fig.add_subplot(4,3,1)
ax.text(0.3, 0.5, 'no arcing-events')
plt.title('Arcing events', size='small')
##### focus dependent arcing
arcing_kv_small = []
arcing_kv_large = []
arcing_kv_micro = []
arcing_time_small = []
arcing_time_large = []
arcing_time_micro = []
arcing_pow_large=[]
arcing_HU_large=[]
arcing_pow_small=[]
arcing_HU_small=[]
arcing_pow_micro=[]
arcing_HU_micro=[]
if len(arcing_time_global) != 0:
kk=set(arcing_idx_global)
arc_idx=[arcing_idx_global.index(x) for x in kk ] #list of indices of first occurance of xray id
for i in arc_idx:
if arcing_foc_global[i] == 'S':
arcing_kv_small.append(arcing_kV_global[i])
arcing_pow_small.append(arcing_kV_global[i]*arcing_mA_global[i]/1000.)
arcing_HU_small.append(arcing_HU_global[i])
arcing_time_small.append(dateutil.parser.parse(arcing_time_global[i]) )
elif arcing_foc_global[i] == 'L':
arcing_kv_large.append(arcing_kV_global[i])
arcing_pow_large.append(arcing_kV_global[i]*arcing_mA_global[i]/1000.)
arcing_HU_large.append(arcing_HU_global[i])
arcing_time_large.append(dateutil.parser.parse(arcing_time_global[i]) )
elif arcing_foc_global[i] == 'M':
arcing_kv_micro.append(arcing_kV_global[i])
arcing_pow_micro.append(arcing_kV_global[i]*arcing_mA_global[i]/1000.)
arcing_HU_micro.append(arcing_HU_global[i])
arcing_time_micro.append(dateutil.parser.parse(arcing_time_global[i]) )
else:
1 #should not happen
if len(arcing_kv_small) > 0:
ax = fig.add_subplot(4,3,7)
ax.hist(arcing_kv_small+[-1], 20, range=(40,125)) #add zero to avoid error hist with only one element
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
ax.set_xlim(40,125)
plt.title("# small focus arc trains: {0}".format(len(arcing_kv_small)), size='small')
else:
ax = fig.add_subplot(4,3,7)
ax.text(0.2, 0.5, 'No small focus arcings')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
ax.set_xlim(40,125)
plt.title("# small focus arcings: {0}".format(len(arcing_kv_small)), size='small')
if len(arcing_kv_large) > 0:
ax = fig.add_subplot(4,3,8)
ax.hist(arcing_kv_large+[-1], 20, range=(40,125)) #add zero to avoid error hist with only one element
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
ax.set_xlim(40,125)
plt.title("# large focus arc trains: {0}".format(len(arcing_kv_large)), size='small')
else:
ax = fig.add_subplot(4,3,8)
ax.text(0.2, 0.5, 'No large focus arcings ')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
ax.set_xlim(40,125)
plt.title("# large focus arcings: {0}".format(len(arcing_kv_large)), size='small')
if len(arcing_kv_micro) > 0:
ax = fig.add_subplot(4,3,9)
ax.hist(arcing_kv_micro+[-1], 20, range=(40,125)) #add zero to avoid error hist with only one element
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
ax.set_xlim(40,125)
plt.title("# micro focus arc trains: {0}".format(len(arcing_kv_micro)), size='small')
else:
ax = fig.add_subplot(4,3,9)
ax.text(0.2, 0.5, 'No micro focus arcings')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
ax.set_xlim(40,125)
plt.title("# micro focus arcings: {0}".format(len(arcing_kv_micro)), size='small')
else:
ax = fig.add_subplot(4,3,7)
ax.text(0.2, 0.5, 'No small focus arcings')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
plt.title("# small focus arcings: 0", size='small')
ax = fig.add_subplot(4,3,8)
ax.text(0.2, 0.5, 'No large focus arcings ')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
plt.title("# large focus arcings: 0", size='small')
ax = fig.add_subplot(4,3,9)
ax.text(0.2, 0.5, 'No micro focus arcings ')
ax.set_xlabel('Voltage /[kV]', size='x-small')
ax.set_ylabel('occurance /# ', size='x-small')
ax.grid(True)
plt.title("# micro focus arcings: 0", size='small')
try:
#HU vs pulse power of arcing events
ax = fig.add_subplot(4,3,12)
ax.plot(arcing_HU_small,arcing_pow_small, marker='.', linestyle='', color='red' , label='S')
ax.plot(arcing_HU_large,arcing_pow_large, marker='.', linestyle='', color='blue', label='L' )
ax.plot(arcing_HU_micro,arcing_pow_micro, marker='.', linestyle='', color='green', label='M' )
ax.set_xlabel('HU /[%]', size='x-small')
ax.set_ylabel('pulse power /[kW]', size='x-small')
ax.grid(True)
ax.set_xlim(0,100)
ax.set_ylim(0,100)
ax.legend()
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('Arcing - HU vs pulse power (arc trains))', size='small')
#hist of arcing regarding to pulsepower F1
ax = fig.add_subplot(4,3,3)
ax.hist(arcing_pow_small+[-1], 50, range=(1,50))
ax.set_xlabel('kW', size='x-small')
ax.set_ylabel('occurance /#', size='x-small')
ax.grid(True)
ax.set_xlim(0,50)
plt.title('Arcing vs. pulsepower F1 (arc trains) ', size='small')
#plt.xticks(c, bezeichnung, rotation=90)
#hist of arcing regarding to pulsepower F2
ax = fig.add_subplot(4,3,6)
ax.hist(arcing_pow_large+[-1], 100, range=(1,100))
ax.set_xlabel('kW', size='x-small')
ax.set_ylabel('occurance /#', size='x-small')
ax.grid(True)
ax.set_xlim(0,100)
plt.title('Arcing vs. pulsepower F2 (arc trains)', size='small')
#-----------------------------
# sum of xray events over time
p_arc=numpy.zeros(len(self.myXEvent.arc_0x001A_frame))
n_arc=numpy.zeros(len(self.myXEvent.arc_0x001A_frame))
for ii in range(len(self.myXEvent.arc_0x001A_frame)):
p_arc[ii]+=(self.myXEvent.arc_0x001A_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x001A_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x001B_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x001B_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x001C_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x001C_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x001D_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x001D_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x001E_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x001E_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0018_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0018_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0008_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0008_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0007_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0007_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0006_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0006_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0005_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0005_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0004_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0004_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0003_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0003_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0002_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0002_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0001_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0001_frame[ii]).count('-')
p_arc[ii]+=(self.myXEvent.arc_0x0000_frame[ii]).count('+')
n_arc[ii]+=(self.myXEvent.arc_0x0000_frame[ii]).count('-')
datesX = [dateutil.parser.parse(s) for s in TIME]
ATx = pylab.date2num(datesX)
all = numpy.array(arange(self.events))+1
onlyF1 =numpy.zeros(self.events)
onlyF2 =numpy.zeros(self.events)
onlyFG =numpy.zeros(self.events)
F1_events=0
F2_events=0
FG_events=0
for i in range(self.events):
if self.myXEvent.focus[i]==ord('S'):
F1_events+=1
if self.myXEvent.focus[i]==ord('L'):
F2_events+=1
if self.myXEvent.focus[i]==ord('M'):
FG_events+=1
onlyF1[i]=F1_events
onlyF2[i]=F2_events
onlyFG[i]=FG_events
ax = fig.add_subplot(4,3,10)
ax.plot_date(ATx, all, marker='', linestyle='-',color='black', label='all (%d)'%self.events)
ax.plot_date(ATx, onlyF1, marker='', linestyle='-',color='blue', label="F1 (%d)"%F1_events)
ax.plot_date(ATx, onlyF2, marker='', linestyle='-',color='red', label="F2 (%d)"%F2_events)
ax.plot_date(ATx, onlyFG, marker='', linestyle='-',color='green', label="FG (%d)"%FG_events)
ax.set_ylabel('occurance /# ', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
arcs_per_10000=(p_arc>0).sum()*10000./self.events
if all_arcs_n==0 and all_arcs_p==0: # evtl. alte SW ohne #
arcs_per_10000=temp_all*10000./self.events
plt.title("#Xrays:{0}".format(self.events)+ ' #Arc(+)-Bursts/10k Xrays:%2.2f'%arcs_per_10000, size='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
#fig.autofmt_xdate()
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
fig.text(0.5, 0.95,'XA'+str(self.myXEvent.SN)+' part18'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(TIME))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(Startzeit[0])+' End: '+str(Startzeit[len(Startzeit)-1]+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr), horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p1.png')
plt.close()
except:
print 'No xray-Events found! Skipping plot page 1!'
#----------------------------------------------------
#page2
fig = plt.figure(figsize=(14,19))
#kV arcing delevopment in time
ax = fig.add_subplot(4,3,1)
ax.plot_date(arcing_time_small, arcing_kv_small, marker='.', linestyle='',color='blue', label="F1")
ax.plot_date(arcing_time_large, arcing_kv_large, marker='.', linestyle='',color='red', label="F2")
ax.plot_date(arcing_time_micro, arcing_kv_micro, marker='.', linestyle='',color='green', label="FG")
ax.set_ylim(40, 130)
ax.set_ylabel('Voltage [kV]', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=3)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('Arcing over time (kV dependent)', size='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
#fig.autofmt_xdate()
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#kW arcing delevopment in time
ax = fig.add_subplot(4,3,2)
ax.plot_date(arcing_time_small, arcing_pow_small, marker='.', linestyle='',color='blue', label="F1")
ax.plot_date(arcing_time_large, arcing_pow_large, marker='.', linestyle='',color='red', label="F2")
ax.plot_date(arcing_time_micro, arcing_pow_micro, marker='.', linestyle='',color='green', label="FG")
ax.set_ylim(5, 130)
ax.set_ylabel('Power [kW]', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.legend(loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
arcs_per_10000=(numpy.array(num_arcing)>0).sum()*10000/self.events
plt.title('Arcing over time (kW dependent)', size='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
#fig.autofmt_xdate()
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#hist of arcing regarding to pulsepower FG
ax = fig.add_subplot(4,3,3)
ax.hist(arcing_pow_micro+[-1], 100, range=(1,30))
ax.set_xlabel('kW', size='x-small')
ax.set_ylabel('occurance /#', size='x-small')
ax.grid(True)
plt.title('Arcing vs. pulsepower FG (arc trains) ', size='small')
ax = fig.add_subplot(4,3,6)
scan_secs=(self.myXEvent.time[0:self.events]*self.myXEvent.frames[0:self.events]).sum()/1000.0
if scan_secs>0:
normed_arcs_less_80kV = ((numpy.array(num_arcing)>0)*(self.myXEvent.voltage[0:self.events]<80) ).sum()*10000./scan_secs
normed_arcs_80_100kV = ((numpy.array(num_arcing)>0)*(self.myXEvent.voltage[0:self.events]>=80)*(self.myXEvent.voltage[0:self.events]<=100) ).sum()*10000./scan_secs
normed_arcs_over_100kV = ((numpy.array(num_arcing)>0)*(self.myXEvent.voltage[0:self.events]>=100)).sum()*10000./scan_secs
normed_arcs_less_80kV_p = ((p_arc>0)*(self.myXEvent.voltage[0:self.events]<80) ).sum()*10000./scan_secs
normed_arcs_80_100kV_p = ((p_arc>0)*(self.myXEvent.voltage[0:self.events]>=80)*(self.myXEvent.voltage[0:self.events]<=100) ).sum()*10000./scan_secs
normed_arcs_over_100kV_p= ((p_arc>0)*(self.myXEvent.voltage[0:self.events]>=100)).sum()*10000./scan_secs
normed_arcs_less_80kV_n = ((n_arc>0)*(self.myXEvent.voltage[0:self.events]<80) ).sum()*10000./scan_secs
normed_arcs_80_100kV_n = ((n_arc>0)*(self.myXEvent.voltage[0:self.events]>=80)*(self.myXEvent.voltage[0:self.events]<=100) ).sum()*10000./scan_secs
normed_arcs_over_100kV_n= ((n_arc>0)*(self.myXEvent.voltage[0:self.events]>=100)).sum()*10000./scan_secs
else:
normed_arcs_less_80kV=0
normed_arcs_80_100kV=0
normed_arcs_over_100kV=0
normed_arcs_less_80kV_p=0
normed_arcs_80_100kV_p=0
normed_arcs_over_100kV_p=0
normed_arcs_less_80kV_n=0
normed_arcs_80_100kV_n=0
normed_arcs_over_100kV_n=0
if all_arcs_n==0 and all_arcs_p==0: # evtl. alte SW ohne #
normed_arcs_less_80kV_p=normed_arcs_less_80kV
normed_arcs_80_100kV_p=normed_arcs_80_100kV
normed_arcs_over_100kV_p=normed_arcs_over_100kV
ax.bar(1,normed_arcs_less_80kV_p,width=0.3,bottom=0,color='red')
ax.bar(1,normed_arcs_less_80kV_n,width=0.3,bottom=normed_arcs_less_80kV_p,color='green')
ax.bar(2,normed_arcs_80_100kV_p,width=0.3,bottom=0,color='red')
ax.bar(2,normed_arcs_80_100kV_n,width=0.3,bottom=normed_arcs_80_100kV_p,color='green')
ax.bar(3,normed_arcs_over_100kV_p,width=0.3,bottom=0,color='red')
ax.bar(3,normed_arcs_over_100kV_n,width=0.3,bottom=normed_arcs_over_100kV_p,color='green')
if normed_arcs_less_80kV_p>0:
ax.text(1, 0, "%2.2f"%normed_arcs_less_80kV_p ,size='x-small',color='black')
if normed_arcs_80_100kV_p>0:
ax.text(2, 0, "%2.2f"%normed_arcs_80_100kV_p ,size='x-small',color='black')
if normed_arcs_over_100kV_p>0:
ax.text(3, 0, "%2.2f"%normed_arcs_over_100kV_p,size='x-small',color='black')
if normed_arcs_less_80kV_n>0:
ax.text(1, normed_arcs_less_80kV_p, "%2.2f"%normed_arcs_less_80kV_n ,size='x-small',color='black')
if normed_arcs_80_100kV_n>0:
ax.text(2, normed_arcs_80_100kV_p, "%2.2f"%normed_arcs_80_100kV_n ,size='x-small',color='black')
if normed_arcs_over_100kV_n>0:
ax.text(3, normed_arcs_over_100kV_p, "%2.2f"%normed_arcs_over_100kV_n,size='x-small',color='black')
ax.set_xlabel('kV range', size='x-small')
ax.set_ylabel('#arc bursts ', size='x-small')
ax.grid(True)
ax.legend(('in pulse (+): %2.2f'%(normed_arcs_less_80kV_p+normed_arcs_80_100kV_p+normed_arcs_over_100kV_p),'after pulse (-): %2.2f'%(normed_arcs_less_80kV_n+normed_arcs_80_100kV_n+normed_arcs_over_100kV_n)),loc=2)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
ax.set_xlim(0.5,3.5)
plt.xticks([1, 2, 3], ["<80kV", "80-100kV", ">100kV"])
plt.title('Arc Bursts per 10k Scan Secs (%2.2fs)'%scan_secs,size='x-small')
###############################
#grid warning events
if len(grid_time_global) != 0:
grid_Time=[]
num_grids= num_grid.__len__()-num_grid.count(0)
temp_0x000A=0
temp_0x0009=0
temp_0x0008=0
temp_0x0007=0
temp_0x0006=0
temp_0x0005=0
temp_0x0004=0
temp_0x0003=0
temp_0x0002=0
temp_0x0001=0
temp_0x0000=0
temp_other =0
temp_all =0
all_grids =numpy.zeros(num_grids)
only_0x000A =numpy.zeros(num_grids)
only_0x0009 =numpy.zeros(num_grids)
only_0x0008 =numpy.zeros(num_grids)
only_0x0007 =numpy.zeros(num_grids)
only_0x0006 =numpy.zeros(num_grids)
only_0x0005 =numpy.zeros(num_grids)
only_0x0004 =numpy.zeros(num_grids)
only_0x0003 =numpy.zeros(num_grids)
only_0x0002 =numpy.zeros(num_grids)
only_0x0001 =numpy.zeros(num_grids)
only_0x0000 =numpy.zeros(num_grids)
other_grids =numpy.zeros(num_grids)
grid_idx=0
for i in range(self.events):
if num_grid[i]>0:
grid_Time.append(dateutil.parser.parse(TIME[i]))
if self.myXEvent.grid_0x000A[i]>0:
temp_0x000A+=self.myXEvent.grid_0x000A[i]
if self.myXEvent.grid_0x0009[i]>0:
temp_0x0009+=self.myXEvent.grid_0x0009[i]
if self.myXEvent.grid_0x0008[i]>0:
temp_0x0008+=self.myXEvent.grid_0x0008[i]
if self.myXEvent.grid_0x0007[i]>0:
temp_0x0007+=self.myXEvent.grid_0x0007[i]
if self.myXEvent.grid_0x0006[i]>0:
temp_0x0006+=self.myXEvent.grid_0x0006[i]
if self.myXEvent.grid_0x0005[i]>0:
temp_0x0005+=self.myXEvent.grid_0x0005[i]
if self.myXEvent.grid_0x0004[i]>0:
temp_0x0004+=self.myXEvent.grid_0x0004[i]
if self.myXEvent.grid_0x0003[i]>0:
temp_0x0003+=self.myXEvent.grid_0x0003[i]
if self.myXEvent.grid_0x0002[i]>0:
temp_0x0002+=self.myXEvent.grid_0x0002[i]
if self.myXEvent.grid_0x0001[i]>0:
temp_0x0001+=self.myXEvent.grid_0x0001[i]
if self.myXEvent.grid_0x0000[i]>0:
temp_0x0000+=self.myXEvent.grid_0x0000[i]
if self.myXEvent.grid_other[i]>0:
temp_other+=self.myXEvent.grid_other[i]
temp_all+=num_grid[i]
all_grids[grid_idx] =temp_all
only_0x000A[grid_idx] =temp_0x000A
only_0x0009[grid_idx] =temp_0x0009
only_0x0008[grid_idx] =temp_0x0008
only_0x0007[grid_idx] =temp_0x0007
only_0x0006[grid_idx] =temp_0x0006
only_0x0005[grid_idx] =temp_0x0005
only_0x0004[grid_idx] =temp_0x0004
only_0x0003[grid_idx] =temp_0x0003
only_0x0002[grid_idx] =temp_0x0002
only_0x0001[grid_idx] =temp_0x0001
only_0x0000[grid_idx] =temp_0x0000
other_grids[grid_idx] =temp_other
grid_idx+=1
AT=pylab.date2num(grid_Time)
ax = fig.add_subplot(4,3,7)
ax.plot_date(AT, all_grids, marker='.', linestyle='-',label='all_grid_warnings (%d)'%temp_all , color='black')
ax.plot_date(AT, only_0x000A, marker='.', linestyle='-',label='0x000A (%d)'%temp_0x000A +' Grid circuit is broken without HV active' , color='darkred')
ax.plot_date(AT, only_0x0009, marker='.', linestyle='-',label='0x0009 (%d)'%temp_0x0009 +' Grid circuit is short without HV active' , color='red')
ax.plot_date(AT, only_0x0008, marker='.', linestyle='-',label='0x0008 (%d)'%temp_0x0008 +' Grid circuit is open without HV active' , color='green')
ax.plot_date(AT, only_0x0007, marker='.', linestyle='-',label='0x0007 (%d)'%temp_0x0007 +' Grid error without HV active' , color='blue')
ax.plot_date(AT, only_0x0006, marker='.', linestyle='-',label='0x0006 (%d)'%temp_0x0006 +' Grid ctrl not ready bef. recov. fr. arcing' , color='limegreen')
ax.plot_date(AT, only_0x0005, marker='.', linestyle='-',label='0x0005 (%d)'%temp_0x0005 +' Grid circuit is broken with HV active' , color='maroon')
ax.plot_date(AT, only_0x0004, marker='.', linestyle='-',label='0x0004 (%d)'%temp_0x0004 +' Grid circuit is short with HV active' , color='gray')
ax.plot_date(AT, only_0x0003, marker='.', linestyle='-',label='0x0003 (%d)'%temp_0x0003 +' Grid circuit is open with HV active' , color='indigo')
ax.plot_date(AT, only_0x0002, marker='.', linestyle='-',label='0x0002 (%d)'%temp_0x0002 +' Grid error with high voltage active' , color='yellow')
ax.plot_date(AT, only_0x0001, marker='.', linestyle='-',label='0x0001 (%d)'%temp_0x0001 +' Grid control not ready before starting HV' , color='cyan')
ax.plot_date(AT, only_0x0000, marker='.', linestyle='-',label='0x0000 (%d)'%temp_0x0000 +' Grid control hardware D660 is missing' , color='hotpink')
ax.plot_date(AT, other_grids, marker='.', linestyle='-',label='other (%d)'%temp_other , color='firebrick')
ax.set_ylabel('occurance /# ', size='x-small')
ax.set_xlabel('Time', size='x-small')
#ylim(ymin=0.01)
legend(bbox_to_anchor=(1.04, 1), loc=2, borderaxespad=0.)
plt.title("Grid warnings (PUD 509A) - Sum:{0}".format(len(grid_time_global)) + "\nTotal Grid warnings: {0}".format(num_grid_tot), size='small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
datemin = datesX[0] #Zeitpunkt erster Xray Event (nicht Grid Warning Event)
datemin =datetime.datetime(datemin.year,datemin.month,datemin.day,0,0,0)
datemax = datesX[-1] #Zeitpunkt letzter Xray Event (nicht Grid Warning Event
datemax = datetime.datetime(datemax.year,datemax.month,datemax.day,23,59,59)
ax.set_xlim(datemin, datemax)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#"""
else:
ax = fig.add_subplot(4,3,7)
ax.text(0.3, 0.5, 'no grid warnings')
plt.title('Grid warnings', size='small')
#### Power vs HU for all Events
ax = fig.add_subplot(4,3,9)
ax.plot(self.myXEvent.HU[0:self.events],self.myXEvent.current[0:self.events]*self.myXEvent.voltage[0:self.events]/1000., marker='.', linestyle='', color='red')
ax.set_xlabel('HU /[%]', size='x-small')
ax.set_ylabel('pulse power /[kW]', size='x-small')
ax.grid(True)
ax.set_xlim(0,100)
ax.set_ylim(0,100)
ax.legend()
plt.title('HU vs pulse power (all events))', size='small')
#### Watervalue over time
ax = fig.add_subplot(4,3,12)
xxtime = [dateutil.parser.parse(s) for s in TIME]
s = pylab.date2num(xxtime)
ax.plot_date(s, self.myXEvent.was[0:self.events], marker='.', linestyle='.')
ax.set_ylabel('Watervalue /[mm]', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
plt.title('Watervalue over time, mean WV: %2.1f mm'%self.myXEvent.was[0:self.events].mean(), size='small')
#### Histogram of power rel to max power
try:
if self.myXEvent.maxPower_Istzeit[0]!=-1:
ax = fig.add_subplot(4,3,10)
temp_array=numpy.array(self.myXEvent.maxPower_Sollzeit)
ax.hist(self.myXEvent.current[0:self.events]*(self.myXEvent.focus[0:self.events]==ord('L'))*self.myXEvent.voltage[0:self.events]/temp_array/1000.,100, range=(0.01,1.0))
ax.set_ylabel('# occurance', size='x-small')
ax.set_xlabel('review pulse power / max pulse power (preview) \n (based on default tube prom, large focus)', size='x-small')
ax.set_xlim(0.0,1.0)
ax.grid(True)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#plt.title('pulse power / max power\n(of review based on org tube prom data)', size='small')
except:
True
try:
if self.myXEvent.maxPower_Istzeit[0]!=-1:
ax = fig.add_subplot(4,3,11)
temp_array=numpy.array(self.myXEvent.maxPower_Sollzeit)
ax.hist(self.myXEvent.current[0:self.events]*(self.myXEvent.focus[0:self.events]==ord('S'))*self.myXEvent.voltage[0:self.events]/temp_array/1000.,100, range=(0.01,1.0))
ax.set_ylabel('# occurance', size='x-small')
ax.set_xlabel('review pulse power / max pulse power (preview) \n (based on default tube prom, small focus)', size='x-small')
ax.set_xlim(0.0,1.0)
ax.grid(True)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
#plt.title('pulse power / max power\n(of review based on org tube prom data)', size='small')
except:
True
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part18'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(TIME))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(fromDate)+' End: '+str(toDate)+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr, horizontalalignment='center', verticalalignment='center')
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p2.png')
#----------------------------------
#page3
fig = plt.figure(figsize=(14,19))
prev_xlims_min=pylab.date2num(self.start__datum)
prev_xlims_max=pylab.date2num(self.ende__datum)
# Time plots of driving frequency and act tube frq
if len(self.driv_tube_freq)!=0:
ax = fig.add_subplot(6,1,1)
xxtime = [dateutil.parser.parse(s) for s in self.envtime]
s = pylab.date2num(xxtime)
if len(PUN_ERR['Err_5023_RAC_OP'])>0:
err_time=PUN_ERR['Err_5023_RAC_OP']
err_val=[190 for r in PUN_ERR['Err_5023_RAC_OP']]
s_err = pylab.date2num(err_time)
ax.plot_date(s, self.driv_tube_freq, marker='.',markersize=2, linestyle='', label='drive_tube_freq',markeredgecolor='red',color='red')
xxtime = [dateutil.parser.parse(s) for s in self.envtime2]
s = pylab.date2num(xxtime)
ax.plot_date(s, self.act_tube_freq , marker='.',markersize=2, linestyle='', label='act_tube_freq', markeredgecolor='blue', color='blue')
if len(PUN_ERR['Err_5023_RAC_OP'])>0:
ax.plot_date(s_err, err_val , marker='o', markersize=5, linestyle='', label='Err_5023_RAC_OP', color='black')
ax.set_ylabel('Frequency /[Hz]', size='x-small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
ax.set_ylim(120,250)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
ax.set_xticklabels([])
ax.set_xlim(prev_xlims_min,prev_xlims_max)
ax.legend(bbox_to_anchor=(1.0001, 1), loc=2, borderaxespad=0.,numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
colors_ = ['red','blue']
for color,text in zip(colors_,leg.get_texts()):
text.set_color(color)
#Schlupfberechnung (nicht ganz sauber, wenn Zeitdifferenzen zwischen Antrieb und Istdrehzahl (todo: sicherstellen innerhalt delta_t=20s?)
temp_driv_frq=numpy.array(self.driv_tube_freq)
temp_act_frq=numpy.array(self.act_tube_freq)
del_elem=numpy.nonzero(temp_act_frq==65535)
temp_driv_frq=numpy.delete(temp_driv_frq,del_elem)
temp_act_frq=numpy.delete(temp_act_frq,del_elem)
min_l=min(len(temp_driv_frq),len(temp_act_frq))
slip=temp_driv_frq[:min_l]-temp_act_frq[:min_l]
if len(temp_driv_frq)!=0:
txt='max driving frequency:%2.1f Hz - mean driving freq: %2.1f Hz - STD driving frequency %2.1f Hz'%(temp_driv_frq.max(),temp_driv_frq.mean(),temp_driv_frq.std())
txt=txt+'\n'
txt=txt+'max actual freq:%2.1f Hz - mean actual freq:%2.1f Hz - STD driving frequency %2.1f Hz'%(temp_act_frq.max(),temp_act_frq.mean(),temp_act_frq.std())
txt=txt+'\n'
txt=txt+'max slip:%2.1f Hz - mean slip:%2.1f Hz - STD slip:%2.1f Hz'%(slip.max(),slip.mean(),slip.std())
plt.title(txt, size='small')
# Time plots of driving current
if len(self.envtime3)!=0:
ax = fig.add_subplot(6,1,2)
if len(PUN_ERR['Err_5023_RAC_OP'])>0:
err_time=PUN_ERR['Err_5023_RAC_OP']
err_val=[7000 for r in PUN_ERR['Err_5023_RAC_OP']]
s_err = pylab.date2num(err_time)
xxtime = [dateutil.parser.parse(cc) for cc in self.envtime3]
s3 = pylab.date2num(xxtime)
ax.plot_date(s3, self.driv_current, marker='.', markeredgecolor='green', markersize=1, linestyle='', label='driv_current', color='green')
if len(PUN_ERR['Err_5023_RAC_OP'])>0:
ax.plot_date(s_err, err_val , marker='o', linestyle='', label='Err_5023_RAC_OP', color='black')
ax.set_ylabel('Drive current /[mA]', size='x-small')
#ax.set_xlabel('Time', size='x-small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
ax.set_ylim(min(self.driv_current)-2000,max(self.driv_current)+2000)
ax.set_xlim(prev_xlims_min,prev_xlims_max)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
ax.set_xticklabels([])
ax.legend(bbox_to_anchor=(1.0001, 1), loc=2, borderaxespad=0.,numpoints=1, handlelength=0)
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('mean driving current: %2.1f mA'%mean(self.driv_current) + ' --- std driving current: %2.1f mA'%(numpy.array(self.driv_current)).std() , size='small')
# Time plot of oil temp / H1 temp /Schlupf
if len(self.t0_temp)!=0:
ax = fig.add_subplot(6,1,3)
xxtime = [dateutil.parser.parse(r) for r in self.t0_time]
r = pylab.date2num(xxtime)
ax.plot_date(r, self.t0_temp, marker='.',markersize=2, linestyle='', label='T0_oil_Temp', markeredgecolor='red', color='red')
ax.set_ylabel('Oil/H1 temp /[grad C]', size='x-small',color='black')
ax.grid(True)
ax.set_ylim(0,100)
for tl in ax.get_yticklabels():
tl.set_color('red')
#H1 temp
xxtime = [dateutil.parser.parse(r) for r in self.H1_time]
r = pylab.date2num(xxtime)
ax.plot_date(r, self.H1_temp, marker='.',markersize=2, linestyle='', label='H1_Temp', markeredgecolor='green', color='green')
#Cooling aggregat runnning
cstate=[]
ctime=[]
if len(cooling_state)>0:
for i in range(1,len(cooling_state)):
if cooling_state[i]>0 and cooling_state[i-1]<=0:
cstate.append(0)
ctime.append(pylab.date2num(dateutil.parser.parse(cooling_time[i-1])))
cstate.append(0)
ctime.append(pylab.date2num(dateutil.parser.parse(cooling_time[i])))
elif cooling_state[i]<=0 and cooling_state[i-1]>0:
cstate.append(5)
ctime.append(pylab.date2num(dateutil.parser.parse(cooling_time[i-1])))
cstate.append(5)
ctime.append(pylab.date2num(dateutil.parser.parse(cooling_time[i])))
else:
if cooling_state[i-1]<=0:
cstate.append(0)
else:
cstate.append(5)
ctime.append(pylab.date2num(dateutil.parser.parse(cooling_time[i-1])))
if cooling_state[-1]>0:
cstate.append(5)
cstate.append(5)
else:
cstate.append(0)
cstate.append(0)
ctime.append(pylab.date2num(dateutil.parser.parse(cooling_time[-1])))
ctime.append(pylab.date2num(dateutil.parser.parse(self.envtime3[-1])))
ax.plot_date(ctime, cstate, marker='', linestyle='-', label='cooling', color='magenta')
ax.legend(bbox_to_anchor=(1.0001, 1), loc=2, borderaxespad=0.,numpoints=1)
leg = ax.get_legend()
#leg.get_frame().set_alpha(0.5)
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
colors_ = ['red','green']
for color,text in zip(colors_,leg.get_texts()):
text.set_color(color)
#Schlupf auf zweiter y-Achse rechts
ax2 = ax.twinx()
ax2.plot_date(s[:min_l], slip, marker='.',markersize=2, linestyle='', label='slip', markeredgecolor='blue',color='blue')
ax2.set_ylabel('Slip in [Hz]', size='x-small', color='blue')
for tl in ax2.get_yticklabels():
tl.set_color('blue')
ax2.set_ylim(min(slip)-2.,max(slip)+2.)
ax.set_xlim(prev_xlims_min,prev_xlims_max)
ax.set_xticklabels([])
try:
hoursum='%2.1fh'%(len(self.envtime2)/60.)
except:
hoursum='n.a.'
plt.title('slip and mean oil temperature T0: %2.1f grad C '%mean(self.t0_temp)+ ' - system run time:'+hoursum, size='small')
else:
1
#Schlupf allein wenn keine Öltemeratur vorhanden
ax2 = fig.add_subplot(6,1,3)
try:
ax2.plot_date(s[:min_l], slip, marker='.',markersize=2, linestyle='', label='slip', markeredgecolor='blue',color='blue')
ax2.set_ylabel('Slip in [Hz]', size='x-small', color='blue')
for tl in ax2.get_yticklabels():
tl.set_color('blue')
ax2.set_ylim(min(slip)-2.,max(slip)+2.)
ax2.set_xlim(prev_xlims_min,prev_xlims_max)
ax2.set_xticklabels([])
except:
print 'error printing slip plot!'
plt.title('slip', size='small')
#### Tube angulation/SID over time (+ Tube position for B)
ax = fig.add_subplot(6,1,4)
try:
if self.myXEvent.SystemType=='Robot Stand':
xxtime = [dateutil.parser.parse(s) for s in scu_224_time]
s = pylab.date2num(xxtime)
ax.plot_date(s, alpha_orb_rob, marker='.', linestyle='-',linewidth=1,color='red',label='tube angle')
#ax.plot_date(s, scu_cran , marker='.', linestyle='-',linewidth=1,color='red',label='CRAN')
#ax.plot_date(s, scu_rao, marker='.', linestyle='-',linewidth=1,color='green',label='RAO')
else: #all other stands
xxtime = [dateutil.parser.parse(s) for s in scu_time]
s = pylab.date2num(xxtime)
ax.plot_date(s, alpha_orb, marker='.', linestyle='-',linewidth=1,color='red',label='tube angle')
if self.plane=='B':
ax.plot_date(s, scu_gantry_long, marker='.', linestyle='-',linewidth=1,color='green',label='Gantry_Long')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y %H:%M'))
ax.set_xlim(prev_xlims_min,prev_xlims_max)
ax.set_xticklabels([])
ax.set_ylim(80,130)
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
if self.plane=='B':
ax.set_ylim(-250,180)
ax.set_ylabel(u'Angulation in [°]/Plane B Pos in [cm]', size='x-small')
else:
ax.set_ylim(-180,180)
ax.set_ylabel(u'Angulation in [°]', size='x-small')
xxtime = [dateutil.parser.parse(s) for s in scu_time]
s = pylab.date2num(xxtime)
ax2 = ax.twinx()
ax2.plot_date(s, scu_sid, marker='.',markersize=1, linestyle='-',linewidth=1,color='blue',label='SID',alpha=0.3)
ax2.set_ylabel('SID in [cm]', size='x-small', color='blue')
ax2.set_ylim(80,130)
for tl in ax2.get_yticklabels():
tl.set_color('blue')
ax2.set_xlim(prev_xlims_min,prev_xlims_max)
ax.legend(bbox_to_anchor=(1.0001, 1), loc=2, borderaxespad=0.,numpoints=1)
leg = ax.get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('Tube geometry data (system type: '+self.myXEvent.SystemType+'); vertical tube time: %4.1f min'%(vertical_tube_time),fontsize='small')
except:
True
###start stops arcings ...####
ax = fig.add_subplot(6,1,5)
#power on/off
if len(power_on)>0 and len(power_off)>0:
xxtime = [dateutil.parser.parse(z) for z in power_on]
p_on_val = [3 for z in power_on]
s_power_on = pylab.date2num(xxtime)
xxtime = [dateutil.parser.parse(z) for z in power_off]
p_off_val = [6 for z in power_off]
s_power_off = pylab.date2num(xxtime)
ax.plot_date(s_power_on, p_on_val , marker='d',markersize=4, linestyle='',color='black',markerfacecolor='white', alpha=0.5,label='Power on')
ax.plot_date(s_power_off,p_off_val, marker='o',markersize=4, linestyle='',color='black', alpha=0.5,label='Power off')
#service start/stop
if len(service_start)>0 and len(service_stop)>0:
xxtime = [dateutil.parser.parse(z) for z in service_start]
ser_on_val = [9 for z in service_start]
s_ser_on = pylab.date2num(xxtime)
xxtime = [dateutil.parser.parse(z) for z in service_stop]
ser_off_val = [12 for z in service_stop]
s_ser_off = pylab.date2num(xxtime)
ax.plot_date(s_ser_on, ser_on_val , marker='s',markersize=4, linestyle='',color='black',markerfacecolor='white', alpha=0.5,label='Service start')
ax.plot_date(s_ser_off,ser_off_val, marker='^',markersize=4, linestyle='',color='black', alpha=0.5,label='Service stop')
y_pos=24
i_=0
for pun_err_type in sorted(PUN_ERR.keys()):
if len(PUN_ERR[pun_err_type])>0:
if pun_err_type=='Err_7110_CAN_DATA_(A100)_normal_limits' or pun_err_type=='Err_7111_CAN_DATA_(A100)_reduced_limits':continue
i_+=1
Err_val=[y_pos+i_*2 for z in PUN_ERR[pun_err_type]]
Err_time=pylab.date2num(PUN_ERR[pun_err_type])
marker = markers.next()
color=colors.next()
if pun_err_type=='Warn_5016_SCAN_WARNING':
arc_val = [25 for z in Err_val]
marker='*'
color='blue'
ax.plot_date(Err_time,Err_val, marker=marker,markersize=4, linestyle='',color=color, alpha=0.5,label=pun_err_type)
#Tube Adjust
if len(TUBE_ADJUST)>0:
#xxtime = [dateutil.parser.parse(z) for z in ERR5022_INTERMEDIATE_CIRCUIT_VOLTAGE_ERROR]
TUBE_ADJUST_val = [15 for z in TUBE_ADJUST]
TUBE_ADJUST_time = pylab.date2num(TUBE_ADJUST)
ax.plot_date(TUBE_ADJUST_time,TUBE_ADJUST_val, marker='p',markersize=4, linestyle='',color='red',label='TUBE_ADJUST')
#TUBE_CONDITIONING
if len(TUBE_CONDITIONING)>0:
TUBE_CONDITIONING_val = [18 for z in TUBE_CONDITIONING]
TUBE_CONDITIONING_time = pylab.date2num(TUBE_CONDITIONING)
ax.plot_date(TUBE_CONDITIONING_time,TUBE_CONDITIONING_val, marker='s',markersize=4, linestyle='',color='cyan',label='TUBE_CONDITIONING')
#LESS_FRAMES (3D Problem)
if len(LESS_FRAMES)>0:
LESS_FRAMES_val = [21 for z in LESS_FRAMES]
LESS_FRAMES_time = pylab.date2num(LESS_FRAMES)
ax.plot_date(LESS_FRAMES_time,LESS_FRAMES_val, marker='s',markersize=4, linestyle='',color='black',label='3D Abort')
#bypass_fluoro
if len(bypass_fl)>0:
bypass_fl_val = [24 for z in bypass_fl]
bypass_fl_time = pylab.date2num(bypass_fl)
ax.plot_date(bypass_fl_time,bypass_fl_val, marker='s',markersize=4, linestyle='',color='green',label='Bypass FL')
#FPGA_Error
if len(FPGA_Error)>0:
FPGA_Error_val = [19 for z in FPGA_Error]
ax.plot_date(FPGA_Error,FPGA_Error_val, marker='s',markersize=4, linestyle='',color='blue',label='FPGA_Error')
#marker=r"$ {} $".format(item[0]), edgecolors='none' )
try:
ax.set_xlim(prev_xlims_min,prev_xlims_max)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_ylim(0,66)
ax.grid(True)
ax.legend(bbox_to_anchor=(1.0001, 1), loc=2, borderaxespad=0.,numpoints=1, handlelength=0 )
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
except:
True
#### HU over time
ax = fig.add_subplot(6,1,6)
if len(all_HU_time)>0:
xxtime = [dateutil.parser.parse(s) for s in all_HU_time]
s = pylab.date2num(xxtime)
ax.plot_date(s, all_HU, marker='.', linestyle='-',linewidth=1,color='blue',label='HU')
t_3D_good=[]
val_3D_good=[]
t_3D_bad=[]
val_3D_bad=[]
for i,x in enumerate(self.myXEvent._3Dmode):
if x!='no3d':
if abs(self.myXEvent.scu_base_rot[i])>30:
t_3D_bad.append(TIME[i])
val_3D_bad.append(50)
else:
t_3D_good.append(TIME[i])
val_3D_good.append(50)
xxtime = [dateutil.parser.parse(s) for s in t_3D_bad]
s_bad = pylab.date2num(xxtime)
xxtime = [dateutil.parser.parse(s) for s in t_3D_good]
s_good = pylab.date2num(xxtime)
ax.plot_date(s_good,val_3D_good , marker='o', linestyle='',color='green', alpha=0.5,label='3D headside('+str(len(s_good))+')')
ax.plot_date(s_bad ,val_3D_bad , marker='s', linestyle='',color='red', alpha=0.5,label='3D lateral('+str(len(s_bad))+')')
ax.set_ylabel('HU in percent', size='x-small')
ax.set_xlabel('Time', size='x-small')
ax.grid(True)
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y\n%H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
ax.set_xlim(prev_xlims_min,prev_xlims_max)
ax.set_ylim(0,max(60,max(all_HU)+10))
#
ax.legend(loc='upper right', borderaxespad=0.,numpoints=1, handlelength=0 ) #bbox_to_anchor=(1.0001, 0),
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize='x-small')
plt.title('HU vs time / 3D Events',fontsize='small')
#------------------
#fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=1.3)
##Tube SNs
fig.text(0.85, 0.95,"Tubes", fontweight='bold', fontsize=8)
offset=1
old_SN='n.a.'
for (date,SN,BE) in self.TubeSerialNumList:
if SN!=old_SN:
fig.text(0.85, 0.95-offset*0.01,date+' : '+SN, fontsize=8)
old_SN=SN
offset+=1
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part18'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(TIME))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(fromDate)+' End: '+str(toDate)+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr, horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if(self.cb_EnvLog.GetValue()):
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p3.png')
plt.close()
#### page 4####
if self.cb_enh_env.GetValue():
fig = plt.figure(figsize=(14,19))
i=1
filled_params=[]
for key in self.env_params.keys():
if len(self.env_timestamp[key])>0:
filled_params.append(key)
numkeys=len(filled_params)
for key in filled_params:
ax = fig.add_subplot(numkeys,1,i)
label_tmp=str(key).replace('plane',self.plane).replace('(','').replace(')','').replace(',','\n')+'/['+self.env_params[key]+']'
ax.plot_date(self.env_timestamp[key], self.env_val[key], marker=None, linestyle='-',linewidth=1,color='blue',label=label_tmp)
try:
ax.set_xlim(prev_xlims_min,prev_xlims_max)
if i<numkeys:
ax.set_xticklabels([])
else:
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%d.%m.%Y\n%H:%M'))
labels = ax.get_xticklabels()
setp(labels, rotation=90, fontsize=8)
ax.grid(True)
plt.rcParams.update({'font.size': 6})
ax.legend(bbox_to_anchor=(1.0001, 1), loc=2, borderaxespad=0.,numpoints=1, handlelength=0 )
leg = plt.gca().get_legend()
ltext = leg.get_texts() # all the text.Text instance in the legend
plt.setp(ltext, fontsize=7)
start, stop = ax.get_ylim()
num_ticks=3
yres=(stop-start)/num_ticks
ticks = np.round(np.arange(start, stop + yres, yres),1)
ax.set_yticks(ticks)
i+=1
except:
True
fig.text(0.5, 0.98,'XA'+str(self.myXEvent.SN)+' part18'+' Radiation events on plane '+str(self.plane)+':'+' '+str(len(TIME))+' ('+str(len(total_events))+' total)'+' Days: '+str(day_total)+' Start: '+str(fromDate)+' End: '+str(toDate)+'\n System SW:'+self.myXEvent.SW[-1][0]+' Tube Serial Number:'+self.TubeSerialNum+' Tube Part Number:'+self.MatrNr, horizontalalignment='center', verticalalignment='center')
self.label_4 = wx.StaticText(self, -1, "", pos=(100,self.GetSize().GetHeight()-55))
fig.text(0.5, 0.02,bottomlinestr+EAversion, horizontalalignment='center', verticalalignment='center',fontsize=10)
if(self.cb_EnvLog.GetValue()):
if (self.cb_png.GetValue()==False):
pdf.savefig(fig)
else:
plt.savefig(name[:-3]+'_p4.png')
plt.close()
if (self.cb_png.GetValue()==False):
pdf.close()
# end of class MyFrame
###############################################################################################################################
def parseXMLTubeProm(numFoken, tubeprom_filename):
if numFoken==3:
foken=('small','large','micro')
else:
foken=('small','large')
try:
tree=etree.parse(tubeprom_filename)
except:
return False
#durchgriffstabelle
xrayVoltage={}
maxCurrAcq={}
maxCurrFluoro={}
focusDepending = tree.getroot().find("Common").find("FocusDepending")
for focusType in foken:
for child in focusDepending.iterchildren():
if (focusType == child.get("FocusType")):
node_type = child.find("FocusTableData").find("MaxPowerTable")
xrayVoltage_temp = node_type.find("XrayVoltage").text.split()
maxCurrAcq_temp = node_type.find("MaxCurrAcq").text.split()
maxCurrFluoro_temp = node_type.find("MaxCurrFluoro").text.split()
xrayVoltage[focusType] = [int(x) for x in xrayVoltage_temp]
maxCurrAcq[focusType] = [int(x) for x in maxCurrAcq_temp]
maxCurrFluoro[focusType] = [int(x) for x in maxCurrFluoro_temp]
#serienbelastungstabelle
myDutyCycle= []
mySceneTime = []
SerialLoadTable={}
SerialLoadTable200={}
for focusType in foken:
mySceneTime=[]
for child in focusDepending.iterchildren():
if (focusType == child.get("FocusType")):
node_type = child.find("FocusTableData").find("SerialLoadTable")
temp = node_type.find("DutyCycle").text.split()
myDutyCycle=[]
for dc in temp:
myDutyCycle.append(int(dc))
node_elements = node_type.findall("element")
dimX = int(myDutyCycle[-1]) + 1 #value of array
dimY = int(node_elements[-1].get("SceneTime")) + 1 #value of array
mySerialLoadTable = numpy.zeros( (dimY, dimX) )
i = 0
for element in node_elements:
SceneTime = element.get("SceneTime")
data = element.get("data").split()
mySceneTime.append(int(SceneTime))
i = i+1
for cycle, item in zip(myDutyCycle, data):
mySerialLoadTable[int(SceneTime)][int(cycle)] = int(item)
SerialLoadTable[focusType]=mySerialLoadTable
#const load
PulseDuration={}
ConstantLoad={}
for focusType in foken:
for child in focusDepending.iterchildren():
if (focusType == child.get("FocusType")):
node_type = child.find("FocusTableData").find("ConstantLoadTable")
PulseDuration_temp = node_type.find("PulseDuration").text.split()
ConstantLoad_temp = node_type.find("ConstantLoad").text.split()
PulseDuration[focusType] = [int(x) for x in PulseDuration_temp]
ConstantLoad[focusType] = [int(x) for x in ConstantLoad_temp]
if numFoken==3:
mySerialLoadTable = numpy.zeros( (dimY, dimX) )
SerialLoadTable200['small']= mySerialLoadTable
SerialLoadTable200['large']= mySerialLoadTable
SerialLoadTable200['micro']= mySerialLoadTable
else: #2F Gigalix
mySerialLoadTable = numpy.zeros( (dimY, dimX) )
SerialLoadTable200['small']= mySerialLoadTable
SerialLoadTable200['large']= mySerialLoadTable
return (SerialLoadTable200,SerialLoadTable,myDutyCycle,mySceneTime,PulseDuration,ConstantLoad,xrayVoltage,maxCurrAcq,maxCurrFluoro)
######
def parseXMLTubeProm_special(numFoken, spec_tubeprom_filename):
if numFoken==3:
foken=('small','large','micro')
else:
foken=('small','large')
kVs={}
tube_currents={}
heat_current={}
try:
tree=etree.parse(spec_tubeprom_filename)
except:
print 'Error reading tube prom '+spec_tubeprom_filename
return 'False'
focusDepending = tree.getroot().find("TubeSpecific").find("FocusDepending")
for focusType in foken:
tube_currents[focusType]=[]
heat_current[focusType]=[]
for child in focusDepending.iterchildren():
if (focusType == child.get("FocusType")):
node_type = child.find("EmissionTable")
temp_v=node_type.find('XrayVoltage').text.split()
kVs[focusType]=[int(x) for x in temp_v]
for child2 in node_type.iterchildren():
try:
tube_currents[focusType].append(int(child2.get('XrayCurrent')))
cur_data=child2.get('data').split()
heat_current[focusType].append([int(x) for x in cur_data])
except:
True
return (kVs,tube_currents,heat_current)
###############################################################
def analyze_examsets(lines):
debug=0
lines=lines.split('\n')
num_acq=0
num_fl=0
num_rm=0
num_alt=0
ACQ_set={}
acq_idx={}
FL_set={}
fl_idx={}
RM_set={}
rm_idx={}
ALT_set={}
alt_idx={}
ACQ=False
FL=False
RM=False
ALT=False
OGP_END=False
acq_params=[]
fl_params=[]
rm_params=[]
alt_params=[]
ogp_diff={}
rx = re.compile('([\t]+)')
# ^^ fill in the characters here.
"""csv_fp=open(examset_filename,'r')
csv_data = csv.reader(csv_fp, delimiter='\t')
for line in csv_data:
print line
"""
line=u''
for k in range(len(lines)):
line=lines[k].lstrip()
line=line.replace(u'\xb5','_')
#print k, line
if len(line)>0:
if line[:7]=='ACQUIRE' and ACQ==False:
#print k, line
ogp_cluster=re.sub(r"(\t+)", r"\t", lines[k-1].strip()).split('\t')
line=re.sub(r"\t\t(\t+)", r"\t\t", line)
t1= line[8:].strip().split('\t\t')
for i,t in enumerate(t1):
#print i, t
s1=t.strip().split('\t')
for j,s in enumerate(s1):
dat2=re.search(r'(.+)\s*(\(\d+,\d+\))',s.strip())
#print s
try:
acq_name=dat2.group(1).strip()
except:
acq_name='n a'
if acq_name in ACQ_set.keys():
ACQ_set[acq_name,'exists']+=1
else:
ACQ_set[acq_name,'exists']=1
ACQ_set[acq_name]={}
acq_idx[num_acq]=acq_name
num_acq+=1
ACQ=True
OGP_substart=[]
OGP_subend=[]
OGP_idx={}
num_acq=0
idx=0
line=lines[k+1].lstrip()
t1= line.strip().split('\t\t')
opg_param=t1[0].strip()
l1=line.split('\t')
for i in range(2,len(l1)):
if l1[i-1]=='' and l1[i]!='' and l1[i]!='\n' and l1[i]!='\r':
OGP_substart.append(i)
try:
if l1[i-1]!='' and (l1[i]=='' or l1[i]=='\n' or l1[i]=='\r'):
OGP_subend.append(i)
#print l1[OGP_substart[-1]:OGP_subend[-1]]
except:
True
for j in range(len(OGP_substart)):
if debug:print ogp_cluster[j]
sets=l1[OGP_substart[j]:OGP_subend[j]]
ACQ_set[acq_idx[num_acq]]={}
for set_i in sets:
if debug:print acq_idx[num_acq],opg_param, set_i
(ACQ_set[acq_idx[num_acq]])[opg_param]=set_i
num_acq+=1
if ACQ==True and line.strip()[0]=='(':
ACQ=False
if ACQ==True and line.strip()[0:3]!='E X':
if line.find('phase: fps / sec / Wait')>-1:
continue
offset=0
num_acq=0
line=lines[k].lstrip()
l1= ['']+line.split('\t')
opg_param=l1[1].strip().replace('[S]','').replace('[--]','').replace(u'\xb5','_').replace(u'\xe5','e').replace(u'\xe9','e')
#print opg_param
v=0
acq_params.append(opg_param)
for j in range(len(OGP_substart)):
sets=l1[OGP_substart[j]-offset:OGP_subend[j]-offset]
for set_i in sets:
#print opg_param, set_i
set_i=set_i.replace('[S]','').replace('[--]','')
if opg_param == 'Focus' and set_i not in ['s','L']:set_i='m' #Unicode Problems
if opg_param in ['3D Start Position' , '3D Angle', '3D Angle Step']:
set_i=re.search(r'([0-9\.]+|)',set_i).group(1)
if ACQ_set[acq_idx[v],'exists']>1:
w=[u for u in acq_idx.keys() if acq_idx[u]==acq_idx[v]][0] #get index of first OGP
if v>w and (ACQ_set[acq_idx[w]])[opg_param]!=set_i: #compare actual OGP param with param of first OGP
ogp_diff[acq_idx[v],opg_param]=True
(ACQ_set[acq_idx[v]])[opg_param]=set_i
v+=1
#Fluoro
if line[:6]=='FLUORO' and FL==False:
#print line
ogp_cluster=re.sub(r"(\t+)", r"\t", lines[k-1].strip()).split('\t')
line=re.sub(r"\t\t(\t+)", r"\t\t", line)
t1= line[8:].strip().split('\t\t')
for i,t in enumerate(t1):
#print i, t
s1=t.strip().split('\t')
for j,s in enumerate(s1):
dat2=re.search(r'(.+)\s*(\(\d+,\d+\))',s.strip())
try:
fl_name=dat2.group(1).strip()
except:
fl_name='n a'
if fl_name in FL_set.keys():
FL_set[fl_name,'exists']+=1
else:
FL_set[fl_name,'exists']=1
FL_set[fl_name]={}
fl_idx[num_fl]=fl_name
num_fl+=1
FL=True
OGP_substart=[]
OGP_subend=[]
OGP_idx={}
num_fl=0
idx=0
line=lines[k+1].lstrip()
t1= line.strip().split('\t\t')
opg_param=t1[0].strip()
l1=line.split('\t')
for i in range(2,len(l1)):
if l1[i-1]=='' and l1[i]!='' and l1[i]!='\n' and l1[i]!='\r':
OGP_substart.append(i)
try:
if l1[i-1]!='' and (l1[i]=='' or l1[i]=='\n' or l1[i]=='\r'):
OGP_subend.append(i)
#print l1[OGP_substart[-1]:OGP_subend[-1]]
except:
True
for j in range(len(OGP_substart)):
sets=l1[OGP_substart[j]-offset:OGP_subend[j]-offset]
FL_set[fl_idx[num_fl]]={}
if debug: print ogp_cluster[j]
for set_i in sets:
if debug:print num_fl,fl_idx[num_fl],opg_param, set_i
(FL_set[fl_idx[num_fl]])[opg_param]=set_i
num_fl+=1
if FL==True and line.strip()[0]=='(':
FL=False
if FL==True and line.strip()[0:3]!='E X':
#print k, line
if line.find('phase: fps / sec / Wait')>-1:
continue
line=lines[k].lstrip()
l1= ['']+line.split('\t')
opg_param=l1[1].strip().replace('[S]','').replace('[--]','').replace(u'\xb5','_').replace(u'\xe5','e').replace(u'\xe9','e')
v=0
fl_params.append(opg_param)
for j in range(len(OGP_substart)):
sets=l1[OGP_substart[j]-offset:OGP_subend[j]-offset]
for set_i in sets:
set_i=set_i.replace('[S]','').replace('[--]','')
if opg_param == 'Focus' and set_i not in ['s','L']:set_i='m' #Unicode Problems
if FL_set[fl_idx[v],'exists']>1:
w=[u for u in fl_idx.keys() if fl_idx[u]==fl_idx[v]][0] #get index of first OGP
if v>w and (FL_set[fl_idx[w]])[opg_param]!=set_i: #compare actual OGP param with param of first OGP
ogp_diff[fl_idx[v],opg_param]=True
(FL_set[fl_idx[v]])[opg_param]=set_i
v+=1
#Roadmap
if line[:7]=='ROADMAP' and RM==False:
ogp_cluster=re.sub(r"(\t+)", r"\t", lines[k-1].strip()).split('\t')
line=re.sub(r"\t\t(\t+)", r"\t\t", line)
t1= line[8:].strip().split('\t\t')
for i,t in enumerate(t1):
#print i, t
s1=t.strip().split('\t')
for j,s in enumerate(s1):
dat2=re.search(r'(.+)\s*(\(\d+,\d+\))',s.strip())
try:
rm_name=dat2.group(1).strip()
except:
rm_name='n a'
if rm_name in RM_set.keys():
RM_set[rm_name,'exists']+=1
else:
RM_set[rm_name,'exists']=1
RM_set[rm_name]={}
rm_idx[num_rm]=rm_name
num_rm+=1
RM=True
OGP_substart=[]
OGP_subend=[]
OGP_idx={}
num_rm=0
idx=0
line=lines[k+1].lstrip()
t1= line.strip().split('\t\t')
opg_param=t1[0].strip()
#print opg_param
l1=line.split('\t')
for i in range(2,len(l1)):
if l1[i-1]=='' and l1[i]!='' and l1[i]!='\n' and l1[i]!='\r':
OGP_substart.append(i)
try:
if l1[i-1]!='' and (l1[i]=='' or l1[i]=='\n' or l1[i]=='\r'):
OGP_subend.append(i)
#print l1[OGP_substart[-1]:OGP_subend[-1]]
except:
True
for j in range(len(OGP_substart)):
if debug: print ogp_cluster[j]
sets=l1[OGP_substart[j]:OGP_subend[j]]
RM_set[rm_idx[num_rm]]={}
for set_i in sets:
if debug:print rm_idx[num_rm],opg_param, set_i
(RM_set[rm_idx[num_rm]])[opg_param]=set_i
num_rm+=1
if RM==True and line.strip()[0]=='(':
RM=False
if RM==True and line.strip()[0:3]!='E X':
#print k,line
if line.find('phase: fps / sec / Wait')>-1:
continue
line=lines[k].lstrip()
l1= ['']+line.split('\t')
opg_param=l1[1].strip().replace('[S]','').replace('[--]','').replace(u'\xb5','_').replace(u'\xe5','e').replace(u'\xe9','e')
#print opg_param
v=0
rm_params.append(opg_param)
for j in range(len(OGP_substart)):
sets=l1[OGP_substart[j]:OGP_subend[j]]
for set_i in sets:
set_i=set_i.replace('[S]','').replace('[--]','')
if opg_param == 'Focus' and set_i not in ['s','L']:set_i='m' #Unicode Problems
if RM_set[rm_idx[v],'exists']>1:
w=[u for u in rm_idx.keys() if rm_idx[u]==rm_idx[v]][0] #get index of first OGP
if v>w and (RM_set[rm_idx[w]])[opg_param]!=set_i: #compare actual OGP param with param of first OGP
ogp_diff[rm_idx[v],opg_param]=True
(RM_set[rm_idx[v]])[opg_param]=set_i
v+=1
#Alternative Acquisition
if line[:7]=='ALT-ACQ' and ALT==False:
ogp_cluster=re.sub(r"(\t+)", r"\t", lines[k-1].strip()).split('\t')
line=re.sub(r"\t\t(\t+)", r"\t\t", line)
t1= line[8:].strip().split('\t\t')
for i,t in enumerate(t1):
#print i, t
s1=t.strip().split('\t')
for j,s in enumerate(s1):
dat2=re.search(r'(.+)\s*(\(\d+,\d+\))',s.strip())
try:
alt_name=dat2.group(1).strip()
except:
alt_name='n a'
if alt_name in ALT_set.keys():
ALT_set[alt_name,'exists']+=1
else:
ALT_set[alt_name,'exists']=1
ALT_set[alt_name]={}
alt_idx[num_alt]=alt_name
num_alt+=1
ALT=True
OGP_substart=[]
OGP_subend=[]
OGP_idx={}
num_alt=0
idx=0
line=lines[k+1].lstrip()
t1= line.strip().split('\t\t')
opg_param=t1[0].strip()
#print opg_param
l1=line.split('\t')
for i in range(2,len(l1)):
if l1[i-1]=='' and l1[i]!='' and l1[i]!='\n' and l1[i]!='\r':
OGP_substart.append(i)
try:
if l1[i-1]!='' and (l1[i]=='' or l1[i]=='\n' or l1[i]=='\r'):
OGP_subend.append(i)
#print l1[OGP_substart[-1]:OGP_subend[-1]]
except:
True
for j in range(len(OGP_substart)):
if debug:print ogp_cluster[j]
sets=l1[OGP_substart[j]:OGP_subend[j]]
ALT_set[alt_idx[num_alt]]={}
for set_i in sets:
if debug:print alt_idx[num_alt],opg_param, set_i
(ALT_set[alt_idx[num_alt]])[opg_param]=set_i
num_alt+=1
if ALT==True and line.strip()[0]=='(':
ALT=False
if ALT==True and line.strip()[0:3]!='E X':
if line.find('phase: fps / sec / Wait')>-1:
continue
line=lines[k].lstrip()
l1= ['']+line.split('\t')
opg_param=l1[1].strip().replace('[S]','').replace('[--]','').replace(u'\xb5','_').replace(u'\xe5','e').replace(u'\xe9','e')
#print opg_param
v=0
alt_params.append(opg_param)
for j in range(len(OGP_substart)):
sets=l1[OGP_substart[j]:OGP_subend[j]]
for set_i in sets:
set_i=set_i.replace('[S]','').replace('[--]','')
if opg_param == 'Focus' and set_i not in ['s','L']:set_i='m' #Unicode Problems
if ALT_set[alt_idx[v],'exists']>1:
w=[u for u in alt_idx.keys() if alt_idx[u]==alt_idx[v]][0] #get index of first OGP
if v>w and (ALT_set[alt_idx[w]])[opg_param]!=set_i: #compare actual OGP param with param of first OGP
ogp_diff[alt_idx[v],opg_param]=True
(ALT_set[alt_idx[v]])[opg_param]=set_i
v+=1
return (ACQ_set,FL_set,RM_set,ALT_set,acq_params,fl_params,rm_params,alt_params,ogp_diff,acq_idx,fl_idx,rm_idx,alt_idx)
#--------------------------------------------------------------
try:
1#from EA_IC import *
except:
print "skipping import"
if __name__ == "__main__":
if len(sys.argv)>1:
print "x: " + str(sys.argv[1])
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "",params=sys.argv[1])
app.SetTopWindow(frame_1)
app.MainLoop()
else:
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "",params=None)
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
###########################################################ENF####################################################################
"""todos VD10
W 19-Nov-14 14:06:29 44288 AX_PUD <I>Info_AD00_Adjust_Info </I>
Time: 19.11.2014, 14:06:29, Process: C:\AXIOM\Service\bin\Rep.exe_2132,
Text: (19.11.2014 14:06:29) ANG-B SET: [0xAD00]PL A100G (SW:VG03Q; HW:VG01C): TubAdj VD00A Giga 125/40/86
W 08-Sep-14 08:01:52 2121 AX_ACU <I>LOG, Injection control: 1 </I>
Time: 8.9.2014, 08:01:52, Process: C:\AXIOM\Service\bin\Rep.exe_2140,
Text: (08.09.2014 08:01:52) ACU-B SET: [00198]CAcuInjectorIoAccess,84|Injector started, ULI: 2
W 08-Sep-14 08:01:52 2121 AX_ACU <I>LOG, Injection control: 2 </I>
Time: 8.9.2014, 08:01:52, Process: C:\AXIOM\Service\bin\Rep.exe_2140,
Text: (08.09.2014 08:01:52) ACU-A SET: [00212]CAcuInjectorControlXrayRel,116|X-ray enabled by injector,
I 19-Jun-14 08:18:01 1221 AX_SCU <I>ULI 1: EMERGENCY BUTTON ACTIVE </I>
Time: 19.6.2014, 08:18:01, Process: C:\AXIOM\Service\bin\Rep.exe_628,
Text: (19.06.2014 08:18:02) SCU SET: [01221]ULI 1 Emergency button is active|0,no src
W 18-Jun-14 12:32:40 0 AX_SCU <I>LOG </I>
Time: 18.6.2014, 12:32:40, Process: C:\AXIOM\Service\bin\Rep.exe_1404,
Text: (18.06.2014 12:32:37) SCU RESET: [00200]No Longer Reduce Speed out of Table range|377,ParkingController.cpp
W 18-Jun-14 12:32:42 419 AX_SCU <I>Collision with wall </I>
Time: 18.6.2014, 12:32:42, Process: C:\AXIOM\Service\bin\Rep.exe_1404,
Text: (18.06.2014 12:32:39) SCU SET: [00419]units 43 114|0,no src
"""
log analysis Werzeug aus Deutschland Dr
最新推荐文章于 2021-07-01 16:54:58 发布