diff --git a/fixhdr/LibTrace.py b/fixhdr/LibTrace.py index eebf3dbde0aa6a7350f17e9fe6b68c70ae8e5a49..511fedd199782d3e65323ee23e6ccb3c5f3233f8 100755 --- a/fixhdr/LibTrace.py +++ b/fixhdr/LibTrace.py @@ -42,7 +42,8 @@ # added blockette 2000 to Mseed class # Blockettes with BTime time definitions now pass the BTime # as a tuple within the blk list -# changed unpack formats to use native byte order with standard size & alignment +# changed unpack formats to use native byte order with standard size & +# alignment ########################## # 2005.035 @@ -51,9 +52,9 @@ # # added check for endianess in Mseed & Segy classes, self.ByteOrder # changed all unpack formats to reflect above change in Mseed & Segy classes -# NOTE: for mseed it is possible to have mixed endianess (e.g. little-endian headers -# and big-endian data). At this time, this library does not handle data and makes -# the determination of endianess based soley on the header. +# NOTE: for mseed it is possible to have mixed endianess (e.g. little-endian +# headers and big-endian data). At this time, this library does not handle data +# and makes the determination of endianess based soley on the header. ########################## # 2005.138 @@ -61,7 +62,8 @@ # Author: bcb # # added -# Mseed.Pad, Mseed.FlagStrtoInt, Mseed.WriteFixedHdr and all of Mseed.Writeblk??? +# Mseed.Pad, Mseed.FlagStrtoInt, Mseed.WriteFixedHdr and all of +# Mseed.Writeblk??? # fixed improper casting of Time Correction in Mseed.fixedhdr to signed long ########################## # 2006.179 @@ -83,7 +85,7 @@ # Author: bcb # # changed Mseed.__init__ to populate identification header fields -# fixed oversight in handling flags in blk100 reads (forgot to +# fixed oversight in handling flags in blk100 reads (forgot to # implement UbyteToStr # fixed improper handling of res fields in blk100, blk201 and blk400 ########################## @@ -123,17 +125,23 @@ # Bug fix: In Writeblk200/201/300/310/320/390/395/500 when unpack inblk to # variables with time (Year, Day, Hour, Min, Sec, junk, Micro) -import os, string, sys, struct, time +import os +import struct +import sys +import time + SPACE = " " -#VERSION = "2019.025" +# VERSION = "2019.025" + class futils: """ file utilities class """ - def __init__(self,infile): - self.infile = open(infile, 'r+b') + + def __init__(self, infile): + self.infile = open(infile, 'rb') def close(self): self.infile.close() @@ -142,137 +150,160 @@ class futils: return self.infile.tell() ######################################################### + + class FixedHeader: """ - mseed fixhdr + mseed fixhdr """ - #first 20char - textblk=timeblk=sampblk=miscblk=[] - textblk=[] - Serial=DHQual=Res=Stat=Chan=Loc=Net=None + # first 20char + textblk = timeblk = sampblk = miscblk = [] + textblk = [] + Serial = DHQual = Res = Stat = Chan = Loc = Net = None # 20:30 - timeblk=[] - Year=Day=Hour=Min=Sec=Micro=None + timeblk = [] + Year = Day = Hour = Min = Sec = Micro = None # 30:36 - sampblk=[] - NumSamp=SampFact=SampMult=None + sampblk = [] + NumSamp = SampFact = SampMult = None # 36:48 - miscblk=[] - act=io=DataDHQualFL=numblock=timcorr=bdata=bbblock=None + miscblk = [] + act = io = DataDHQualFL = numblock = timcorr = bdata = bbblock = None + ######################################################### + + class Mseed(futils): def __init__(self, infile): """ - initialize file, determine byteorder, sizes, time, and load first fixed header + initialize file, determine byteorder, sizes, time, and load first fixed + header """ - self.type=self.rate=None + self.type = self.rate = None try: - futils.__init__(self,infile) - #local variable to class - self.infileseek=self.infile.seek - self.infilewrite=self.infile.write - self.infileread=self.infile.read - self.sunpack=struct.unpack - self.spack=struct.pack + futils.__init__(self, infile) + # local variable to class + self.infileseek = self.infile.seek + self.infilewrite = self.infile.write + self.infileread = self.infile.read + self.sunpack = struct.unpack + self.spack = struct.pack self.byteorder = self.ByteOrder() if self.byteorder != "unknown": - #otherwise it might be mseed + # otherwise it might be mseed self.type = "mseed" # read 1st fixed header in file - hdrs=self.fixedhdr() - (self.filesize,self.blksize)=self.sizes() - (self.numblocks, odd_size)=divmod(self.filesize,self.blksize) + hdrs = self.fixedhdr() + (self.filesize, self.blksize) = self.sizes() + (self.numblocks, odd_size) = divmod( + self.filesize, self.blksize) if odd_size: pass # starttime of trace self.time = ":".join(map(str, (self.FH.Year, self.FH.Day, self.FH.Hour, self.FH.Min, self.FH.Sec))) - except Exception as e: + except Exception: pass ######################################################### - def isMseed(self) : + + def isMseed(self): """ - determines if processed file is mseed (return 1) or unknown type (return 0) + determines if processed file is mseed (return 1) or unknown type + (return 0) """ - #if we don't know byteorder it must not be mseed - if self.byteorder == "unknown": return 0 - else: return 1 + # if we don't know byteorder it must not be mseed + if self.byteorder == "unknown": + return 0 + else: + return 1 ######################################################### + def idhdr(self): """ trace id info """ - return self.type, self.FH.Stat, self.FH.Chan, self.FH.Loc, self.FH.Net, self.time, self.rate + return (self.type, self.FH.Stat, self.FH.Chan, self.FH.Loc, + self.FH.Net, self.time, self.rate) ######################################################### + def FirstLastTime(self): """ - returns first and last block times in epoch + returns first and last block times in epoch """ - try : - #get first fixed header and calculate beginning epoch + try: + # get first fixed header and calculate beginning epoch btime_str = time.strptime(self.time, '%Y:%j:%H:%M:%S') bepoch = time.mktime(btime_str) + (self.FH.Micro * 0.0001) - #figure out where the end of the file is and read the last fixed header - # and calculate eepoch - (numblocks, odd_size)=divmod(self.filesize, self.blksize) - self.infileseek(-self.blksize,2) + # figure out where the end of the file is and read the last fixed + # header and calculate eepoch + (numblocks, odd_size) = divmod(self.filesize, self.blksize) + self.infileseek(-self.blksize, 2) loc = self.infile.tell() - etime=self.btime2time(loc) + etime = self.btime2time(loc) etime_str = time.strptime(etime, '%Y:%j:%H:%M:%S') eepoch = time.mktime(etime_str) + (self.FH.Micro * 0.0001) - # return bepoch, eepoch except Exception as e: return e + ######################################################### + def tracelength(self): """ returns tracelength in seconds """ - try : - #get first fixed header and calculate beginning epoch - (bepoch, eepoch)=self.FirstLastTime() + try: + # get first fixed header and calculate beginning epoch + (bepoch, eepoch) = self.FirstLastTime() -# #here I have to get the last few samples and calculate how much time is accounted for - self.infileseek(-self.blksize+30,2) - sampblock=self.infileread(2) + # here I have to get the last few samples and calculate how much + # time is accounted for + self.infileseek(-self.blksize + 30, 2) + sampblock = self.infileread(2) fmtstr = self.fmt_order + "H" numsamp = self.sunpack(fmtstr, sampblock)[0] - lastsamples=(numsamp-1)/self.rate - return ((eepoch+lastsamples) - bepoch ) - except Exception as e: + lastsamples = (numsamp - 1) / self.rate + return ((eepoch + lastsamples) - bepoch) + except Exception: pass + ######################################################### - def btime2time(self, seekval=0) : + + def btime2time(self, seekval=0): """ reads file fixed header and returns time string from btime """ - try : - hdrs=self.fixedhdr(seekval) + try: + hdrs = self.fixedhdr(seekval) time = ":".join(map(str, (self.FH.Year, self.FH.Day, self.FH.Hour, self.FH.Min, self.FH.Sec))) return time - except Exception as e: + except Exception: pass + ######################################################### - def idread(self, seekval=0) : + + def idread(self, seekval=0): """ read file as if it is mseed just pulling necessary info from fixed header """ - try : - hdrs=self.fixedhdr(seekval) + try: + hdrs = self.fixedhdr(seekval) - return self.FH.Stat, self.FH.Chan, self.FH.Loc, self.FH.Net,\ - self.rate, self.FH.Year, self.FH.Day, self.FH.Hour, self.FH.Min, self.FH.Sec, self.FH.Micro - except : + return (self.FH.Stat, self.FH.Chan, self.FH.Loc, self.FH.Net, + self.rate, self.FH.Year, self.FH.Day, self.FH.Hour, + self.FH.Min, self.FH.Sec, self.FH.Micro) + except Exception: return + ######################################################### + def calcrate(self): """ this routine assumes that idread has been called first @@ -287,37 +318,38 @@ class Mseed(futils): If Sample rate factor < 0 and Sample rate Multiplier < 0, rate = 1/(Sampfact X Sampmult) """ - sampFact=float(self.FH.SampFact) - sampMult=float(self.FH.SampMult) - if sampFact > 0 and sampMult > 0 : + sampFact = float(self.FH.SampFact) + sampMult = float(self.FH.SampMult) + if sampFact > 0 and sampMult > 0: rate = sampFact * sampMult - elif sampFact > 0 and sampMult < 0 : - rate = -1.0 * (sampFact/sampMult) - elif sampFact < 0 and sampMult > 0 : - rate = -1.0 * (sampMult/sampFact) - elif sampFact < 0 and sampMult < 0 : - rate = 1.0/(sampFact * sampMult) - else : + elif sampFact > 0 and sampMult < 0: + rate = -1.0 * (sampFact / sampMult) + elif sampFact < 0 and sampMult > 0: + rate = -1.0 * (sampMult / sampFact) + elif sampFact < 0 and sampMult < 0: + rate = 1.0 / (sampFact * sampMult) + else: rate = sampFact return rate ######################################################### - def ByteOrder(self, seekval=20) : + + def ByteOrder(self, seekval=20): """ read file as if it is mseed just pulling time info from fixed header and determine if it makes sense unpacked as big endian or little endian """ Order = "unknown" - try : - #seek to timeblock and read + try: + # seek to timeblock and read self.infileseek(seekval) - timeblock=self.infileread(10) - # timeblock=self.TraceBuffer[seekval:seekval+10] + timeblock = self.infileread(10) + # timeblock=self.TraceBuffer[seekval:seekval+10] - #assume big endian + # assume big endian (Year, Day, Hour, Min, Sec, junk, Micro) = \ - self.sunpack('>HHBBBBH',timeblock) - #test if big endian read makes sense + self.sunpack('>HHBBBBH', timeblock) + # test if big endian read makes sense if 1950 <= Year <= 2050 and \ 1 <= Day <= 366 and \ 0 <= Hour <= 23 and \ @@ -326,10 +358,10 @@ class Mseed(futils): Order = "big" self.fmt_order = ">" else: - #try little endian read - (Year, Day, Hour, Min, Sec, junk, Micro)=\ - self.sunpack('<HHBBBBH',timeblock) - #test if little endian read makes sense + # try little endian read + (Year, Day, Hour, Min, Sec, junk, Micro) =\ + self.sunpack('<HHBBBBH', timeblock) + # test if little endian read makes sense if 1950 <= Year <= 2050 and \ 1 <= Day <= 366 and \ 0 <= Hour <= 23 and \ @@ -337,41 +369,45 @@ class Mseed(futils): 0 <= Sec <= 59: Order = "little" self.fmt_order = "<" - except : + except Exception: pass return Order + ######################################################### + def sizes(self, seekval=0): """ Finds Blockette 1000 and returns file size & Data Record Length """ try: - #determine file size - self.infileseek(0,2) - filesize=self.infile.tell() - #proceed to seekval + # determine file size + self.infileseek(0, 2) + filesize = self.infile.tell() + # proceed to seekval self.infileseek(seekval) - #self.infileseek(39) - #assign number of blockettes and offset to next blockette - nblock=self.FH.miscblk[3] - nextblock=self.FH.miscblk[6] - n=0 - #find blockette 1000 + # self.infileseek(39) + # assign number of blockettes and offset to next blockette + nblock = self.FH.miscblk[3] + nextblock = self.FH.miscblk[6] + n = 0 + # find blockette 1000 while n < nblock: self.infileseek(nextblock) - (blktype, newblock)=self.typenxt(nextblock) + (blktype, newblock) = self.typenxt(nextblock) if not blktype: return None, None if blktype == 1000: - (type, next, encode,order,length,res)=self.blk1000(nextblock) + (type, next, encode, order, length, + res) = self.blk1000(nextblock) return filesize, 2**length - nextblock=newblock - n+=1 - except Exception as e: + nextblock = newblock + n += 1 + except Exception: return None, None ######################################################### + def typenxt(self, seekval=0): """ Reads first 4 bytes of blockette @@ -380,25 +416,26 @@ class Mseed(futils): try: self.infileseek(seekval) fmtstr = self.fmt_order + "HH" - (type, next)=self.sunpack(fmtstr, self.infileread(4)) + (type, next) = self.sunpack(fmtstr, self.infileread(4)) - #reset back to beginning of blockette - self.infileseek(-4,1) + # reset back to beginning of blockette + self.infileseek(-4, 1) return type, next - except Exception as e: + except Exception: return None, None ######################################################### + def setEndian(self, endianess=""): """ set format string for endian type """ if endianess == "big": - fmtorderstr=">" + fmtorderstr = ">" elif endianess == "little": - fmtorderstr="<" + fmtorderstr = "<" else: - fmtorderstr=self.fmt_order + fmtorderstr = self.fmt_order return fmtorderstr ######################################################### @@ -426,6 +463,7 @@ class Mseed(futils): # UBYTE 8 Unused for data (required for alignment)( # UWORD 16 .0001 seconds (0-9999) ######################################################### + def fixedhdr(self, seekval=0): """ Reads fixed header of 48 bytes (see SEED manual) @@ -459,8 +497,8 @@ class Mseed(futils): Offset to beginning of data (UWORD, 2) Offset to beginning of next blockette (UWORD, 2) """ - #local variable -# self.sunpack=self.sunpack + # local variable + # self.sunpack=self.sunpack try: del self.FH except Exception as e: @@ -468,43 +506,45 @@ class Mseed(futils): self.FH = FixedHeader() try: self.infileseek(seekval) - fhblk=self.infileread(48) - #station info + fhblk = self.infileread(48) + # station info fmtstr = self.fmt_order + "6scc5s2s3s2s" - self.FH.textblk=self.sunpack(fmtstr,fhblk[0:20]) + self.FH.textblk = self.sunpack(fmtstr, fhblk[0:20]) - #time info + # time info fmtstr = self.fmt_order + "HHBBBBH" - self.FH.timeblk=self.sunpack(fmtstr,fhblk[20:30]) + self.FH.timeblk = self.sunpack(fmtstr, fhblk[20:30]) - #sample info + # sample info fmtstr = self.fmt_order + "Hhh" - self.FH.sampblk=self.sunpack(fmtstr, fhblk[30:36]) + self.FH.sampblk = self.sunpack(fmtstr, fhblk[30:36]) - #misc info + # misc info fmtstr = self.fmt_order + "BBBBlHH" - tmpblk=self.sunpack(fmtstr,fhblk[36:48]) - #decompose tmpblk[0-2] into bit fields, create miscblk + tmpblk = self.sunpack(fmtstr, fhblk[36:48]) + # decompose tmpblk[0-2] into bit fields, create miscblk for i in range(3): self.FH.miscblk = self.UbytetoStr(tmpblk, i) - tmpblk=self.FH.miscblk #recast tmpblk as list + tmpblk = self.FH.miscblk # recast tmpblk as list - (self.FH.Serial, self.FH.DHQual, res, self.FH.Stat, self.FH.Loc, self.FH.Chan, self.FH.Net)\ - =self.FH.textblk - (self.FH.Year, self.FH.Day, self.FH.Hour, self.FH.Min, self.FH.Sec, junk, self.FH.Micro)\ - =self.FH.timeblk + (self.FH.Serial, self.FH.DHQual, res, self.FH.Stat, self.FH.Loc, + self.FH.Chan, self.FH.Net) = self.FH.textblk + (self.FH.Year, self.FH.Day, self.FH.Hour, self.FH.Min, + self.FH.Sec, junk, self.FH.Micro) = self.FH.timeblk (self.FH.NumSamp, self.FH.SampFact, self.FH.SampMult)\ - =self.FH.sampblk - self.rate=self.calcrate() + = self.FH.sampblk + self.rate = self.calcrate() - return self.FH.textblk, self.FH.timeblk, self.FH.sampblk, self.FH.miscblk -# return textblk,timeblk,sampblk,miscblk + return (self.FH.textblk, self.FH.timeblk, self.FH.sampblk, + self.FH.miscblk) + # return textblk,timeblk,sampblk,miscblk - except Exception as e: + except Exception: print("error reading fixed header") pass ######################################################### + def WriteFixedHdr(self, hdrlist, seekval=0, endianess=""): """ Writes fixed header of 48 bytes (see SEED manual) @@ -513,64 +553,66 @@ class Mseed(futils): try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) - #station info - #left justify values - #fmtstr0 = fmtorderstr + "6scc5s2s3s2s" - - SeqNum = self.Pad(hdrlist[0][0], 6) #SeqNum - DQual = hdrlist[0][1] #DataQual - Res = hdrlist[0][2] #Reserved + fmtorderstr = self.setEndian(endianess) + # station info + # left justify values + # fmtstr0 = fmtorderstr + "6scc5s2s3s2s" + + SeqNum = self.Pad(hdrlist[0][0], 6) # SeqNum + DQual = hdrlist[0][1] # DataQual + Res = hdrlist[0][2] # Reserved try: - Stat = self.Pad(hdrlist[0][3], 5).encode() #Stat - Loc = self.Pad(hdrlist[0][4], 2).encode() #Loc - Chan = self.Pad(hdrlist[0][5], 3).encode() #Chan - Net = self.Pad(hdrlist[0][6], 2).encode() #Net + Stat = self.Pad(hdrlist[0][3], 5).encode() # Stat + Loc = self.Pad(hdrlist[0][4], 2).encode() # Loc + Chan = self.Pad(hdrlist[0][5], 3).encode() # Chan + Net = self.Pad(hdrlist[0][6], 2).encode() # Net except AttributeError: - Stat = self.Pad(hdrlist[0][3], 5) #Stat - Loc = self.Pad(hdrlist[0][4], 2) #Loc - Chan = self.Pad(hdrlist[0][5], 3) #Chan - Net = self.Pad(hdrlist[0][6], 2) #Net - - #time info - #fmtstr1 = fmtorderstr + "HHBBBBH" - (Year, Day, Hour, Min, Sec, junk, Micro)=hdrlist[1] - Micro=int(Micro) - - #sample info - #fmtstr2 = fmtorderstr + "Hhh" + Stat = self.Pad(hdrlist[0][3], 5) # Stat + Loc = self.Pad(hdrlist[0][4], 2) # Loc + Chan = self.Pad(hdrlist[0][5], 3) # Chan + Net = self.Pad(hdrlist[0][6], 2) # Net + + # time info + # fmtstr1 = fmtorderstr + "HHBBBBH" + (Year, Day, Hour, Min, Sec, junk, Micro) = hdrlist[1] + Micro = int(Micro) + + # sample info + # fmtstr2 = fmtorderstr + "Hhh" (NumSamp, SampFact, SampMult) = hdrlist[2] - - #misc info - #fmtstr3 = fmtorderstr + "BBBBlHH" + + # misc info + # fmtstr3 = fmtorderstr + "BBBBlHH" (actFlags, ioFlags, dqFlags, numblk, timecor, offsetData, - offsetBlktt)=hdrlist[3] - #convert flag string to integer + offsetBlktt) = hdrlist[3] + # convert flag string to integer actFlags = self.FlagStrtoInt(actFlags) ioFlags = self.FlagStrtoInt(ioFlags) dqFlags = self.FlagStrtoInt(dqFlags) - - #pack fields + + # pack fields fmtstr = fmtorderstr + "6scc5s2s3s2sHHBBBBHHhhBBBBlHH" - - pack_hdr = self.spack( - fmtstr,SeqNum, DQual, Res, Stat, Loc, Chan, Net, - Year, Day, Hour, Min, Sec, junk, Micro, - NumSamp, SampFact, SampMult,actFlags, ioFlags, dqFlags, - numblk, timecor, offsetData, offsetBlktt) - - #write header + + pack_hdr = self.spack(fmtstr, SeqNum, DQual, Res, Stat, Loc, Chan, + Net, Year, Day, Hour, Min, Sec, junk, Micro, + NumSamp, SampFact, SampMult, actFlags, + ioFlags, dqFlags, numblk, timecor, + offsetData, offsetBlktt) + + # write header self.infilewrite(pack_hdr) - + return 48 - except Exception as e: + except Exception: print("error writing fixed header") return 0 ######################################################### + def GetBlk(self, blknum, seekval=0): - ValidBlk=(100,200,201,300,310,320,390,395,400,405,500,1000,1001,2000) - if not blknum in ValidBlk: + ValidBlk = (100, 200, 201, 300, 310, 320, 390, + 395, 400, 405, 500, 1000, 1001, 2000) + if blknum not in ValidBlk: return 0 else: callcmd = "global blk; blk=self.blk%s(%s)" \ @@ -578,13 +620,16 @@ class Mseed(futils): exec(callcmd) return blk + ######################################################### + def PutBlk(self, blknum, indata, endian, seekval=0): """ test for valid blockette, if true write blockette """ - ValidBlk=(100,200,201,300,310,320,390,395,400,405,500,1000,1001,2000) - if not blknum in ValidBlk: + ValidBlk = (100, 200, 201, 300, 310, 320, 390, + 395, 400, 405, 500, 1000, 1001, 2000) + if blknum not in ValidBlk: return 0 else: callcmd = "global bytes_written; "\ @@ -593,18 +638,20 @@ class Mseed(futils): exec(callcmd) return bytes_written + ######################################################### + def blk100(self, seekval=0): """ Sample Rate Blockette 100 (12 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Actual sample rate (FLOAT, 4) - Flags (BYTE, 1) - Reserved (UBYTE, 3) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Actual sample rate (FLOAT, 4) + Flags (BYTE, 1) + Reserved (UBYTE, 3) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHfb3B" @@ -617,12 +664,13 @@ class Mseed(futils): def Writeblk100(self, inblk, seekval=0, endianess=""): """ writes Sample Rate Blockette 100 (12 bytes) - requires tuple inblk=(blkette, nextblk, actrate, flags, res0, res1, res2) + requires tuple inblk=(blkette, nextblk, actrate, flags, res0, res1, + res2) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHfb3B" (blkette, nextblk, actrate, flags, res0, res1, res2) = inblk flags = self.FlagStrtoInt(flags) @@ -631,27 +679,27 @@ class Mseed(futils): res0, res1, res2) self.infilewrite(pack_blk) return 12 - except Exception as e: + except Exception: print("error writing blockette 100") return 0 - ######################################################### + def blk200(self, seekval=0): """ Generic Event Detection Blockette 200 (52 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Signal amplitude (FLOAT, 4) - Signal period (FLOAT,4) - Background estimate (FLOAT,4) - Event detection flags (UBYTE, 1) - Reserved (UBYTE, 1) - Signal onset time (BTime expanded, 10) - Detector Name (CHAR*24) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Signal amplitude (FLOAT, 4) + Signal period (FLOAT,4) + Background estimate (FLOAT,4) + Event detection flags (UBYTE, 1) + Reserved (UBYTE, 1) + Signal onset time (BTime expanded, 10) + Detector Name (CHAR*24) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHfffBB" @@ -666,22 +714,23 @@ class Mseed(futils): tmpblk.append(timeblk) tmpblk = tmpblk + list(blk2) - #apply bit mask to Ubyte + # apply bit mask to Ubyte blk = self.UbytetoStr(tmpblk, 5) return blk ######################################################### + def Writeblk200(self, inblk, seekval=0, endianess=""): """ writes Generic Event Detection Blockette 200 (52 bytes) requires tuple inblk - inblk=(blkette, nextblk, amp, period, bg, flags, \ - Year, Day, Hour, Min, Sec, junk, Micro, charstr) + inblk=(blkette, nextblk, amp, period, bg, flags, + Year, Day, Hour, Min, Sec, junk, Micro, charstr) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHfffBBHHBBBBH24s" (blkette, nextblk, amp, period, bg, flags, @@ -695,30 +744,30 @@ class Mseed(futils): self.infilewrite(pack_blk) return 52 - except Exception as e: + except Exception: print("error writing blockette 200") return 0 - ######################################################### + def blk201(self, seekval=0): """ Murdock Event Detection Blockette 201 (60 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of - header (UWORD, 2) - Signal amplitude (FLOAT, 4) - Signal period (FLOAT,4) - Background estimate (FLOAT,4) - Event detection flags (UBYTE, 1) - Reserved (UBYTE, 1) - Signal onset time (BTime expanded, 10) - Signal-to-noise ration values (UBYTE*6) - Lookback value (UBYTE, 1) - Pick algorithym (UBYTE, 1) - Detector Name (CHAR*24) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of + header (UWORD, 2) + Signal amplitude (FLOAT, 4) + Signal period (FLOAT,4) + Background estimate (FLOAT,4) + Event detection flags (UBYTE, 1) + Reserved (UBYTE, 1) + Signal onset time (BTime expanded, 10) + Signal-to-noise ration values (UBYTE*6) + Lookback value (UBYTE, 1) + Pick algorithym (UBYTE, 1) + Detector Name (CHAR*24) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHfffBB" @@ -733,68 +782,69 @@ class Mseed(futils): tmpblk.append(timeblk) tmpblk = tmpblk + list(blk2) - #apply bit mask to Ubyte + # apply bit mask to Ubyte blk = self.UbytetoStr(tmpblk, 5) return blk ######################################################### + def Writeblk201(self, inblk, seekval=0, endianess=""): """ writes Murdock Event Detection Blockette 201 (60 bytes) requires tuple inblk inblk=(blkette, nextblk, amp, period, bg, flags, res, - Year, Day, Hour, Min, Sec, junk, Micro, - SN0, SN1, SN2, SN3, SN4, SN5, loop, algo, Name) + Year, Day, Hour, Min, Sec, junk, Micro, + SN0, SN1, SN2, SN3, SN4, SN5, loop, algo, Name) """ try: self.infileseek(seekval) fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHfffBBHHBBBBH6BBB24s" - + (blkette, nextblk, amp, period, bg, flags, res, (Year, Day, Hour, Min, Sec, junk, Micro), SN0, SN1, SN2, SN3, SN4, SN5, loop, algo, Name) = inblk - + flags = self.FlagStrtoInt(flags) - - pack_blk = self.spack( - fmtstr, blkette, nextblk, amp, period, bg, flags, res, - Year, Day, Hour, Min, Sec, junk, Micro, - SN0, SN1, SN2, SN3, SN4, SN5, loop, algo, Name) - + + pack_blk = self.spack(fmtstr, blkette, nextblk, amp, period, bg, + flags, res, Year, Day, Hour, Min, Sec, junk, + Micro, SN0, SN1, SN2, SN3, SN4, SN5, loop, + algo, Name) + self.infilewrite(pack_blk) return 60 - except Exception as e: + except Exception: print("error writing blockette 201") return 0 - ######################################################### + def blk300(self, seekval=0): """ Step Calibration Blockette 300 (60 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Beginning of calibration time (BTime expanded, 10) - Number of step calibrations (UBYTE, 1) - Calibrations flags (UBYTE, 1) - Step duration (ULONG, 4) - Interval durations (ULONG, 4) - Calibration signal amplitude (FLOAT, 4) - Channel with calibration input (CHAR*3) - Reserved (UBYTE, 1) - Reference amplitude (ULONG, 4) - Coupling (CHAR*12) - Rolloff (CHAR*12) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Beginning of calibration time (BTime expanded, 10) + Number of step calibrations (UBYTE, 1) + Calibrations flags (UBYTE, 1) + Step duration (ULONG, 4) + Interval durations (ULONG, 4) + Calibration signal amplitude (FLOAT, 4) + Channel with calibration input (CHAR*3) + Reserved (UBYTE, 1) + Reference amplitude (ULONG, 4) + Coupling (CHAR*12) + Rolloff (CHAR*12) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HH" - blk1=self.sunpack(fmtstr, self.infileread(4)) + blk1 = self.sunpack(fmtstr, self.infileread(4)) fmtstr = self.fmt_order + "HHBBBBH" timeblk = self.sunpack(fmtstr, self.infileread(10)) fmtstr = self.fmt_order + "BBIIf3sBI12s12s" @@ -805,22 +855,23 @@ class Mseed(futils): tmpblk.append(timeblk) tmpblk = tmpblk + list(blk2) - #apply bit mask to Ubyte + # apply bit mask to Ubyte blk = self.UbytetoStr(tmpblk, 4) return blk ######################################################### + def Writeblk300(self, inblk, seekval=0, endianess=""): """ writes Step Calibration Blockette 300 (60 bytes) requires tuples inblk inblk=(blkette, nextblk, Year, Day, Hour, Min, Sec, junk, Micro, - numst, flags, dur, interv, amp, chan, res, ref, couple, rolloff) + numst, flags, dur, interv, amp, chan, res, ref, couple, rolloff) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHHHBBBBHBBIIf3sBI12s12s" (blkette, nextblk, (Year, Day, Hour, Min, Sec, junk, Micro), @@ -837,31 +888,31 @@ class Mseed(futils): self.infilewrite(pack_blk) return 60 - except Exception as e: + except Exception: print("error writing blockette 300") return 0 ######################################################### + def blk310(self, seekval=0): """ Sine Calibration Blockette 310 (60 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Beginning of calibration time (BTime expanded, 10) - Reserved (UBYTE, 1) - Calibrations flags (UBYTE, 1) - Calibration duration (ULONG, 4) - Period of signal (FLOAT, 4) - Amplitude of signal (FLOAT, 4) - Channel with calibration input (CHAR*3) - Reserved (UBYTE, 1) - Reference amplitued (ULONG, 4) - Coupling (CHAR*12) - Rolloff (CHAR*12) - + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Beginning of calibration time (BTime expanded, 10) + Reserved (UBYTE, 1) + Calibrations flags (UBYTE, 1) + Calibration duration (ULONG, 4) + Period of signal (FLOAT, 4) + Amplitude of signal (FLOAT, 4) + Channel with calibration input (CHAR*3) + Reserved (UBYTE, 1) + Reference amplitued (ULONG, 4) + Coupling (CHAR*12) + Rolloff (CHAR*12) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HH" @@ -876,22 +927,23 @@ class Mseed(futils): tmpblk.append(timeblk) tmpblk = tmpblk + list(blk2) - #apply bit mask to Ubyte + # apply bit mask to Ubyte blk = self.UbytetoStr(tmpblk, 4) return blk ######################################################### + def Writeblk310(self, inblk, seekval=0, endianess=""): """ writes Sine Calibration Blockette 310 (60 bytes) requires tuples inblk inblk=(blkette, nextblk, Year, Day, Hour, Min, Sec, junk, Micro, - res, flags, dura,per,ampsig,chan, res2,refamp,coup,rolloff) + res, flags, dura,per,ampsig,chan, res2,refamp,coup,rolloff) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHHHBBBBHBBIff3sBI12s12s" (blkette, nextblk, (Year, Day, Hour, Min, Sec, junk, Micro), @@ -899,38 +951,38 @@ class Mseed(futils): refamp, coup, rolloff) = inblk flags = self.FlagStrtoInt(flags) - pack_blk = self.spack( - fmtstr, blkette, nextblk, - Year, Day, Hour, Min, Sec, junk, Micro, - res, flags, dura,per,ampsig,chan, res2,refamp,coup,rolloff) + pack_blk = self.spack(fmtstr, blkette, nextblk, Year, Day, Hour, + Min, Sec, junk, Micro, res, flags, dura, per, + ampsig, chan, res2, refamp, coup, rolloff) self.infilewrite(pack_blk) return 60 - except Exception as e: + except Exception: print("error writing blockette 310") return 0 ######################################################### + def blk320(self, seekval=0): """ Pseudo-random Calibraton Blockette 320 (64 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Beginning of calibration time (BTime expanded, 10) - Reserved (UBYTE, 1) - Calibrations flags (UBYTE, 1) - Calibration duration (ULONG, 4) - Peak-to-peak amplitude of steps (FLOAT, 4) - Channel with calibration input (CHAR*3) - Reserved (UBYTE, 1) - Reference amplitued (ULONG, 4) - Coupling (CHAR*12) - Rolloff (CHAR*12) - Noise type (CHAR*8) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Beginning of calibration time (BTime expanded, 10) + Reserved (UBYTE, 1) + Calibrations flags (UBYTE, 1) + Calibration duration (ULONG, 4) + Peak-to-peak amplitude of steps (FLOAT, 4) + Channel with calibration input (CHAR*3) + Reserved (UBYTE, 1) + Reference amplitued (ULONG, 4) + Coupling (CHAR*12) + Rolloff (CHAR*12) + Noise type (CHAR*8) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HH" @@ -945,58 +997,59 @@ class Mseed(futils): tmpblk.append(timeblk) tmpblk = tmpblk + list(blk2) - #apply bit mask to Ubyte + # apply bit mask to Ubyte blk = self.UbytetoStr(tmpblk, 4) return blk ######################################################### + def Writeblk320(self, inblk, seekval=0, endianess=""): """ writes Pseudo-random Calibraton Blockette 320 (64 bytes) requires tuples inblk inblk=(blkette, nextblk, Year, Day, Hour, Min, Sec, junk, Micro, - res, flags, dura,ptop,chan, res2,refamp,coup,rolloff,noise) + res, flags, dura,ptop,chan, res2,refamp,coup,rolloff,noise) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHHHBBBBHBBIf3sBI12s12s8s" - (blkette, nextblk, (Year, Day, Hour, Min, Sec, junk, Micro), - res, flags, dura, ptop, chan, res2, - refamp, coup, rolloff, noise) = inblk + (blkette, nextblk, (Year, Day, Hour, Min, Sec, junk, Micro), res, + flags, dura, ptop, chan, res2, refamp, coup, rolloff, + noise) = inblk flags = self.FlagStrtoInt(flags) - pack_blk = self.spack( - fmtstr, blkette, nextblk, - Year, Day, Hour, Min, Sec, junk, Micro, - res, flags, dura, ptop, chan, res2, - refamp, coup, rolloff, noise) + pack_blk = self.spack(fmtstr, blkette, nextblk, Year, Day, Hour, + Min, Sec, junk, Micro, res, flags, dura, + ptop, chan, res2, refamp, coup, rolloff, + noise) self.infilewrite(pack_blk) return 64 - except Exception as e: + except Exception: print("error writing blockette 320") return 0 ######################################################### + def blk390(self, seekval=0): """ Generic Calibraton Blockette 390 (28 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Beginning of calibration time (BTime expanded, 10) - Reserved (UBYTE, 1) - Calibrations flags (UBYTE, 1) - Calibration duration (ULONG, 4) - Calibration signal amplitude (FLOAT, 4) - Channel with calibration input (CHAR*3) - Reserved (UBYTE, 1) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Beginning of calibration time (BTime expanded, 10) + Reserved (UBYTE, 1) + Calibrations flags (UBYTE, 1) + Calibration duration (ULONG, 4) + Calibration signal amplitude (FLOAT, 4) + Channel with calibration input (CHAR*3) + Reserved (UBYTE, 1) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HH" @@ -1011,22 +1064,23 @@ class Mseed(futils): tmpblk.append(timeblk) tmpblk = tmpblk + list(blk2) - #apply bit mask to Ubyte + # apply bit mask to Ubyte blk = self.UbytetoStr(tmpblk, 4) return blk ######################################################### + def Writeblk390(self, inblk, seekval=0, endianess=""): """ writes Generic Calibraton Blockette 390 (28 bytes) requires tuples inblk inblk=(blkette, nextblk, Year, Day, Hour, Min, Sec, junk, Micro, - res, flags, dura,amp,chan, res2) + res, flags, dura,amp,chan, res2) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHHHBBBBHBBIf3sB" (blkette, nextblk, (Year, Day, Hour, Min, Sec, junk, Micro), @@ -1036,26 +1090,27 @@ class Mseed(futils): pack_blk = self.spack( fmtstr, blkette, nextblk, Year, Day, Hour, Min, Sec, junk, Micro, - res, flags, dura,amp,chan, res2) + res, flags, dura, amp, chan, res2) self.infilewrite(pack_blk) return 28 - except Exception as e: + except Exception: print("error writing blockette 390") return 0 ######################################################### + def blk395(self, seekval=0): """ Calibraton Abort Blockette 395 (16 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - End of calibration time (BTime expanded, 10) - Reserved (UBYTE, 2) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + End of calibration time (BTime expanded, 10) + Reserved (UBYTE, 2) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHHHBBBBH2s" @@ -1063,6 +1118,7 @@ class Mseed(futils): return list(blk) ######################################################### + def Writeblk395(self, inblk, seekval=0, endianess=""): """ writes Calibraton Abort Blockette 395 (16 bytes) @@ -1072,43 +1128,44 @@ class Mseed(futils): try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHHHBBBBH2s" - (blkette, nextblk, - (Year, Day, Hour, Min, Sec, junk, Micro), res) = inblk + (blkette, nextblk, (Year, Day, Hour, Min, Sec, junk, Micro), + res) = inblk - pack_blk = self.spack( - fmtstr, blkette, nextblk, - Year, Day, Hour, Min, Sec, junk, Micro, res) + pack_blk = self.spack(fmtstr, blkette, nextblk, Year, Day, Hour, + Min, Sec, junk, Micro, res) self.infilewrite(pack_blk) return 16 - except Exception as e: + except Exception: print("error writing blockette 395") return 0 ######################################################### + def blk400(self, seekval=0): """ Beam Blockette 400 (16 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Beam azimuth (degrees) (FLOAT, 4) - Beam slowness (sec/degree) (FLOAT, 4) - Beam configuration (UWORD, 2) - Reserved (UBYTE, 2) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Beam azimuth (degrees) (FLOAT, 4) + Beam slowness (sec/degree) (FLOAT, 4) + Beam configuration (UWORD, 2) + Reserved (UBYTE, 2) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHffH2B" - blk=self.sunpack(fmtstr, self.infileread(16)) + blk = self.sunpack(fmtstr, self.infileread(16)) return list(blk) ######################################################### + def Writeblk400(self, inblk, seekval=0, endianess=""): """ writes Beam Blockette 400 (16 bytes) @@ -1123,33 +1180,35 @@ class Mseed(futils): (blkette, nextblk, baz, bslw, bconf, res0, res1) = inblk - pack_blk=self.spack( - fmtstr, blkette, nextblk, baz, bslw, bconf, res0, res1) + pack_blk = self.spack(fmtstr, blkette, nextblk, baz, bslw, bconf, + res0, res1) self.infilewrite(pack_blk) return 16 - except Exception as e: + except Exception: print("error writing blockette 400") return 0 ######################################################### + def blk405(self, seekval=0): """ Beam Delay Blockette 405 (6 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - Array of delay values (UWORD, 2) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + Array of delay values (UWORD, 2) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHH" - blk=self.sunpack(fmtstr, self.infileread(6)) + blk = self.sunpack(fmtstr, self.infileread(6)) return list(blk) ######################################################### + def Writeblk405(self, inblk, seekval=0, endianess=""): """ writes Beam Delay Blockette 405 (6 bytes) @@ -1159,7 +1218,7 @@ class Mseed(futils): try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHH" (blkette, nextblk, delay) = inblk @@ -1169,35 +1228,36 @@ class Mseed(futils): self.infilewrite(pack_blk) return 6 - except Exception as e: + except Exception: print("error writing blockette 405") return 0 ######################################################### + def blk500(self, seekval=0): """ Timing Blockette 500 (200 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of header - (UWORD, 2) - VCO correction (FLOAT, 4) - Time of exception (BTime expanded, 10) - microsec (UBYTE, 1) - Reception quality (UBYTE, 1) - Exception count (ULONG, 4) - Exception type (CHAR*16) - Clock model (CHAR*32) - Clock status (CHAR*128) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of header + (UWORD, 2) + VCO correction (FLOAT, 4) + Time of exception (BTime expanded, 10) + microsec (UBYTE, 1) + Reception quality (UBYTE, 1) + Exception count (ULONG, 4) + Exception type (CHAR*16) + Clock model (CHAR*32) + Clock status (CHAR*128) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHf" blk1 = self.sunpack(fmtstr, self.infileread(8)) fmtstr = self.fmt_order + "HHBBBBH" - timeblk = self.sunpack(fmtstr,self.infileread(10)) + timeblk = self.sunpack(fmtstr, self.infileread(10)) fmtstr = self.fmt_order + "BBI16s32s128s" - blk2=self.sunpack(fmtstr, self.infileread(182)) + blk2 = self.sunpack(fmtstr, self.infileread(182)) # incorporate timeblk tuple into blk list blk = list(blk1) @@ -1207,17 +1267,18 @@ class Mseed(futils): return blk ######################################################### + def Writeblk500(self, inblk, seekval=0, endianess=""): """ writes Timing Blockette 500 (200 bytes) requires tuples inblk inblk=(blkette, nextblk, vcocorr,Year, Day, Hour, Min, Sec, junk, - Micro, Micro2, qual,cnt,type,mod,stat) + Micro, Micro2, qual,cnt,type,mod,stat) """ try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHfHHBBBBHBBI16s32s128s" (blkette, nextblk, vcocorr, @@ -1232,23 +1293,24 @@ class Mseed(futils): self.infilewrite(pack_blk) return 200 - except Exception as e: + except Exception: print("error writing blockette 500") return 0 ######################################################### + def blk1000(self, seekval=0): """ Data Only SEED Blockette 1000 (8 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of - header (UWORD, 2) - Encoding Format (BYTE, 1) - Word Order (UBYTE, 1) - Data Record Length (UBYTE, 1) - Reserved (UBYTE, 1) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of + header (UWORD, 2) + Encoding Format (BYTE, 1) + Word Order (UBYTE, 1) + Data Record Length (UBYTE, 1) + Reserved (UBYTE, 1) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHbBBB" @@ -1257,6 +1319,7 @@ class Mseed(futils): return list(blk) ######################################################### + def Writeblk1000(self, inblk, seekval=0, endianess=""): """ writes Data Only SEED Blockette 1000 (8 bytes) @@ -1269,37 +1332,40 @@ class Mseed(futils): fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHbBBB" - (blkette, nextblk, fmt,order,length,res) = inblk + (blkette, nextblk, fmt, order, length, res) = inblk pack_blk = self.spack( - fmtstr, blkette, nextblk, fmt,order,length,res) + fmtstr, blkette, nextblk, fmt, order, length, res) self.infilewrite(pack_blk) return 8 - except Exception as e: + except Exception: print("error writing blockette 1000") return 0 ######################################################### + def blk1001(self, seekval=0): """ Data Extension Blockette 1001 (8 bytes) Returns tuple - blk - Blockette type (UWORD, 2) - Next blockette's byte offset relative to fixed section of - header (UWORD, 2) - Timing Quality (UBYTE, 1) - microsec (UBYTE, 1) - Reserved (UBYTE, 1) - Frame count (UBYTE, 1) + blk + Blockette type (UWORD, 2) + Next blockette's byte offset relative to fixed section of + header (UWORD, 2) + Timing Quality (UBYTE, 1) + microsec (UBYTE, 1) + Reserved (UBYTE, 1) + Frame count (UBYTE, 1) """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHBBBB" blk = self.sunpack(fmtstr, self.infileread(8)) return list(blk) + ######################################################### + def Writeblk1001(self, inblk, seekval=0, endianess=""): """ writes Data Extension Blockette 1001 (8 bytes) @@ -1309,22 +1375,23 @@ class Mseed(futils): try: self.infileseek(seekval) - fmtorderstr=self.setEndian(endianess) + fmtorderstr = self.setEndian(endianess) fmtstr = fmtorderstr + "HHBBBB" (blkette, nextblk, tqual, micro, res, fcnt) = inblk - pack_blk = self.spack( - fmtstr, blkette, nextblk, tqual, micro, res, fcnt) + pack_blk = self.spack(fmtstr, blkette, nextblk, tqual, micro, + res, fcnt) self.infilewrite(pack_blk) return 8 - except Exception as e: + except Exception: print("error writing blockette 1001") return 0 ######################################################### + def blk2000(self, seekval=0): """ Variable Length Opaque Data Blockette @@ -1379,16 +1446,16 @@ class Mseed(futils): """ self.infileseek(seekval) fmtstr = self.fmt_order + "HHHHIBBB" - blk=self.sunpack(fmtstr, self.infileread(15)) - #decompose tmpblk[6] into bit fields, create blk + blk = self.sunpack(fmtstr, self.infileread(15)) + # decompose tmpblk[6] into bit fields, create blk tmpblk = self.UbytetoStr(blk, 6) - blk=tmpblk #recast blk as list + blk = tmpblk # recast blk as list - #Now decipher Opaque Header + # Now decipher Opaque Header charlist = [] char = "" length_data_string = 0 - NumOpaqueHeaders=int(blk[7]) + NumOpaqueHeaders = int(blk[7]) fmtstr = self.fmt_order + "s" for i in range(NumOpaqueHeaders): tmpchar = "" @@ -1400,21 +1467,20 @@ class Mseed(futils): length_data_string += 1 charlist.append(char) blk.append(charlist) -# opaque = "" -# rdbyte = int(tmpblk[2]) - 15 - length_data_string -# fmt = "=%ds" % rdbyte -# opaque=self.sunpack(fmt, self.infileread(rdbyte)) -# -# # -# print opaque -# # + # opaque = "" + # rdbyte = int(tmpblk[2]) - 15 - length_data_string + # fmt = "=%ds" % rdbyte + # opaque=self.sunpack(fmt, self.infileread(rdbyte)) + # print(opaque) return blk + ######################################################### + def UbytetoStr(self, tup, offset): """ converts unsign byte to string values """ - list=[] + list = [] strval = "" # mask bit fields and build string for i in range(8): @@ -1431,7 +1497,9 @@ class Mseed(futils): else: list.append(tup[i]) return list + ######################################################### + def FlagStrtoInt(self, flagstr): """ converts Flag String to Integer @@ -1445,28 +1513,29 @@ class Mseed(futils): return flagint ######################################################### + def Pad(self, var, num): """ pad header values to specified length with blank space right justified """ - varlength=len(var) + varlength = len(var) if varlength == num: return var elif varlength < num: - pad = num-varlength - newvar = var + SPACE*pad + pad = num - varlength + newvar = var + SPACE * pad return newvar ######################################################### -### END MSEED +# END MSEED ######################################################### class Segy(futils): def __init__(self, infile): self.type = self.serial = self.chan = self.time = self.rate = None - futils.__init__(self,infile) - # self.byteorder: byte order of input file. + futils.__init__(self, infile) + # self.byteorder: byte order of input file. # "big" # "little" # or "unknown" @@ -1477,20 +1546,23 @@ class Segy(futils): # "<" little endian ######################################################### - def isSegy(self) : + + def isSegy(self): """ determines if processed file is segy or unknown type """ - #if we don't know byteorder it must not be segy - if self.byteorder == "unknown": return 0 + # if we don't know byteorder it must not be segy + if self.byteorder == "unknown": + return 0 - #otherwise it might be segy + # otherwise it might be segy (Sserial, Schan, Srate, Syear, Sday, Shour, Smin, Ssec) = self.idread() - #we have already tested for a valid time in self.ByteOrder, this test is - #to ensure that we were able to read a complete idhdr header + # we have already tested for a valid time in self.ByteOrder, this test + # is to ensure that we were able to read a complete idhdr header if Sserial == Schan == Srate == Syear == Sday == Shour == \ - Smin == Ssec == None: return 0 - #if we're this far it must be segy + Smin == Ssec is None: + return 0 + # if we're this far it must be segy self.type = "segy" if Sserial < 36864: self.serial = Sserial @@ -1502,74 +1574,79 @@ class Segy(futils): return 1 ######################################################### + def idhdr(self): return self.type, self.serial, self.chan, self.time, self.rate ######################################################### + def tracelength(self): """ returns trace length in seconds """ self.infile.seek(228) fmtstr = self.fmt_order + "L" - numsamp=struct.unpack(fmtstr, self.infile.read(4))[0] - length=numsamp/self.rate + numsamp = struct.unpack(fmtstr, self.infile.read(4))[0] + length = numsamp / self.rate return length + ######################################################### - def idread(self) : + + def idread(self): """ Read file as if SEGY file trying to extract channel, time block, sample rate, and serial number """ - try : + try: self.infile.seek(0) - SH=self.infile.read(240) -# self.infile.seek(12) + SH = self.infile.read(240) + # self.infile.seek(12) fmtstr = self.fmt_order + "L" -# chan = struct.unpack(fmtstr, self.infile.read(4))[0] -# print chan + # chan = struct.unpack(fmtstr, self.infile.read(4))[0] + # print(chan) chan = struct.unpack(fmtstr, SH[12:16])[0] -# self.infile.seek(156) -# timeblock=self.infile.read(10) + # self.infile.seek(156) + # timeblock=self.infile.read(10) fmtstr = self.fmt_order + "HHHHH" -# (year,day,hour,min,sec)=struct.unpack(fmtstr, timeblock) + # (year,day,hour,min,sec)=struct.unpack(fmtstr, timeblock) (year, day, hour, min, sec) = struct.unpack(fmtstr, SH[156:166]) -# self.infile.seek(200) + # self.infile.seek(200) fmtstr = self.fmt_order + "L" -# samp=struct.unpack(fmtstr, self.infile.read(4))[0] -# print samp + # samp=struct.unpack(fmtstr, self.infile.read(4))[0] + # print(samp) samp = struct.unpack(fmtstr, SH[200:204])[0] - rate = int(1/(samp/1e6)) + rate = int(1 / (samp / 1e6)) -# self.infile.seek(224) + # self.infile.seek(224) fmtstr = self.fmt_order + "H" -# serial = struct.unpack(fmtstr, self.infile.read(2))[0] + # serial = struct.unpack(fmtstr, self.infile.read(2))[0] serial = struct.unpack(fmtstr, SH[224:226])[0] return serial, chan, rate, year, day, hour, min, sec - except : + except Exception: return None, None, None, None, None, None, None, None ######################################################### - def ByteOrder(self, seekval=156) : + + def ByteOrder(self, seekval=156): """ read file as if it is segy just pulling time info from header and determine if it makes sense unpacked as big endian or little endian """ Order = "unknown" - try : - #seek to timeblock and read + try: + # seek to timeblock and read self.infile.seek(seekval) - timeblock=self.infile.read(10) + timeblock = self.infile.read(10) - #assume big endian - (Year, Day, Hour, Min, Sec)=\ - struct.unpack('>HHHHH',timeblock) - #test if big endian read makes sense + # assume big endian + (Year, Day, Hour, Min, Sec) =\ + struct.unpack('>HHHHH', timeblock) + # test if big endian read makes sense if 1950 <= Year <= 2050 and \ 1 <= Day <= 366 and \ 0 <= Hour <= 23 and \ @@ -1578,10 +1655,10 @@ class Segy(futils): Order = "big" self.fmt_order = ">" else: - #try little endian read - (Year, Day, Hour, Min, Sec)=\ - struct.unpack('<HHHHH',timeblock) - #test if little endian read makes sense + # try little endian read + (Year, Day, Hour, Min, Sec) =\ + struct.unpack('<HHHHH', timeblock) + # test if little endian read makes sense if 1950 <= Year <= 2050 and \ 1 <= Day <= 366 and \ 0 <= Hour <= 23 and \ @@ -1589,84 +1666,92 @@ class Segy(futils): 0 <= Sec <= 59: Order = "little" self.fmt_order = "<" - except : + except Exception: pass return Order + ######################################################### - def to_int(self, input) : + + def to_int(self, input): """ conversion routine from hex to integer """ - HEXCHAR=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"] - hexnum=str(input) - retval=0 - input_length=len(hexnum) - for i in range(input_length) : - for index in range(len(HEXCHAR)) : - if hexnum[i].upper() == HEXCHAR[index] : - retval=retval + index*(16**(input_length-(1+i))) + HEXCHAR = ["0", "1", "2", "3", "4", "5", "6", + "7", "8", "9", "A", "B", "C", "D", "E", "F"] + hexnum = str(input) + retval = 0 + input_length = len(hexnum) + for i in range(input_length): + for index in range(len(HEXCHAR)): + if hexnum[i].upper() == HEXCHAR[index]: + retval = retval + index * (16**(input_length - (1 + i))) return retval ######################################################### - def to_hex(self, number) : + + def to_hex(self, number): """ conversion routine from integer to hex """ - retval=0 - hexnum=hex(number) + retval = 0 + hexnum = hex(number) return hexnum[2:] + + ######################################################### -### END SEGY +# END SEGY ######################################################### -if __name__ == "__main__" : +if __name__ == "__main__": VERSION = "2008.204" - filecnt=0 -# based on traverse routine in "python standard library", Lundh pg 34 - def GetTrace(DataDir) : + filecnt = 0 + # based on traverse routine in "python standard library", Lundh pg 34 + + def GetTrace(DataDir): global filecnt stack = [] rwError = 0 - for k in range(len(DataDir)) : + for k in range(len(DataDir)): stack.append(DataDir[k]) files = [] file_list = {} errcnt = 0 - while stack : + while stack: directory = stack.pop() if not os.path.isdir(directory): print("\n***WARNING*** Directory \"%s\" not found.\n" % directory) continue - # else : + # else : for file in os.listdir(directory): fullname = os.path.join(directory, file) if not os.access(fullname, 6): - rwError+=1 - continue + rwError += 1 + continue - if os.path.isfile(fullname) : - filecnt+=1 + if os.path.isfile(fullname): + filecnt += 1 try: newfile = Segy(fullname) if newfile.isSegy(): (type, serial, chan, time, rate) = newfile.idhdr() length = newfile.tracelength() - # length = "NULL" - file_list[fullname] = ( - type, serial, chan, time, rate, length, - newfile.ByteOrder()) + # length = "NULL" + file_list[fullname] = (type, serial, chan, time, + rate, length, + newfile.ByteOrder()) newfile.close() - except Exception as e: - rwError+=1 + except Exception: + rwError += 1 pass else: try: - newfile=Mseed(fullname) + newfile = Mseed(fullname) if newfile.isMseed(): try: - #simple test to determine if correct size file + # simple test to determine if correct size + # file filesize = newfile.filesize blksize = newfile.blksize (numblocks, odd_size) = \ @@ -1686,26 +1771,25 @@ if __name__ == "__main__" : time = newfile.time rate = newfile.rate length = newfile.tracelength() - # length = "NULL" + # length = "NULL" file_list[fullname] = ( type, serial, chan, time, rate, length, newfile.ByteOrder()) newfile.close() except Exception as e: - rwError+=1 + rwError += 1 pass - # if os.path.isdir(fullname) and not os.path.islink(fullname) : - if os.path.isdir(fullname) or \ - (os.path.islink(fullname) \ - and not os.path.isfile(fullname)): + # if os.path.isdir(fullname) and not os.path.islink(fullname): + if os.path.isdir(fullname) or (os.path.islink(fullname) and + not os.path.isfile(fullname)): stack.append(fullname) return file_list, rwError - if len(sys.argv) > 1 : - if sys.argv[1] == "-#" : + if len(sys.argv) > 1: + if sys.argv[1] == "-#": print(VERSION) sys.exit(1) - else : + else: print("Unknown arguement %s" % sys.argv[1:]) sys.exit(1) @@ -1713,27 +1797,29 @@ if __name__ == "__main__" : mseednum = 0 unknownnum = 0 Dirs = [] -# Dirs.append(",") + # Dirs.append(",") Dirs.append(".") -# Dirs.append("/Users/bruce/data/uniq") - (file_list,rwError) = GetTrace(Dirs) - for file in file_list : + # Dirs.append("/Users/bruce/data/uniq") + (file_list, rwError) = GetTrace(Dirs) + for file in file_list: file_type = file_list[file][0] - if file_type == "segy" : + if file_type == "segy": segynum += 1 -# print "\n SEGY \n" -# print "segy: ", file_list[file][1], file_list[file][2], file_list[file][3], \ -# file_list[file][4], file_list[file][5], file_list[file][6] - elif file_type == "mseed" : -# if file_type == "mseed" : + # print("\n SEGY \n") + # print("segy: ", file_list[file][1], file_list[file][2], + # file_list[file][3], file_list[file][4], file_list[file][5], + # file_list[file][6]) + elif file_type == "mseed": + # if file_type == "mseed" : mseednum += 1 -# print "\n MSEED \n" -# print "mseed: ", file_list[file][1], file_list[file][2], file_list[file][3], \ -# file_list[file][4], file_list[file][5], file_list[file][6] - - #else : - #unknownnum += 1 - #print "\n Format Not Recognized \n" + # print("\n MSEED \n") + # print("mseed: ", file_list[file][1], file_list[file][2], + # file_list[file][3], file_list[file][4], file_list[file][5], + # file_list[file][6]) + + # else : + # unknownnum += 1 + # print("\n Format Not Recognized \n") print("\nTotal Files Found = %i " % filecnt) print("SEGY Files Processed = %i \nMSEED Files Processed = %i" % (segynum, mseednum)) diff --git a/fixhdr/fixhdr.py b/fixhdr/fixhdr.py index 405ad1be19bf93e7361cf8a260dd642d3d4b3e91..4053074c7ac185e2cd9e02e21acee383f56a7353 100755 --- a/fixhdr/fixhdr.py +++ b/fixhdr/fixhdr.py @@ -85,7 +85,8 @@ # Added features: # # Wait utility -# if something is running pops-up a window telling user to wait +# if something is running pops-up a window telling user +# to wait # functions: # WaitWidget # Warn utility @@ -94,7 +95,8 @@ # WarnWidget # Ignore # Enhanced Logging functionality -# user can now sort log on All, Headers, Time, Endian, or Summary +# user can now sort log on All, Headers, Time, Endian, +# or Summary # user can flush logs # functions: # FlushLogs @@ -106,8 +108,8 @@ # date 2005.252 # # fixed round-off error of microseconds in self.FillTime -# Added to TimeShift notebook the ability to set/unset the Data Quality flag in the -# FSDH that indicates the "Time tag is questionable" +# Added to TimeShift notebook the ability to set/unset the Data Quality flag in +# the FSDH that indicates the "Time tag is questionable" # Updated help & man page # implemented sorts for displaying several dictionary's contents ########################## @@ -127,7 +129,8 @@ # introduced batchmode (cmdline -b option) # now importing getopt to parse commandline args # changed MSEED format tab to conform to SEED Manual v2.3, Feb 1993, Appendix A -# threaded all operations that write to headers so that they can be cleanly stopped +# threaded all operations that write to headers so that they can be cleanly +# stopped ########################## # modification @@ -142,7 +145,7 @@ # date 2005.300 # # bug fix in BuildEpoch in try/except that revealed itself if time format was -# incorrect. +# incorrect. # add ResetTimeShift # add CheckTimeFormat to ensure proper Time format entered # @@ -153,7 +156,7 @@ # # bug fix in ApplyTimeCor that caused not all traces to be corrected # Changed granularity of selection times from milliseconds to seconds to -# avoid roundoff errors going from string to epoch and back again. +# avoid roundoff errors going from string to epoch and back again. # Added feature in Time Shift window allowing user to wildcard location codes # ########################## @@ -170,37 +173,43 @@ # date 2007.133 # # new stuff- -# new flags, batchmode for time & endian, template for time corrections, better handling of previous -# header or time corrections, undo time correction button, record of time corrections, -# changed method of handling batchmode, allows user to specify datadir, list time corrections +# new flags, batchmode for time & endian, template for time corrections, +# better handling of previous header or time corrections, undo time correction +# button, record of time corrections, changed method of handling batchmode, +# allows user to specify datadir, list time corrections # # new methods -# TimeDictSet, WildCardLoc, NewOnlyTime, LoadTimeSelect, DumpUpdateDicts, Usage, ExitWidget, GetTimeCor -# ListTimeCor, AddZero, LaunchUndoTimeCor, CancelWarnTL, RecalcStartEnd +# TimeDictSet, WildCardLoc, NewOnlyTime, LoadTimeSelect, +# DumpUpdateDicts, Usage, ExitWidget, GetTimeCor, ListTimeCor, AddZero, +# LaunchUndoTimeCor, CancelWarnTL, RecalcStartEnd # # reworked methods -# LaunchApplyTimeCor, ApplyTimeCor, UpdateTimeShift, GetStartEnd, writeFile, LoadTemplate, ExitCheck -# wait, WriteLog, addTextInfoBar +# LaunchApplyTimeCor, ApplyTimeCor, UpdateTimeShift, GetStartEnd, +# writeFile, LoadTemplate, ExitCheck, wait, WriteLog, addTextInfoBar # # removed methods # WaitWidget, ModAndExit # -# fix bug whereby 'Save Header Template' ignored current entries on 'Trace Header' tab +# fix bug whereby 'Save Header Template' ignored current entries on 'Trace +# Header' tab ########################## # modification # author: bcb # date 2007.177 # # bug fix in LoadTemplate -# when loading timelist if shift = NA or na then shift was left unassigned -# this caused Time_Shift_sec to be an invalid float later in processing +# when loading timelist if shift = NA or na then shift was left +# unassigned this caused Time_Shift_sec to be an invalid float later +# in processing ########################## # modification # author: bcb # date 2007.192 # -# changed reporting of rw errors to just listing number of files w/o rw permission -# added column to ListTimeCor to display if 'Timing Questionable' flag is set or unset +# changed reporting of rw errors to just listing number of files w/o rw +# permission +# added column to ListTimeCor to display if 'Timing Questionable' flag is set +# or unset # added balloon help # added Template format help ########################## @@ -209,14 +218,16 @@ # date 2007.342 # # reworked method: TimeSet to incorporate TestTimeShift -# added method: TestTimeShift to ensure user doesn't exceed time correction field +# added method: TestTimeShift to ensure user doesn't exceed time correction +# field # ########################## # modification # author: bcb # date 2008:154 # -# bug fix: In ApplyTimeCor missed instance when blk_start < startTime < blk_end and blk_start< endTime<blk_end +# bug fix: In ApplyTimeCor missed instance when blk_start < startTime < blk_end +# and blk_start< endTime<blk_end ################################################################ # # modification @@ -224,7 +235,8 @@ # author: Bruce Beaudoin # # modified to take advantage of LibTrace optimization -# cleaned up testing of files. Now done in FindTrace not everytime file is opened. +# cleaned up testing of files. Now done in FindTrace not everytime file is +# opened. # added globbing to Directory path # optimized several routines with generators (thanks Lloyd) ################################################################ @@ -233,18 +245,20 @@ # version: 2009.175 # author: Jayson Barr # -# modified to no longer create threads. I commented out all the lines with threading calls so this can -# later be noted where would be useful to add it in again. The reason for this is because everytime a thread -# was used it was defined, started and then joined immediately. Therefore, there was no reason for them -# to be threads at all, and it was breaking with Tk because the functions that were the targets for the threads -# weren't actually Tk/thread safe. - +# modified to no longer create threads. I commented out all the lines with +# threading calls so this can later be noted where would be useful to add it +# in again. The reason for this is because everytime a thread was used it was +# defined, started and then joined immediately. Therefore, there was no reason +# for them to be threads at all, and it was breaking with Tk because the +# functions that were the targets for the threads weren't actually Tk/thread +# safe. +################################################################ # # modification # version: 2018.176 # author: Derick Hess # Updated cookiecutter version, added call to main(), etc. - +# ################################################################ # # modification @@ -252,26 +266,38 @@ # author: Lan Dam # convert to py3 # bug fix: In GetStartEnd when no "Stat:Loc:Net" selected (timeid="") +################################################################ +# +# modification +# version: 2020.212 +# author: Maeva Pourpoint +# +# Updates to work under Python 3. +# Unit tests to ensure basic functionality. +# Code cleanup to conform to the PEP8 style guide. +# Directory cleanup (remove unused files introduced by Cookiecutter). +# Packaged with conda. +################################################################ -VERSION = "2019.025" - -import os, sys, string, time +import os import Pmw +import sys +import time -from operator import mod -from struct import pack from getopt import getopt - -#import threading from glob import glob +from operator import mod from tkinter import * from tkinter.filedialog import * + from fixhdr.LibTrace import * +VERSION = "2020.212" + SPACE = " " DATALOC = "" -#vars used for batchmode +# vars used for batchmode BatchFile = "" Endianess = "" RunHeaderBatch = 0 @@ -279,6 +305,7 @@ RunTimeBatch = 0 RunEndianBatch = 0 BATCHMODE = 0 + def Usage(err=''): print(err) print("Usage\nfixhdr \nfixhdr -#\nfixhdr -h\nfixhdr [-d DataDirs] " @@ -296,81 +323,89 @@ def Usage(err=''): print(" -# - print version number") print(" NOTE: -m, -t & -e are mutually exclusive. If you wish to do") print(" both timing and headers, run time corrections first.") - os._exit(0) + # get commandline args try: opts, pargs = getopt(sys.argv[1:], 'hd:t:m:e:#') -except Exception as e: +except Exception: err = "\nERROR: Invalid command line usage\n" Usage(err) + sys.exit(1) else: for flag, arg in opts: if flag == "-h": Usage() + sys.exit(0) if flag == "-d": - DATALOC=arg + DATALOC = arg if flag == "-e": - Endianess=arg + Endianess = arg if Endianess != "big" and Endianess != "little": - err="\nError: Endianess must be either 'big' or 'little'" + err = "\nError: Endianess must be either 'big' or 'little'" Usage(err) - RunEndianBatch=1 - BATCHMODE=1 + RunEndianBatch = 1 + BATCHMODE = 1 if flag == "-m": - BatchFile=arg - RunHeaderBatch=1 - BATCHMODE=1 + BatchFile = arg + RunHeaderBatch = 1 + BATCHMODE = 1 if flag == "-t": BatchFile = arg RunTimeBatch = 1 - BATCHMODE=1 + BATCHMODE = 1 if flag == "-#": print(VERSION) - os._exit(0) + sys.exit(0) if RunTimeBatch + RunHeaderBatch + RunEndianBatch > 1: - err="\nERROR: Cannot correct timing, headers and/or endianess simultaniously\n" + err = ("\nERROR: Cannot correct timing, headers and/or endianess " + "simultaniously\n") Usage(err) - - + sys.exit(1) print("\n", os.path.basename(sys.argv[0]), VERSION) -#From "Python and Tkinter Programming", J.E. Grayson, pg.103 + +# From "Python and Tkinter Programming", J.E. Grayson, pg.103 class Command: - def __init__(self,func, *args, **kw): + def __init__(self, func, *args, **kw): self.func = func self.args = args self.kw = kw + def __call__(self, *args, **kw): args = self.args + args kw.update(self.kw) self.func(*args, **kw) + # # Over ride some methods in FileDialog so we only select directories # From TraceBuilder.py, auth Steve Azevedo & Lloyd Carothers # -class DirectoryDialog (FileDialog) : +class DirectoryDialog(FileDialog): title = "Directory Select" - def __init__ (self, root) : - FileDialog.__init__ (self, root) - #Only allow selection of directories (single click) - def files_select_event (self, e): + def __init__(self, root): + FileDialog.__init__(self, root) + + # Only allow selection of directories (single click) + def files_select_event(self, e): pass - #Double click - def files_double_event (self, e): + # Double click + + def files_double_event(self, e): pass - #Make sure it's a directory and accessable - def ok_command (self) : - file = self.get_selection () - if not os.path.isdir (file) : - if not os.access (file, R_OK) : - self.root.bell () + # Make sure it's a directory and accessable + def ok_command(self): + file = self.get_selection() + if not os.path.isdir(file): + if not os.access(file, R_OK): + self.root.bell() file = None - self.quit (file) + self.quit(file) + # main class MainWindow: @@ -380,18 +415,19 @@ class MainWindow: Pmw.initialise(self.root) self.root.title(title) - #create balloon - self.balloon=Pmw.Balloon(self.root) + # create balloon + self.balloon = Pmw.Balloon(self.root) - #set timezone to UTC + # set timezone to UTC os.environ['TZ'] = 'GMT' time.tzname = ('GMT', 'GMT') time.timezone = 0 - #Start Global Variables + # Start Global Variables self.e_width = 24 - #Variables, lists, dictionaries associated with traces and trace headers + # Variables, lists, dictionaries associated with traces and trace + # headers self.OldSID = StringVar() self.DataDirs = StringVar() self.StatSel = StringVar() @@ -414,7 +450,7 @@ class MainWindow: ["Sample_Rate", self.SampleRate] ] - #New Values on Trace Headers notebook + # New Values on Trace Headers notebook self.NStation = StringVar() self.NChannel = StringVar() self.NLocCode = StringVar() @@ -426,8 +462,8 @@ class MainWindow: ["Network_Code", self.NNetCode] ] - #Modified button on Trace Headers notebook - #denote whether applied updates or not + # Modified button on Trace Headers notebook + # denote whether applied updates or not self.SetStat = IntVar() self.SetChan = IntVar() self.SetLoc = IntVar() @@ -440,21 +476,21 @@ class MainWindow: ] self.SetHdrDict = {} - #vars used in global nb + # vars used in global nb self.GlobalStation = StringVar() self.GlobalChannel = StringVar() self.GlobalLocCode = StringVar() self.GlobalSps = StringVar() self.GlobalNetCode = StringVar() - #global update variables + # global update variables self.GUStation = StringVar() self.GUChannel = StringVar() self.GULocCode = StringVar() self.GUSps = StringVar() self.GUNetCode = StringVar() - #lists for dropdown menus on Global Modify notebook + # lists for dropdown menus on Global Modify notebook self.StationList = [] self.ChannelList = [] self.LocList = [] @@ -472,7 +508,7 @@ class MainWindow: ["Sample_Rate", self.GlobalSps, self.SpsList, self.GUSps] ] - #vars used in TimeShift nb + # vars used in TimeShift nb self.TimeShiftName = StringVar() self.OldShiftName = StringVar() self.TSStartTime = StringVar() @@ -497,7 +533,6 @@ class MainWindow: ["Time_Shift_sec", self.TSShift], ["Time_Tag_Quest", self.TimeTagQuest], ["Corr_Type", self.TypeTimeCor] - ] self.SetTime = IntVar() @@ -507,7 +542,7 @@ class MainWindow: ["Time_Tag_Quest", self.SetTQuest] ] - #vars used in Endianess nb + # vars used in Endianess nb self.Savefile = StringVar() self.DataDirList = [] self.BigEndianList = [] @@ -518,7 +553,7 @@ class MainWindow: self.NumBigFiles.set(0) self.ToEndian = StringVar() - #log vars and lists + # log vars and lists self.LogList = [ ["All", 0], ["Header", 1], @@ -534,13 +569,13 @@ class MainWindow: self.LogEndian = [] self.LogSummary = [] - #activity and warning vars + # activity and warning vars self.ActiveText = StringVar() self.ActiveText.set("") self.AlteredText = StringVar() self.AlteredText.set("") - #set of vars watched for active threading event + # set of vars watched for active threading event self.RunBuilddb = IntVar() self.RunBuilddb.set(0) self.RunModHdrs = IntVar() @@ -555,10 +590,10 @@ class MainWindow: self.CancelWarn.set(0) self.IgnoreWarn = IntVar() self.IgnoreWarn.set(0) - self.UseNewOnlyTime=IntVar() + self.UseNewOnlyTime = IntVar() self.UseNewOnlyTime.set(0) - #if DATALOC not set on commandline set here + # if DATALOC not set on commandline set here if DATALOC: self.DataDirs.set(DATALOC) else: @@ -571,7 +606,7 @@ class MainWindow: # If batchmode then launch from here and exit if BATCHMODE: - #address endian change first since unique i.e. no batchfile + # address endian change first since unique i.e. no batchfile print("Running in Batch Mode") if RunEndianBatch: print("Changing Endianess to: ", Endianess) @@ -613,49 +648,52 @@ class MainWindow: # Build GUI self.createMainButtons(self.root) self.createNoteBooks(self.root) + ######################################## - def createMainButtons(self,master): + + def createMainButtons(self, master): """ Build buttons for root window """ - #create info bar at bottom of root window + # create info bar at bottom of root window self.InfoString_l = Label(master, - bg = "yellow", - relief = "ridge") + bg="yellow", + relief="ridge") self.InfoString_l.pack(side='bottom', fill='x') - #persistent buttons across all tabs - self.Button_fm = Frame(master, relief = 'groove', borderwidth = 2) - self.Button_fm.pack(side = 'bottom', pady=5, fill = 'x') + # persistent buttons across all tabs + self.Button_fm = Frame(master, relief='groove', borderwidth=2) + self.Button_fm.pack(side='bottom', pady=5, fill='x') self.exit_b = Button(self.Button_fm, - text = "Exit", - relief = "ridge", - cursor = 'pirate', - command = Command(self.ExitCheck), - activebackground= 'red', + text="Exit", + relief="ridge", + cursor='pirate', + command=Command(self.ExitCheck), + activebackground='red', activeforeground='black') self.exit_b.pack(side='right', anchor='e') self.balloon.bind(self.exit_b, "Exit Program") self.save_b = Button(self.Button_fm, text='Save Template', - relief = "ridge", + relief="ridge", activebackground='green', command=Command(self.saveWidget, master, "templ") ) self.save_b.pack(side='right', anchor='e') - self.balloon.bind(self.save_b, "Export saved header & \ntiming corrections to file") + self.balloon.bind( + self.save_b, "Export saved header & \ntiming corrections to file") self.save_b = Button(self.Button_fm, text='Load Template', - relief = "ridge", + relief="ridge", activebackground='green', command=Command(self.LoadTemplate) ) self.save_b.pack(side='right', anchor='e') - self.balloon.bind(self.save_b, "Import saved header & \ntiming corrections file") - + self.balloon.bind( + self.save_b, "Import saved header & \ntiming corrections file") self.PopUpHelp_cb = Checkbutton(self.Button_fm, text="PopUp Help", @@ -666,16 +704,19 @@ class MainWindow: self.balloon.bind(self.PopUpHelp_cb, "Toggles 'PopUp Help' on and off") ######################################## + def ToggleBalloons(self): """ turns balloon help on and off """ if self.PopUpHelp.get(): - self.balloon.configure(state = 'balloon') + self.balloon.configure(state='balloon') else: - self.balloon.configure(state = 'none') + self.balloon.configure(state='none') + ######################################## - def createNoteBooks(self,master): + + def createNoteBooks(self, master): """ Set up notebooks in root window """ @@ -689,185 +730,200 @@ class MainWindow: self.buildMSformat(nb) nb.pack(padx=5, pady=5, fill='both', expand=1) - ################################################################## - def buildHdrList(self,master): + + def buildHdrList(self, master): """ Populate HdrList NoteBook - tab for selecting traces, building trace database, and correcting headers one key at a time + tab for selecting traces, building trace database, and correcting + headers one key at a time """ self.StatChanList_nb = master.add('Trace Headers') - #buttons - self.Button_fm = Frame(self.StatChanList_nb, borderwidth = 2) - self.Button_fm.pack(side = 'bottom', padx= 5, pady=5, fill = 'x') - self.StatChanList_fm = Frame(self.StatChanList_nb, relief = 'groove', borderwidth = 2) + # buttons + self.Button_fm = Frame(self.StatChanList_nb, borderwidth=2) + self.Button_fm.pack(side='bottom', padx=5, pady=5, fill='x') + self.StatChanList_fm = Frame( + self.StatChanList_nb, relief='groove', borderwidth=2) self.ClearUpdateDict_b = Button(self.Button_fm, - text = "Clear Update Dictionary", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.ClearAllTrace, 1), - activebackground= 'orange', + text="Clear Update Dictionary", + relief="ridge", + cursor='X_cursor', + command=Command(self.ClearAllTrace, 1), + activebackground='orange', activeforeground='black') self.ClearUpdateDict_b.pack(side='right', anchor='e') - self.balloon.bind(self.ClearUpdateDict_b, "Clears all entries \nin 'Update Dictionary'") + self.balloon.bind(self.ClearUpdateDict_b, + "Clears all entries \nin 'Update Dictionary'") self.clear_b = Button(self.Button_fm, - text = "Clear Current", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.ClearAllTrace), - activebackground= 'orange', + text="Clear Current", + relief="ridge", + cursor='X_cursor', + command=Command(self.ClearAllTrace), + activebackground='orange', activeforeground='black') self.clear_b.pack(side='right', anchor='e') - self.balloon.bind(self.clear_b, \ - "Clears entries in 'Update Dictionary' \nfor selected Stat:Chan:Loc:Net:Sps") + self.balloon.bind(self.clear_b, "Clears entries in 'Update " + "Dictionary' \nfor selected Stat:Chan:Loc:Net:Sps") self.ModHdr_b = Button(self.Button_fm, - text = "Modify Headers", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.LaunchModHdrs), + text="Modify Headers", + relief="ridge", + cursor='X_cursor', + command=Command(self.LaunchModHdrs), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.ModHdr_b.pack(side='right', anchor='e') - self.balloon.bind(self.ModHdr_b, \ - "Modifies headers using current entries \nand all entries in 'Update Dictionary'") + self.balloon.bind(self.ModHdr_b, "Modifies headers using current " + "entries \nand all entries in 'Update Dictionary'") self.listtrace_b = Button(self.Button_fm, - text = "List Traces", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.ListTrace, self.StatChanList_nb), - activebackground= 'green', - activeforeground= 'black') + text="List Traces", + relief="ridge", + cursor='X_cursor', + command=Command( + self.ListTrace, self.StatChanList_nb), + activebackground='green', + activeforeground='black') self.listtrace_b.pack(side='left', anchor='e') - self.balloon.bind(self.listtrace_b, \ + self.balloon.bind(self.listtrace_b, "Lists traces for selected \nStat:Chan:Loc:Net:Sps") - #data directory find and clear buttons, and entry field - #button to build trace db - self.DataDirs_fm = Frame(self.StatChanList_nb, relief = 'groove', borderwidth = 2) - self.DataDirs_fm.pack(side = 'top', pady=5, fill = 'x') + # data directory find and clear buttons, and entry field + # button to build trace db + self.DataDirs_fm = Frame(self.StatChanList_nb, + relief='groove', borderwidth=2) + self.DataDirs_fm.pack(side='top', pady=5, fill='x') self.DataDirs_l = Label(self.DataDirs_fm, text='Data Directories: ') self.DataDirs_l.pack(side='left') - self.balloon.bind(self.DataDirs_l, \ - "Search path(s) for finding mseed files. \nColon separate multiple entries") + self.balloon.bind(self.DataDirs_l, "Search path(s) for finding mseed " + "files. \nColon ""separate multiple entries") self.DataDirs_e = Entry(self.DataDirs_fm, - selectbackground = 'yellow', - textvariable = self.DataDirs) - self.DataDirs_e.pack(side='left', anchor='w',expand=1, fill='x') + selectbackground='yellow', + textvariable=self.DataDirs) + self.DataDirs_e.pack(side='left', anchor='w', expand=1, fill='x') self.ClearDataDir_b = Button(self.DataDirs_fm, - activebackground = 'orange', - relief = "ridge", - text = "Clear", - command = Command(self.setValue, self.DataDirs) + activebackground='orange', + relief="ridge", + text="Clear", + command=Command( + self.setValue, self.DataDirs) ) self.ClearDataDir_b.pack(side='right') - self.balloon.bind(self.ClearDataDir_b, \ + self.balloon.bind(self.ClearDataDir_b, "Clears 'Data Directories' entry") self.FindDataDir_b = Button(self.DataDirs_fm, - activebackground = 'green', - relief = "ridge", - text = "Find", - command = Command(self.getPath, self.DataDirs, None) + activebackground='green', + relief="ridge", + text="Find", + command=Command( + self.getPath, self.DataDirs, None) ) self.FindDataDir_b.pack(side='right') - self.balloon.bind(self.FindDataDir_b, \ + self.balloon.bind(self.FindDataDir_b, "Dialog window to \nselect Data Directories") - if not DATALOC: self.DataDirs.set(os.getcwd()) + if not DATALOC: + self.DataDirs.set(os.getcwd()) self.BuildTrcList_b = Button(self.DataDirs_fm, - activebackground = 'green', - relief = "ridge", + activebackground='green', + relief="ridge", background='lightblue', - text = "Build Trace db", - command = Command(self.BuildTrcList) + text="Build Trace db", + command=Command(self.BuildTrcList) ) self.BuildTrcList_b.pack(side='right') - self.balloon.bind(self.BuildTrcList_b, \ - "Build a Trace db using \n'Data Directories' \nas top level directories") + self.balloon.bind(self.BuildTrcList_b, "Build a Trace db using \n'" + "Data Directories' \nas top level directories") # station selection frame and entry box - self.StatSel_fm = Frame(self.StatChanList_nb, relief = 'groove', borderwidth = 2) - self.StatSel_fm.pack(side = 'top', pady=5, fill = 'x') - self.StatSel_l = Label(self.StatSel_fm, text='Find only stations (colon separated list): ') + self.StatSel_fm = Frame(self.StatChanList_nb, + relief='groove', borderwidth=2) + self.StatSel_fm.pack(side='top', pady=5, fill='x') + self.StatSel_l = Label(self.StatSel_fm, text="Find only stations " + "(colon separated list): ") self.StatSel_l.pack(side='left') self.StatSel_e = Entry(self.StatSel_fm, - selectbackground = 'yellow', - textvariable = self.StatSel) - self.StatSel_e.pack(side='left', anchor='w',expand=1, fill='x') - self.balloon.bind(self.StatSel_e, "Filter trace search \nfor these stations") + selectbackground='yellow', + textvariable=self.StatSel) + self.StatSel_e.pack(side='left', anchor='w', expand=1, fill='x') + self.balloon.bind( + self.StatSel_e, "Filter trace search \nfor these stations") self.ClearStatSel_b = Button(self.StatSel_fm, - activebackground = 'orange', - relief = "ridge", - text = "Clear", - command = Command(self.setValue, self.StatSel) + activebackground='orange', + relief="ridge", + text="Clear", + command=Command( + self.setValue, self.StatSel) ) self.ClearStatSel_b.pack(side='right') self.balloon.bind(self.ClearStatSel_b, "Clear station filter") - #setup frame for station substitutions. to be filled later - self.StatChanList_fm.pack(side = 'top', pady = 5, fill = 'x') + # setup frame for station substitutions. to be filled later + self.StatChanList_fm.pack(side='top', pady=5, fill='x') ################################################################## - def buildGlobal(self,master): + + def buildGlobal(self, master): """ Populate Global NoteBook for making global changes to headers """ self.GlobalFix_nb = master.add('Global Modify') - self.Button_fm = Frame(self.GlobalFix_nb, borderwidth = 2) - self.Button_fm.pack(side = 'bottom', padx= 5, pady=5, fill = 'x') - self.GlobalFix_fm = Frame(self.GlobalFix_nb, relief = 'groove', borderwidth = 2) + self.Button_fm = Frame(self.GlobalFix_nb, borderwidth=2) + self.Button_fm.pack(side='bottom', padx=5, pady=5, fill='x') + self.GlobalFix_fm = Frame( + self.GlobalFix_nb, relief='groove', borderwidth=2) - #buttons + # buttons self.ClearUpdateDict_b = Button(self.Button_fm, - text = "Clear Update Dictionary", - relief = "ridge", - cursor = 'X_cursor', - command = Command( + text="Clear Update Dictionary", + relief="ridge", + cursor='X_cursor', + command=Command( self.ClearAllTrace, 1), - activebackground= 'orange', + activebackground='orange', activeforeground='black') self.ClearUpdateDict_b.pack(side='right', anchor='e') - self.balloon.bind(self.ClearUpdateDict_b, "Clears all entries \nin 'Update Dictionary'") + self.balloon.bind(self.ClearUpdateDict_b, + "Clears all entries \nin 'Update Dictionary'") self.clear_b = Button(self.Button_fm, - text = "Clear Current", - relief = "ridge", - cursor = 'X_cursor', - command = Command( + text="Clear Current", + relief="ridge", + cursor='X_cursor', + command=Command( self.ClearAllGlobal, self.GlobalListVars), - activebackground= 'orange', + activebackground='orange', activeforeground='black') self.clear_b.pack(side='right', anchor='e') self.balloon.bind(self.clear_b, "Clears all \ncurrent entries") self.GlobalSet_b = Button(self.Button_fm, - text = "Global Set", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.GlobalSet), + text="Global Set", + relief="ridge", + cursor='X_cursor', + command=Command(self.GlobalSet), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.GlobalSet_b.pack(side='right', anchor='e') self.balloon.bind(self.GlobalSet_b, "Add current entries \nto 'Update Dictionary'") - #we let user see directory selection here but they don't have - #access to manipulation buttons found on Trace Headers notebook + # we let user see directory selection here but they don't have + # access to manipulation buttons found on Trace Headers notebook self.DataDirs_fm = Frame( - self.GlobalFix_nb, relief = 'groove', borderwidth = 2) - self.DataDirs_fm.pack(side = 'top', pady=5, fill = 'x') + self.GlobalFix_nb, relief='groove', borderwidth=2) + self.DataDirs_fm.pack(side='top', pady=5, fill='x') self.DataDirs_l = Label( self.DataDirs_fm, text='Current Data Directories: ') self.DataDirs_l.pack(side='left') @@ -875,91 +931,93 @@ class MainWindow: "Traces located \nbeneath these \ndirectories") self.DataDirs_e = Entry(self.DataDirs_fm, - selectbackground = 'yellow', - textvariable = self.DataDirs) - self.DataDirs_e.pack(side='left', anchor='w',expand=1, fill='x') + selectbackground='yellow', + textvariable=self.DataDirs) + self.DataDirs_e.pack(side='left', anchor='w', expand=1, fill='x') - #setup frame for global substitutions. to be filled later - self.GlobalFix_fm.pack(side = 'top', pady = 5, fill = 'x') + # setup frame for global substitutions. to be filled later + self.GlobalFix_fm.pack(side='top', pady=5, fill='x') ################################################################## - def buildTimeShift(self,master): + + def buildTimeShift(self, master): """ Populate Time Shift NoteBook for applying time corrections to headers """ self.TimeShift_nb = master.add('Time Shift') - self.Button_fm = Frame(self.TimeShift_nb, borderwidth = 2) - self.Button_fm.pack(side = 'bottom', padx= 5, pady=5, fill = 'x') - self.TimeShift_fm = Frame(self.TimeShift_nb, relief = 'groove', borderwidth = 2) + self.Button_fm = Frame(self.TimeShift_nb, borderwidth=2) + self.Button_fm.pack(side='bottom', padx=5, pady=5, fill='x') + self.TimeShift_fm = Frame( + self.TimeShift_nb, relief='groove', borderwidth=2) - #buttons + # buttons self.clear_b = Button(self.Button_fm, - text = "Clear All", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.ResetTimeShift), - activebackground= 'orange', + text="Clear All", + relief="ridge", + cursor='X_cursor', + command=Command(self.ResetTimeShift), + activebackground='orange', activeforeground='black') self.clear_b.pack(side='right', anchor='e') self.balloon.bind(self.clear_b, "Clears all \ncurrent entries") self.ReCalc_b = Button(self.Button_fm, - text = "Recalc Start/End", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.RecalcStartEnd), + text="Recalc Start/End", + relief="ridge", + cursor='X_cursor', + command=Command(self.RecalcStartEnd), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.ReCalc_b.pack(side='right', anchor='e') self.balloon.bind( self.ReCalc_b, "Recalculate start and \nend times for selected traces") self.TimeSet_b = Button(self.Button_fm, - text = "Time Set", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.TimeDictSet), + text="Time Set", + relief="ridge", + cursor='X_cursor', + command=Command(self.TimeDictSet), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.TimeSet_b.pack(side='right', anchor='e') self.balloon.bind(self.TimeSet_b, "Add current entries \nto 'Update Dictionary'") self.ApplyTime_b = Button(self.Button_fm, - text = "Apply Time Correction", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.LaunchApplyTimeCor), + text="Apply Time Correction", + relief="ridge", + cursor='X_cursor', + command=Command(self.LaunchApplyTimeCor), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.ApplyTime_b.pack(side='right', anchor='e') self.balloon.bind( self.ApplyTime_b, "Modifies trace times using current entries " "\nand all entries in 'Update Dictionary'") self.listtimecor_b = Button(self.Button_fm, - text = "List Time Corrections", - relief = "ridge", - cursor = 'X_cursor', - command = Command( + text="List Time Corrections", + relief="ridge", + cursor='X_cursor', + command=Command( self.ListTimeCor, self.TimeShift_nb), - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.listtimecor_b.pack(side='left', anchor='e') self.balloon.bind( self.listtimecor_b, "List time corrections \ncurrently in trace " "headers \nfor select Stat:Loc:Net") - #we let user see directory selection here but they don't have - #access to manipulation buttons found on Trace Headers notebook + # we let user see directory selection here but they don't have + # access to manipulation buttons found on Trace Headers notebook self.DataDirs_fm = Frame( - self.TimeShift_nb, relief = 'groove', borderwidth = 2) - self.DataDirs_fm.pack(side = 'top', pady=5, fill = 'x') + self.TimeShift_nb, relief='groove', borderwidth=2) + self.DataDirs_fm.pack(side='top', pady=5, fill='x') self.DataDirs_l = Label( self.DataDirs_fm, text='Current Data Directories: ') self.DataDirs_l.pack(side='left') @@ -967,61 +1025,61 @@ class MainWindow: "Traces located \nbeneath these \ndirectories") self.DataDirs_e = Entry(self.DataDirs_fm, - selectbackground = 'yellow', - textvariable = self.DataDirs) - self.DataDirs_e.pack(side='left', anchor='w',expand=1, fill='x') + selectbackground='yellow', + textvariable=self.DataDirs) + self.DataDirs_e.pack(side='left', anchor='w', expand=1, fill='x') - #time correction type buttons + # time correction type buttons self.RadButtons_fm = Frame( - self.TimeShift_nb, relief = 'groove', borderwidth = 2) - self.RadButtons_fm.pack(side = 'top', pady=5, fill = 'x') + self.TimeShift_nb, relief='groove', borderwidth=2) + self.RadButtons_fm.pack(side='top', pady=5, fill='x') self.UndoTimeCor_b = Button(self.RadButtons_fm, - text = "Undo Time Corrections", - relief = "ridge", - cursor = 'X_cursor', - command = Command(self.LaunchUndoTimeCor), + text="Undo Time Corrections", + relief="ridge", + cursor='X_cursor', + command=Command(self.LaunchUndoTimeCor), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.UndoTimeCor_b.pack(side='right', anchor='e') self.balloon.bind(self.UndoTimeCor_b, "Reverse applied \ntime corrections") - - self.TimeRad_l=Label(self.RadButtons_fm, - text="How to Treat Existing Corrections:") + self.TimeRad_l = Label(self.RadButtons_fm, + text="How to Treat Existing Corrections:") self.TimeRad_l.pack(side='left', anchor='e') self.balloon.bind( self.TimeRad_l, "When applying time corrections: \nAdd to " "existing or \nZero and replace existing") - for text, value in (["Add To",0],["Replace",1]): + for text, value in (["Add To", 0], ["Replace", 1]): Radiobutton( - self.RadButtons_fm, text=text,value=value, + self.RadButtons_fm, text=text, value=value, variable=self.TypeTimeCor).pack(side='left', anchor='e') - #setup frame for global substitutions. to be filled later - self.TimeShift_fm.pack(side = 'top', pady = 5, fill = 'x') + # setup frame for global substitutions. to be filled later + self.TimeShift_fm.pack(side='top', pady=5, fill='x') ################################################################## - def buildEndian(self,master): + + def buildEndian(self, master): """ Populate Endian NoteBook for swapping endianess of headers """ self.Endian_nb = master.add('Endianess') - self.Endian_fm = Frame(self.Endian_nb, relief = 'groove', borderwidth = 2) + self.Endian_fm = Frame(self.Endian_nb, relief='groove', borderwidth=2) - #buttons + # buttons self.ToBig_b = Button(self.Endian_fm, - text = "Convert to Big", - relief = "ridge", - cursor = 'X_cursor', - command = Command( + text="Convert to Big", + relief="ridge", + cursor='X_cursor', + command=Command( self.LaunchChangeEndian, "big"), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.ToBig_b.grid(row=1, column=3, sticky=W) self.balloon.bind(self.ToBig_b, "Convert all little \nendian files to \nbig endian") @@ -1029,22 +1087,22 @@ class MainWindow: Label(self.Endian_fm, text="Little Endian Files Found: ").grid( row=1, column=1, sticky=W) Entry(self.Endian_fm, - width = 8, - relief = "flat", - justify = "right", - background = 'yellow', - textvariable = self.NumLittleFiles).grid( + width=8, + relief="flat", + justify="right", + background='yellow', + textvariable=self.NumLittleFiles).grid( row=1, column=2, sticky=W) self.ToLittle_b = Button(self.Endian_fm, - text = "Convert to Little", - relief = "ridge", - cursor = 'X_cursor', - command = Command( + text="Convert to Little", + relief="ridge", + cursor='X_cursor', + command=Command( self.LaunchChangeEndian, "little"), background='lightblue', - activebackground= 'green', - activeforeground= 'black') + activebackground='green', + activeforeground='black') self.ToLittle_b.grid(row=2, column=3, sticky=W) self.balloon.bind(self.ToLittle_b, "Convert all big \nendian files to \nlittle endian") @@ -1052,17 +1110,17 @@ class MainWindow: Label(self.Endian_fm, text="Big Endian Files Found: ").grid( row=2, column=1, sticky=W) Entry(self.Endian_fm, - width = 8, - relief = "flat", - justify = "right", - background = 'yellow', - textvariable = self.NumBigFiles).grid(row=2, column=2, sticky=W) - - #we let user see directory selection here but they don't have - #access to manipulation buttons found on Trace Headers notebook + width=8, + relief="flat", + justify="right", + background='yellow', + textvariable=self.NumBigFiles).grid(row=2, column=2, sticky=W) + + # we let user see directory selection here but they don't have + # access to manipulation buttons found on Trace Headers notebook self.DataDirs_fm = Frame( - self.Endian_nb, relief = 'groove', borderwidth = 2) - self.DataDirs_fm.pack(side = 'top', pady=5, fill = 'x') + self.Endian_nb, relief='groove', borderwidth=2) + self.DataDirs_fm.pack(side='top', pady=5, fill='x') self.DataDirs_l = Label( self.DataDirs_fm, text='Current Data Directories: ') self.DataDirs_l.pack(side='left') @@ -1070,14 +1128,15 @@ class MainWindow: "Traces located \nbeneath these \ndirectories") self.DataDirs_e = Entry(self.DataDirs_fm, - selectbackground = 'yellow', - textvariable = self.DataDirs) - self.DataDirs_e.pack(side='left', anchor='w',expand=1, fill='x') + selectbackground='yellow', + textvariable=self.DataDirs) + self.DataDirs_e.pack(side='left', anchor='w', expand=1, fill='x') - self.Endian_fm.pack(side = 'top', pady = 5, fill = 'x') + self.Endian_fm.pack(side='top', pady=5, fill='x') ################################################################## - def buildLog(self,master): + + def buildLog(self, master): """ Populate Log NoteBook for keeping track of changes """ @@ -1088,10 +1147,10 @@ class MainWindow: self.LogText = Pmw.ScrolledText(self.Log_nb, borderframe=1) - #log_filters + # log_filters self.RadButtons_fm = Frame( - self.Log_nb, relief = 'groove', borderwidth = 2) - self.RadButtons_fm.pack(side = 'top', pady=5, fill = 'x') + self.Log_nb, relief='groove', borderwidth=2) + self.RadButtons_fm.pack(side='top', pady=5, fill='x') self.DisplayLog_l = Label( self.RadButtons_fm, text='Display messages for: ') self.DisplayLog_l.pack(side='left') @@ -1104,7 +1163,7 @@ class MainWindow: command=Command(self.DisplayLog), variable=self.LogVar).pack(side='left', anchor='e') - #buttons + # buttons self.Clear_b = Button(self.Log_fm, text='Clear Logs', relief='ridge', @@ -1137,28 +1196,29 @@ class MainWindow: self.LogText.pack(side='bottom', fill='both', expand=1) - #tags used for highlighting log entries + # tags used for highlighting log entries self.LogText.tag_config('blue', foreground='blue') self.LogText.tag_config('dkgreen', foreground='darkgreen') self.LogText.tag_config('red', foreground='red') self.LogText.tag_config('black', foreground='black') ################################################################## + def BuildLists(self): """ builds lists drop downs in global modify and timeshift notebook """ - #clean any old entries + # clean any old entries del self.StationList[:] del self.ChannelList[:] del self.LocList[:] del self.NetList[:] del self.SpsList[:] - #build lists for drop down selections - for key in self.TraceDict : - (stat,chan,loc,net,sps) = key.split(":") + # build lists for drop down selections + for key in self.TraceDict: + (stat, chan, loc, net, sps) = key.split(":") if stat not in self.StationList: self.StationList.append(stat) if not self.ChannelList.count(chan): @@ -1170,14 +1230,14 @@ class MainWindow: if not self.SpsList.count(sps): self.SpsList.append(sps) - #add wildcard entry + # add wildcard entry self.StationList.append("*") self.ChannelList.append("*") self.LocList.append("*") self.NetList.append("*") self.SpsList.append("*") - #sort lists + # sort lists self.StationList = sorted(self.StationList) self.ChannelList = sorted(self.ChannelList) self.LocList = sorted(self.LocList) @@ -1185,6 +1245,7 @@ class MainWindow: self.SpsList = sorted(self.SpsList) ####################################### + def BuildTrcList(self): """ build a trace list using DataDirList as base directories @@ -1192,30 +1253,29 @@ class MainWindow: # clear infostring self.addTextInfoBar() - - #kill warn window if it exist (i.e. user got here from self.Ignore) - #this may not longer be necessary + # kill warn window if it exist (i.e. user got here from self.Ignore) + # this may not longer be necessary try: self.killWindow(self.WarnWidget_tl) - except Exception as e: + except Exception: pass - #initialize lists + # initialize lists self.DataDirList = [] self.StatSelList = [] - self.BigEndianList=[] - self.LittleEndianList=[] - self.TimeCorrectedFiles={} + self.BigEndianList = [] + self.LittleEndianList = [] + self.TimeCorrectedFiles = {} n = 0 # split directory string & test they exist before launching into # self.FindTrace # populate DataDirList - for idir in self.DataDirs.get().split(":") : + for idir in self.DataDirs.get().split(":"): dirlist = glob(idir) for newdir in dirlist: if not os.path.isdir(newdir): - err="***WARNING*** Directory " + newdir + " not found." + err = "***WARNING*** Directory " + newdir + " not found." self.addTextInfoBar(err, "red") return self.DataDirList.append(newdir) @@ -1224,7 +1284,7 @@ class MainWindow: if self.StatSel.get() == "*" or self.StatSel.get() == "": pass else: - for statsel in self.StatSel.get().split(":") : + for statsel in self.StatSel.get().split(":"): statsel = statsel.strip() self.StatSelList.append(statsel) @@ -1233,13 +1293,13 @@ class MainWindow: # have a variable to watch status of process # next I spawn a thread to FindTrace self.RunBuilddb.set(1) - #tRun=threading.Thread(target=self.LaunchFindTrace) + # tRun=threading.Thread(target=self.LaunchFindTrace) self.LaunchFindTrace() - #tRun.start() + # tRun.start() # stay here until thread dies - #tRun.join() + # tRun.join() - #fill/update notebooks if not running batch mode + # fill/update notebooks if not running batch mode if not BATCHMODE: info = "Building lists, updating frames" self.addTextInfoBar(info) @@ -1249,38 +1309,39 @@ class MainWindow: self.UpdateGlobalList(self.GlobalFix_fm) self.NumBigFiles.set(len(self.BigEndianList)) self.NumLittleFiles.set(len(self.LittleEndianList)) - #clear any lingering updates + # clear any lingering updates self.UpdateHdrDict = {} self.SetHdrDict = {} self.UpdateTimeDict = {} self.SetTimeDict = {} self.ClearAll(self.SetHdrVars) self.ClearAll(self.NewVars) - text= "\n" + str(self.FoundFiles.get()) + \ + text = "\n" + str(self.FoundFiles.get()) + \ " unique mseed files found. *** " \ + str(self.RWErrors.get()) + " files with errors. See Log." self.addTextInfoBar(text, "green") self.root.bell() - #insert info on Log notebook + # insert info on Log notebook if not BATCHMODE: self.WriteLog("\n<Build Trace db>", "All", "blue") dirs = "Directories searched: " + self.DataDirs.get() - self.WriteLog(dirs,"All","black") - self.WriteLog(text,"All","black") + self.WriteLog(dirs, "All", "black") + self.WriteLog(text, "All", "black") if self.StatChanList: - self.WriteLog("\t<Unique ID's found:>","All", "dkgreen") + self.WriteLog("\t<Unique ID's found:>", "All", "dkgreen") for item in self.StatChanList: - self.WriteLog("\t"+item,"All", "black") - self.WriteLog("\t<end>","All", "dkgreen") - self.WriteLog("<end>","All", "blue") + self.WriteLog("\t" + item, "All", "black") + self.WriteLog("\t<end>", "All", "dkgreen") + self.WriteLog("<end>", "All", "blue") - #since we just rebuilt db no files have been altered + # since we just rebuilt db no files have been altered self.AlteredText.set("") return ####################################### - def LaunchFindTrace(self) : + + def LaunchFindTrace(self): """ separated out so FindTrace could be run as a thread @@ -1288,7 +1349,7 @@ class MainWindow: if not BATCHMODE: self.CancelTL(self.RunBuilddb, "Build Trace db") - (self.TraceDict, self.TraceTimeDict, NumFiles,rwError) = \ + (self.TraceDict, self.TraceTimeDict, NumFiles, rwError) = \ self.FindTrace(self.DataDirList) if self.RunBuilddb.get() and not BATCHMODE: @@ -1299,11 +1360,12 @@ class MainWindow: return ####################################### - def FindTrace(self, DataDir) : + + def FindTrace(self, DataDir): """ based on traverse routine in "python standard library", Lundh pg 34 """ - #local variables + # local variables stack = [] losjoin = os.path.join losaccess = os.access @@ -1316,7 +1378,7 @@ class MainWindow: appendBigEndian = self.BigEndianList.append appendLittleEndian = self.LittleEndianList.append # build stack of input directories - for k in range(len(DataDir)) : + for k in range(len(DataDir)): if not DataDir[k] in stack: stackappend(DataDir[k]) # init several list and dictionaries @@ -1324,32 +1386,32 @@ class MainWindow: file_list = {} time_list = {} NumMseedFiles = 0 - rwError=0 - cnt=1 + rwError = 0 + cnt = 1 - #loop while directories still exist in stack - while stack : + # loop while directories still exist in stack + while stack: directory = stackpop() if not losaccess(directory, 5): text = "Skipped: %s" % directory text1 = "\t\tAccess Error" - self.WriteLog(text,"All","red") - self.WriteLog(text1,"All","black") + self.WriteLog(text, "All", "red") + self.WriteLog(text1, "All", "black") continue try: - genfiles=(ifile for ifile in loslistdir(directory)) - except StandardError as e: + genfiles = (ifile for ifile in loslistdir(directory)) + except Exception as e: print("Directory Read Error: %s" % e) continue - while 1: + while True: try: file = next(genfiles) except StopIteration: break - #respond to a cancel request + # respond to a cancel request if not self.RunBuilddb.get(): break # keep user posted of progress @@ -1357,31 +1419,31 @@ class MainWindow: pass else: self.wait("Examining File: ", cnt) - #build up list of mseed files w/ full pathnames + # build up list of mseed files w/ full pathnames fullname = losjoin(directory, file) - if losisfile(fullname) : + if losisfile(fullname): if not losaccess(fullname, 6): - err= "ERROR: Read/Write permission denied. "\ + err = "ERROR: Read/Write permission denied. "\ "\n\t File:" + fullname - self.WriteLog(err,"Header","red") - rwError+=1 + self.WriteLog(err, "Header", "red") + rwError += 1 continue try: msfile = Mseed(fullname) - if msfile.isMseed() : + if msfile.isMseed(): try: - #simple test to determine if correct size file + # simple test to determine if correct size file filesize = msfile.filesize blksize = msfile.blksize numblocks = msfile.numblocks except Exception as e: - err= "ERROR: Cannot determine file and block"\ - " sizes. \n\t File:" + fullname - self.WriteLog(err,"Header","red") - rwError+=1 + err = ("ERROR: Cannot determine file and " + "block sizes. \n\t File:" + fullname) + self.WriteLog(err, "Header", "red") + rwError += 1 continue - #assign header info + # assign header info type = msfile.type rate = msfile.rate time = msfile.time @@ -1390,69 +1452,71 @@ class MainWindow: loc = msfile.FH.Loc.decode().strip() net = msfile.FH.Net.decode().strip() - #window on specific stations if exist + # window on specific stations if exist if self.StatSelList: - if not stat in self.StatSelList: + if stat not in self.StatSelList: continue # build endian lists if msfile.byteorder == "big": - if not fullname in self.BigEndianList: + if fullname not in self.BigEndianList: appendBigEndian(fullname) else: - if not fullname in self.LittleEndianList: + if fullname not in self.LittleEndianList: appendLittleEndian(fullname) - #build file list for fixing headers - fileid = ":".join(map(str,( - stat,chan,loc,net,rate))) - #fileid= str(stat) + ":" + chan + ":" + loc + ":"\ - # + net + ":" + str(rate) + # build file list for fixing headers + fileid = ":".join(map(str, ( + stat, chan, loc, net, rate))) + # fileid= (str(stat) + ":" + chan + ":" + loc + ":" + # + net + ":" + str(rate)) try: - if not fullname in file_list[fileid]: + if fullname not in file_list[fileid]: file_list[fileid].append(fullname) - NumMseedFiles+=1 + NumMseedFiles += 1 except KeyError: file_list[fileid] = [] file_list[fileid].append(fullname) - NumMseedFiles+=1 + NumMseedFiles += 1 # build empty time_list to fill later with # GetStartEnd - timeid = ":".join(map(str,(stat,loc,net)),) - #timeid = ":".join(map(str,(stat,loc,net)),) - #timeid=str(stat) + ":" + loc + ":" + net - #if not time_list.has_key(timeid) : + timeid = ":".join( + list(map(str, (stat, loc, net))),) + # timeid = ":".join(map(str,(stat,loc,net)),) + # timeid=str(stat) + ":" + loc + ":" + net + # if not time_list.has_key(timeid) : time_list[timeid] = [] msfile.close() - except StandardError as e: + except Exception as e: print("File Open Error: %s" % e) print(fullname) - cnt+=1 + cnt += 1 # add fullname to stack if it is a directory or link - if losisdir(fullname) or (losislink(fullname) \ - and not losisfile(fullname)): - if not fullname in stack: + if losisdir(fullname) or (losislink(fullname) and + not losisfile(fullname)): + if fullname not in stack: stackappend(fullname) return file_list, time_list, NumMseedFiles, rwError ################################################################## - def UpdateHdrList(self,fm): + + def UpdateHdrList(self, fm): """ create HdrList entries This is extracted from the buildHdrList to allow for dynamic update of header list """ - #build list for stat:chan:loc:net:sps selection dropdown + # build list for stat:chan:loc:net:sps selection dropdown self.StatChanList = sorted(list(self.TraceDict.keys())) self.ClearAll(self.StatChanListVars) if not self.StatChanList: self.addTextInfoBar("No Data Found", 'orange') - #build dropdown and entry boxes - n=0 + # build dropdown and entry boxes + n = 0 for var in self.StatChanListVars: Label(fm, text=var[0]).grid(row=n, sticky=W) if var[0] == "Stat:Chan:Loc:Net:Sps": @@ -1465,33 +1529,34 @@ class MainWindow: ).grid(row=n, column=1, sticky=W) Label(fm, text="New Values").grid(row=n, column=2, sticky=W) Label(fm, text="Applied").grid(row=n, column=3, sticky=W) - else : + else: Entry(fm, - width = self.e_width, - selectbackground = 'yellow', - textvariable = var[1]).grid(row=n, column=1, sticky=W) + width=self.e_width, + selectbackground='yellow', + textvariable=var[1]).grid(row=n, column=1, sticky=W) - if 1<=n and n <=4 : + if 1 <= n and n <= 4: Entry(fm, - width = self.e_width, - selectbackground = 'yellow', - textvariable = self.NewVars[n-1][1]).grid( + width=self.e_width, + selectbackground='yellow', + textvariable=self.NewVars[n - 1][1]).grid( row=n, column=2, sticky=W) - n+=1 + n += 1 - #build boxes indicating if update is applied - n=1 + # build boxes indicating if update is applied + n = 1 for var in self.SetHdrVars: Checkbutton(fm, - variable = var[1], - text = " ", - indicatoron = "FALSE", - selectcolor = "green", - state = "disabled" + variable=var[1], + text=" ", + indicatoron="FALSE", + selectcolor="green", + state="disabled" ).grid(row=n, column=3) - n+=1 + n += 1 ######################################### + def UpdateHdr(self, name=""): """ builds UpdateHdrDict based on entries in NewValues @@ -1500,7 +1565,7 @@ class MainWindow: # assign new values to UpdateHdrDict for var in self.NewVars: testkey = self.OldSID.get() - if testkey in self.UpdateHdrDict : + if testkey in self.UpdateHdrDict: if var[1].get(): value = var[1].get().upper() if var[0] in self.UpdateHdrDict[testkey]: @@ -1508,12 +1573,12 @@ class MainWindow: if testkey in self.SetHdrDict: if var[0] in self.SetHdrDict[testkey]: del self.SetHdrDict[testkey][var[0]] - self.UpdateHdrDict[testkey][var[0]]=value - else : - if var[1].get() : + self.UpdateHdrDict[testkey][var[0]] = value + else: + if var[1].get(): self.UpdateHdrDict[testkey] = {} value = var[1].get().upper() - self.UpdateHdrDict[testkey][var[0]]=value + self.UpdateHdrDict[testkey][var[0]] = value self.ClearAll(self.NewVars) # populate current header listing with new selection @@ -1523,7 +1588,7 @@ class MainWindow: if n == 0: self.setValue(var[1], name) else: - setval = name.split(":")[n-1] + setval = name.split(":")[n - 1] self.setValue(var[1], setval) n += 1 @@ -1534,12 +1599,12 @@ class MainWindow: setval = self.UpdateHdrDict[name][var[0]] self.setValue(var[1], setval) - #fill in Applied buttons + # fill in Applied buttons self.ClearAll(self.SetHdrVars) if name in self.SetHdrDict: for var in self.SetHdrVars: if var[0] in self.SetHdrDict[name]: - setval =self.SetHdrDict[name][var[0]] + setval = self.SetHdrDict[name][var[0]] self.setValue(var[1], setval) self.OldSID.set(name) @@ -1547,7 +1612,7 @@ class MainWindow: try: if self.TraceList_tl.winfo_exists(): self.ListTrace(self.StatChanList_nb) - except Exception as e: + except Exception: pass # give user info on traces selected @@ -1557,13 +1622,14 @@ class MainWindow: self.addTextInfoBar(textstr, 'lightblue') ####################################### - def LaunchModHdrs(self) : + + def LaunchModHdrs(self): """ separated out so ModHdrs could be run as a thread """ - #if headers have already been alterred warn user + # if headers have already been alterred warn user if self.SetHdrDict or self.SetTimeDict: self.WarnWidget(self.StatChanList_nb, "headers") self.WarnWidget_tl.wait_window() @@ -1572,20 +1638,21 @@ class MainWindow: elif self.CancelWarn.get(): return - #if the user ignores warning proceed + # if the user ignores warning proceed self.RunModHdrs.set(1) - #mRun=threading.Thread(target=self.ModHdrs) + # mRun=threading.Thread(target=self.ModHdrs) self.ModHdrs() - #mRun.start() + # mRun.start() # stay here until thread dies - #mRun.join() + # mRun.join() if self.RunModHdrs.get(): self.KillCancelTL(self.RunModHdrs) self.IgnoreWarn.set(0) ####################################### + def ModHdrs(self): """ uses values in UpdateHdrDict to modify headers for traces in @@ -1595,7 +1662,8 @@ class MainWindow: self.CancelTL(self.RunModHdrs, "Modify Headers") self.addTextInfoBar() - # first make sure any current 'new values' are saved to UpdateHdrDict + # first make sure any current 'new values' are saved to + # UpdateHdrDict self.UpdateHdr(self.StationName.get()) if not self.StationName.get() and not self.UpdateHdrDict: self.addTextInfoBar("No Station Selected", 'orange') @@ -1605,7 +1673,9 @@ class MainWindow: return self.ActiveText.set("Modify Headers Running") - self.AlteredText.set("Headers or blockette times have been modified.\n Rebuild database to avoid unexpected results.\n") + self.AlteredText.set("Headers or blockette times have been modified." + "\n Rebuild database to avoid unexpected " + "results.\n") # now make mods to headers for all keys (sta:chan:loc:net:sps) in # UpdateHdrDict @@ -1616,34 +1686,34 @@ class MainWindow: for key in inlist: if key not in self.SetHdrDict: self.SetHdrDict[key] = {} - if key in self.TraceDict : - #set new values if exist and keep track - #of modifications in SetHdrDict + if key in self.TraceDict: + # set new values if exist and keep track + # of modifications in SetHdrDict Stat = Loc = Chan = Net = "" skeylist = (skey for skey in self.UpdateHdrDict[key]) - while 1: + while True: try: subkey = next(skeylist) except StopIteration: break - #for subkey in self.UpdateHdrDict[key].keys() : + # for subkey in self.UpdateHdrDict[key].keys() : value = self.UpdateHdrDict[key][subkey] if subkey == "Station_Name": Stat = value - self.SetHdrDict[key][subkey]=1 + self.SetHdrDict[key][subkey] = 1 if subkey == "Channel": Chan = value - self.SetHdrDict[key][subkey]=1 + self.SetHdrDict[key][subkey] = 1 if subkey == "Location_Code": Loc = value - self.SetHdrDict[key][subkey]=1 + self.SetHdrDict[key][subkey] = 1 if subkey == "Network_Code": Net = value - self.SetHdrDict[key][subkey]=1 - ifilelist=(ifile for ifile in self.TraceDict[key]) - #for infile in self.TraceDict[key] : - #respond to cancel requests - while 1: + self.SetHdrDict[key][subkey] = 1 + ifilelist = (ifile for ifile in self.TraceDict[key]) + # for infile in self.TraceDict[key] : + # respond to cancel requests + while True: try: infile = next(ifilelist) except StopIteration: @@ -1662,18 +1732,18 @@ class MainWindow: filesize = msfile.filesize blksize = msfile.blksize numblocks = msfile.numblocks - #(numblocks, odd_size)=divmod(filesize, blksize) - ## should not be needed, but not expensive - #if odd_size: - #warn="WARNING: File size is not an integer number "\ - # "of block size (+ str(blksize) +"). File: " + infile - #self.WriteLog(warn,"Header","red") - #warn_cnt+=1 + # (numblocks, odd_size)=divmod(filesize, blksize) + # should not be needed, but not expensive + # if odd_size: + # warn="WARNING: File size is not an integer number "\ + # "of block size (+ str(blksize) +"). File: " + infile + # self.WriteLog(warn,"Header","red") + # warn_cnt+=1 # loop over all blocks and correct headers blk = 0 while blk < numblocks: - hdrs = msfile.fixedhdr(blk*blksize) + hdrs = msfile.fixedhdr(blk * blksize) (SeqNum, DHQual, res, oldStat, oldLoc, oldChan, oldNet) = hdrs[0] if not Stat: @@ -1687,27 +1757,27 @@ class MainWindow: newhdrs = ((SeqNum, DHQual, res, Stat, Loc, Chan, Net), hdrs[1], hdrs[2], hdrs[3]) bytes_written = msfile.WriteFixedHdr( - newhdrs, blk*blksize) + newhdrs, blk * blksize) blk += 1 msfile.close() - #do some cleanup + # do some cleanup self.ClearAll(self.StatChanListVars) self.ClearAll(self.SetHdrVars) self.ClearAll(self.NewVars) if error_cnt or warn_cnt: text = SPACE.join(("Modified Headers in ", str(cnt - error_cnt), - " files. Encountered " , str(error_cnt), - " error(s) & ", str(warn_cnt)," warning(s)")) + " files. Encountered ", str(error_cnt), + " error(s) & ", str(warn_cnt), " warning(s)")) self.addTextInfoBar(text, "orange") else: - text = SPACE.join(("Modified Headers in ",str(cnt)," files")) + text = SPACE.join(("Modified Headers in ", str(cnt), " files")) self.addTextInfoBar(text, "green") - #insert info on Log notebook + # insert info on Log notebook self.WriteLog("\n<Modify Headers>", "Header", "blue") if error_cnt or warn_cnt: - self.WriteLog(text , "Header", "red") + self.WriteLog(text, "Header", "red") else: self.WriteLog(text, "Header", "black") self.DumpUpdateDicts("mod") @@ -1722,11 +1792,11 @@ class MainWindow: builds drop downs for global modify notebook """ - #build drop down and new entries + # build drop down and new entries Label(fm, text="For Headers Matching:").grid( row=0, column=1, sticky=W) Label(fm, text="Substitute Values:").grid(row=0, column=2, sticky=W) - n=1 + n = 1 for var in self.GlobalListVars: Label(fm, text=var[0]).grid(row=n, sticky=W) Pmw.ComboBox(fm, @@ -1735,22 +1805,23 @@ class MainWindow: entry_textvariable=var[1], scrolledlist_items=(var[2]) ).grid(row=n, column=1, sticky=W) - if var[0] != "Sample_Rate" : + if var[0] != "Sample_Rate": Entry(fm, - width = self.e_width, - selectbackground = 'yellow', - textvariable = var[3]).grid(row=n, column=2, sticky=W) - #set wildcard as default + width=self.e_width, + selectbackground='yellow', + textvariable=var[3]).grid(row=n, column=2, sticky=W) + # set wildcard as default var[1].set("*") - n+=1 + n += 1 ####################################### + def GlobalSet(self): """ build UpdateHdrDict """ self.addTextInfoBar() - #check if mods are enterred + # check if mods are enterred if not self.GUStation.get() \ and not self.GUChannel.get() \ and not self.GULocCode.get() \ @@ -1759,23 +1830,18 @@ class MainWindow: return for key in self.TraceDict: - #make sure there are no lingering NewVars + # make sure there are no lingering NewVars self.ClearAll(self.NewVars) - (stat,chan,loc,net,sps) = key.split(":") - if (self.GlobalStation.get() == "*" \ - or self.GlobalStation.get() == stat) \ - and \ - (self.GlobalChannel.get() == "*" \ - or self.GlobalChannel.get() == chan)\ - and \ - (self.GlobalLocCode.get() == "*" \ - or self.GlobalLocCode.get() == loc)\ - and \ - (self.GlobalNetCode.get() == "*" \ - or self.GlobalNetCode.get() == net)\ - and \ - (self.GlobalSps.get() == "*" \ - or self.GlobalSps.get() == sps): + (stat, chan, loc, net, sps) = key.split(":") + if (self.GlobalStation.get() == "*" or + self.GlobalStation.get() == stat) and \ + (self.GlobalChannel.get() == "*" or + self.GlobalChannel.get() == chan) and \ + (self.GlobalLocCode.get() == "*" or + self.GlobalLocCode.get() == loc) and \ + (self.GlobalNetCode.get() == "*" or + self.GlobalNetCode.get() == net) and \ + (self.GlobalSps.get() == "*" or self.GlobalSps.get() == sps): if self.GUStation.get(): self.NStation.set(self.GUStation.get()) @@ -1810,12 +1876,13 @@ class MainWindow: self.addTextInfoBar(info, 'green') ####################################### + def TimeDictSet(self): """ build UpdateTimeDict """ self.addTextInfoBar() - #check input formats before committing to UpdateTimeDict + # check input formats before committing to UpdateTimeDict if not self.TimeShiftName.get(): if self.UpdateTimeDict: return 1 @@ -1852,23 +1919,23 @@ class MainWindow: self.addTextInfoBar(err, 'red') return 0 - #Create UpdateTimeDict entry. THIS OVERWRITES any previous entry - #I overwrite since when a user selects Stat:Loc:Net on Notebook - #they are informed if an entry exists and if it has been applied. - #User beware - (stat,loc,net) = self.TimeShiftName.get().split(':') + # Create UpdateTimeDict entry. THIS OVERWRITES any previous entry + # I overwrite since when a user selects Stat:Loc:Net on Notebook + # they are informed if an entry exists and if it has been applied. + # User beware + (stat, loc, net) = self.TimeShiftName.get().split(':') for key in self.TraceTimeDict: (TTD_stat, TTD_loc, TTD_net) = key.split(':') - if TTD_stat==stat \ + if TTD_stat == stat \ and \ - (TTD_loc==loc or loc=="*") \ + (TTD_loc == loc or loc == "*") \ and \ - TTD_net==net : - self.UpdateTimeDict[key]={} + TTD_net == net: + self.UpdateTimeDict[key] = {} for var in self.ShiftVars: - self.UpdateTimeDict[key][var[0]]=var[1].get() + self.UpdateTimeDict[key][var[0]] = var[1].get() # empty all entries -# self.ClearAll(self.StatChanListVars) + # self.ClearAll(self.StatChanListVars) info = "Time Set Done. Use 'Apply Time Corrections' to apply." self.addTextInfoBar(info, 'green') return 1 @@ -1879,40 +1946,41 @@ class MainWindow: """ builds drop downs for TimeShift notebook """ - #build list for stat:loc:net selection dropdown + # build list for stat:loc:net selection dropdown self.StatLocNetList = sorted(list(self.TraceTimeDict.keys())) if not self.StatLocNetList: self.addTextInfoBar("No Data Found", 'orange') - #build drop down and new entries + # build drop down and new entries Label(fm, text="For Traces Matching:").grid(row=0, column=1, sticky=W) Label(fm, text="Time Shift:").grid(row=0, column=3, sticky=W) Label(fm, text="Applied").grid(row=0, column=4, sticky=W) - n=1 + n = 1 Label(fm, text="Stat:Loc:Net").grid(row=1, sticky=W) Pmw.ComboBox(fm, history=0, - entry_width=self.e_width-5, + entry_width=self.e_width - 5, entry_textvariable=self.TimeShiftName, scrolledlist_items=(self.StatLocNetList), selectioncommand=Command(self.LoadTimeSelect) ).grid(row=n, column=1, sticky=W) self.WildButton = Checkbutton(fm, - text ="Wildcard Location Code", - command = Command(self.WildCardLoc), - variable = self.WildLoc + text="Wildcard Location Code", + command=Command(self.WildCardLoc), + variable=self.WildLoc ) - self.WildButton.grid(row=n+1, column=1, sticky=W) + self.WildButton.grid(row=n + 1, column=1, sticky=W) n = 1 for var in self.ShiftVars: - if var[0] == "Corr_Type": continue + if var[0] == "Corr_Type": + continue if var[0] != "Time_Tag_Quest": Label(fm, text=var[0]).grid(row=n, column=2, sticky=E) Entry(fm, - width = self.e_width-5, - selectbackground = 'yellow', - textvariable = var[1]).grid(row=n, column=3, sticky=W) + width=self.e_width - 5, + selectbackground='yellow', + textvariable=var[1]).grid(row=n, column=3, sticky=W) n += 1 elif var[0] == "Time_Tag_Quest": @@ -1925,20 +1993,22 @@ class MainWindow: scrolledlist_items=("set", "unset"), ).grid(row=n, column=3, sticky=W) - #build boxes indicating if update is applied + # build boxes indicating if update is applied n = 3 for var in self.SetTimeVars: Checkbutton(fm, - variable = var[1], - indicatoron = "FALSE", - text = " ", - selectcolor = "green", - state = "disabled" + variable=var[1], + indicatoron="FALSE", + text=" ", + selectcolor="green", + state="disabled" ).grid(row=n, column=4) n += 1 -# clear variables etc. + # clear variables etc. self.ResetTimeShift() + ####################################### + def WildCardLoc(self): """ sub loc code with * @@ -1947,7 +2017,7 @@ class MainWindow: if self.TimeShiftName.get(): self.OldShiftName.set(self.TimeShiftName.get()) newname = self.TimeShiftName.get().split(":") - newname[1]="*" + newname[1] = "*" self.TimeShiftName.set(":".join(newname)) else: return @@ -1956,14 +2026,16 @@ class MainWindow: self.TimeShiftName.set(self.OldShiftName.get()) else: return + ####################################### - def LaunchApplyTimeCor(self, undo=0) : + + def LaunchApplyTimeCor(self, undo=0): """ separated out so ApplyTimeCor could be run as a thread """ - #if headers have already been alterred warn user + # if headers have already been alterred warn user if not undo: if self.SetTimeDict or self.SetHdrDict: self.WarnWidget(self.TimeShift_nb, "time") @@ -1971,30 +2043,31 @@ class MainWindow: if self.CancelWarn.get(): return - #if the user ignores warning proceed - #set var indicating ApplyTimeCor is running. Watched to exit thread if - #cancel button selected in CancelTL + # if the user ignores warning proceed + # set var indicating ApplyTimeCor is running. Watched to exit thread if + # cancel button selected in CancelTL self.RunApplyTimeCor.set(1) - #write log and user information + # write log and user information self.WriteLog("\n<Modify Time>", "Time", "blue") - #tRun=threading.Thread(target=self.ApplyTimeCor) + # tRun=threading.Thread(target=self.ApplyTimeCor) self.ApplyTimeCor() - #tRun.start() + # tRun.start() # stay here until thread dies - #tRun.join() + # tRun.join() - #nuke top level CancelTL + # nuke top level CancelTL if self.RunApplyTimeCor.get(): self.KillCancelTL(self.RunApplyTimeCor) - #some cleanup + # some cleanup self.WriteLog("<end>", "Time", "blue") self.ResetTimeShift() self.IgnoreWarn.set(0) self.UseNewOnlyTime.set(0) ####################################### + def NewOnlyTime(self): """ Set flag to only use new (unapplied) timing corrections @@ -2003,7 +2076,9 @@ class MainWindow: self.ActiveText.set("") self.AlteredText.set("") self.UseNewOnlyTime.set(1) + ####################################### + def ApplyTimeCor(self): """ apply timing correction to start time etc. @@ -2012,7 +2087,7 @@ class MainWindow: # Launch CancelTL allowing user to cancel process if not BATCHMODE: self.CancelTL(self.RunApplyTimeCor, "Apply Time Correction") - #update with lingering window entries + # update with lingering window entries if not self.TimeDictSet(): return @@ -2024,9 +2099,9 @@ class MainWindow: for key in UpdateTimeDictKeys: if key not in self.TraceTimeDict: continue - #capture cancel + # capture cancel if not self.RunApplyTimeCor.get(): - infotext="Canceled Applied Corrections to: " + str(num_cnt)\ + infotext = "Canceled Applied Corrections to: " + str(num_cnt)\ + " files." self.addTextInfoBar(infotext, 'orange') logtext = "\t" + infotext @@ -2058,36 +2133,36 @@ class MainWindow: self.addTextInfoBar("Invalid EndTime String", 'red') return - #write log and user information -# self.WriteLog("\n<Modify Time>\n", "Time", "blue") - logtext= "\n\tKey Name: " + key + # write log and user information + # self.WriteLog("\n<Modify Time>\n", "Time", "blue") + logtext = "\n\tKey Name: " + key self.WriteLog(logtext, "Time", "black") - cnt=len(self.TraceTimeDict[key]) - 1 #first record - logtext="\tNumber of Traces Selected: " + str(cnt) + cnt = len(self.TraceTimeDict[key]) - 1 # first record + logtext = "\tNumber of Traces Selected: " + str(cnt) self.WriteLog(logtext, "Time", "black") if key in self.TimeCorrectedFiles: - changedfiles=len(self.TimeCorrectedFiles[key]) + changedfiles = len(self.TimeCorrectedFiles[key]) if self.UseNewOnlyTime.get(): - logtext="\tSkipping " + str(changedfiles) + \ + logtext = "\tSkipping " + str(changedfiles) + \ " previously corrected files." self.WriteLog(logtext, "Time", "black") else: - logtext="\tApplying Corrections to " + str(changedfiles)\ + logtext = "\tApplying Corrections to " + str(changedfiles)\ + " previously corrected files." self.WriteLog(logtext, "Time", "red") - logtext="\tStart_Time of Correction: " + \ + logtext = "\tStart_Time of Correction: " + \ str(self.TSStartTime.get()) self.WriteLog(logtext, "Time", "black") - logtext="\tEnd_Time of Correction: " + \ + logtext = "\tEnd_Time of Correction: " + \ str(self.TSEndTime.get()) self.WriteLog(logtext, "Time", "black") - logtext= "\tTime_Shift_sec " + str(self.TSShift.get()) + logtext = "\tTime_Shift_sec " + str(self.TSShift.get()) self.WriteLog(logtext, "Time", "black") if self.TypeTimeCor.get(): - type="Replace existing time correction" + type = "Replace existing time correction" else: - type="Add to existing time correction" - logtext="\tType of Correction: " + type + type = "Add to existing time correction" + logtext = "\tType of Correction: " + type self.WriteLog(logtext, "Time", "black") if self.TimeTagQuest.get(): @@ -2098,21 +2173,21 @@ class MainWindow: logtext = "\t\"Time tag is questionable\" flag unset" self.WriteLog(logtext, "Time", "black") - #set up dictionary to monitor corrected files + # set up dictionary to monitor corrected files if key not in self.TimeCorrectedFiles: - self.TimeCorrectedFiles[key]=[] - #apply corrections for selected keys - textstr= "Correcting File Number: " + self.TimeCorrectedFiles[key] = [] + # apply corrections for selected keys + textstr = "Correcting File Number: " for timetup in self.TraceTimeDict[key][1:]: if self.UseNewOnlyTime.get(): if timetup[0] in self.TimeCorrectedFiles[key]: - skip_cnt+=1 - infotext="Skipping File " + str(skip_cnt) + skip_cnt += 1 + infotext = "Skipping File " + str(skip_cnt) self.addTextInfoBar(infotext) continue - #respond to cancel requests + # respond to cancel requests if not self.RunApplyTimeCor.get(): - infotext="Canceled Applied Corrections to: " + \ + infotext = "Canceled Applied Corrections to: " + \ str(num_cnt) + " files." self.addTextInfoBar(infotext, 'orange') logtext = "\t" + infotext @@ -2121,27 +2196,28 @@ class MainWindow: if (startEpoch <= timetup[1] and timetup[1] <= endEpoch) or \ (startEpoch <= timetup[2] and timetup[2] <= endEpoch) or \ (timetup[1] <= startEpoch and endEpoch <= timetup[2]): - #info for user + # info for user if not self.TimeSet(timetup[0], startEpoch, endEpoch): - err_cnt+=1 + err_cnt += 1 # if this fails, make sure UpdateTimeDict is cleared # for key del self.UpdateTimeDict[key] break else: self.TimeCorrectedFiles[key].append(timetup[0]) - num_cnt+=1 + num_cnt += 1 if key not in self.SetTimeDict: - self.SetTimeDict[key]={} + self.SetTimeDict[key] = {} if mod(num_cnt, 10): pass else: self.wait(textstr, num_cnt) - #keep track of time corrections applied + # keep track of time corrections applied if key in self.UpdateTimeDict: for subkey in self.UpdateTimeDict[key]: - #add to existing if TypeTimeCor is set to 'Add To' i.e. == 0 + # add to existing if TypeTimeCor is set to 'Add To' i.e. + # == 0 if subkey == "Time_Shift_sec" \ and not self.TypeTimeCor.get(): # add to previous if the user ignored warning to Apply @@ -2163,12 +2239,11 @@ class MainWindow: self.UpdateTimeDict[key][subkey] if err_cnt: - logtext="\tTime corection failed for " + str(err_cnt) + " files" + logtext = "\tTime corection failed for " + str(err_cnt) + " files" self.WriteLog(logtext, "Time", "red") - if self.RunApplyTimeCor.get(): - infotext="Done. Applied Corrections to: " + str(num_cnt) + \ + infotext = "Done. Applied Corrections to: " + str(num_cnt) + \ " files." self.addTextInfoBar(infotext, 'green') if not BATCHMODE: @@ -2176,9 +2251,10 @@ class MainWindow: logtext = "\t" + infotext self.WriteLog(logtext, "Time", "green") self.ActiveText.set("") -# self.WriteLog("<end>\n", "Time", "blue") + # self.WriteLog("<end>\n", "Time", "blue") ####################################### + def LaunchUndoTimeCor(self): """ Launch UndoTimeCor in thread @@ -2188,7 +2264,7 @@ class MainWindow: self.addTextInfoBar(infotext, 'orange') return - #if headers have already been alterred warn user + # if headers have already been alterred warn user self.WarnWidget(self.TimeShift_nb, "undo") self.WarnWidget_tl.wait_window() if not self.IgnoreWarn.get(): @@ -2199,13 +2275,13 @@ class MainWindow: self.ResetTimeShift() self.UpdateTimeDict = {} for key in self.SetTimeDict: - #Populate UpdateTimeDict with previously applied Time Corrections + # Populate UpdateTimeDict with previously applied Time Corrections if key not in self.UpdateTimeDict: self.UpdateTimeDict[key] = {} for subkey in self.SetTimeDict[key]: if subkey == "Time_Shift_sec": self.UpdateTimeDict[key][subkey] = \ - (-1.0)*self.SetTimeDict[key][subkey] + (-1.0) * self.SetTimeDict[key][subkey] elif subkey == "Time_Tag_Quest": if self.SetTimeDict[key][subkey] == "set": self.UpdateTimeDict[key][subkey] = "unset" @@ -2219,17 +2295,18 @@ class MainWindow: self.UpdateTimeDict[key][subkey] = \ self.SetTimeDict[key][subkey] - # self.SetTimeDict={} + # self.SetTimeDict={} self.LaunchApplyTimeCor(1) return ####################################### + def BuildEpoch(self, input_time): """ build epoch time from input time string """ - EpochTime=None - err="" + EpochTime = None + err = "" intTime = str(input_time.get()) try: @@ -2244,7 +2321,8 @@ class MainWindow: return EpochTime, err ####################################### - def TimeSet(self, ifile,startEpoch, endEpoch): + + def TimeSet(self, ifile, startEpoch, endEpoch): """ apply time correction to given mseed file """ @@ -2256,7 +2334,7 @@ class MainWindow: self.WriteLog(ShiftErr, "Time", "red") return 0 - #open mseed files for correction + # open mseed files for correction msfile = Mseed(ifile) filesize = msfile.filesize blksize = msfile.blksize @@ -2267,11 +2345,11 @@ class MainWindow: n = 0 while n < numblocks: - hdrs = msfile.fixedhdr(n*blksize) + hdrs = msfile.fixedhdr(n * blksize) # more test just incase, this will fail if headers have been # change w/o updating the db - (SeqNum, DHQual, res, Stat, Loc, Chan, Net)=hdrs[0] + (SeqNum, DHQual, res, Stat, Loc, Chan, Net) = hdrs[0] Stat = Stat.strip() if self.WildLoc.get(): Loc = "*" @@ -2287,7 +2365,7 @@ class MainWindow: # determine time of blockette and process if between startEpoch # & endEpoch (Year, Day, Hour, Min, Sec, junk, Micro) = hdrs[1] - timestr = ":".join(map(str,(Year, Day, Hour, Min, Sec))) + timestr = ":".join(map(str, (Year, Day, Hour, Min, Sec))) time_str = time.strptime(timestr, '%Y:%j:%H:%M:%S') blkEpoch = time.mktime(time_str) + (Micro * 0.0001) if startEpoch <= blkEpoch and blkEpoch <= endEpoch: @@ -2327,52 +2405,50 @@ class MainWindow: newshift = self.TSShift.get() blkEpoch = blkEpoch + self.TSShift.get() - - hdrs[3][4] = int(newshift/0.0001) + hdrs[3][4] = int(newshift / 0.0001) EpochInt = int(blkEpoch) - EpochDec = (blkEpoch-EpochInt) - newMicro = round(EpochDec/0.0001) + EpochDec = (blkEpoch - EpochInt) + newMicro = round(EpochDec / 0.0001) - #build new start time entry + # build new start time entry (year, month, day, hour, min, sec, wkday, jday, dst) = \ time.gmtime(EpochInt) - #set/unset Activity flag to indicate time shift + # set/unset Activity flag to indicate time shift if newshift: hdrs[3][0] = self.SetFlag(hdrs[3][0], 1) else: hdrs[3][0] = self.SetFlag(hdrs[3][0], 1, "unset") - #set/unset Data Quality flag to indicate "Time tag questionable" + # set/unset Data Quality flag to indicate "Time tag questionable" if self.TimeTagQuest.get(): action = self.TimeTagQuest.get() hdrs[3][2] = self.SetFlag(hdrs[3][2], 7, action) - newhdrs = (hdrs[0], (year, jday, hour, min, sec, junk, newMicro), hdrs[2], hdrs[3]) - bytes_written = msfile.WriteFixedHdr(newhdrs, n*blksize) + bytes_written = msfile.WriteFixedHdr(newhdrs, n * blksize) # This block of code should be activated. What needs to happen # is that for every blockette that has a BTime entry, that entry # should be shifted based on the above logic. - #numblk=hdrs[3][3] - #addseek=hdrs[3][6] - #b=0 - #loop over number of blockettes following fixed header at block n - # I should be searching for blk 500 here. - #while b < numblk: - #seekval=(n*blksize)+addseek - #(blktype, next)=msfile.typenxt(seekval) - #print blktype, next - #getBlkCmd="blklist=msfile.blk" + str(blktype) + "(" + - # str(seekval) + ")" - #exec getBlkCmd - #addseek=next - #b+=1 + # numblk=hdrs[3][3] + # addseek=hdrs[3][6] + # b=0 + # loop over number of blockettes following fixed header at block n + # I should be searching for blk 500 here. + # while b < numblk: + # seekval=(n*blksize)+addseek + # (blktype, next)=msfile.typenxt(seekval) + # print blktype, next + # getBlkCmd="blklist=msfile.blk" + str(blktype) + "(" + + # str(seekval) + ")" + # exec getBlkCmd + # addseek=next + # b+=1 n += 1 - #get endianess before closing + # get endianess before closing msfile.close() # some user info @@ -2382,12 +2458,14 @@ class MainWindow: self.WriteLog(err, "Time", "red") err = "\tNO CORRECTION APPLIED TO THESE BLOCKETTES" self.WriteLog(err, "Time", "red") - if blk_err == numblocks: return 0 - # clear variables etc. + if blk_err == numblocks: + return 0 + # clear variables etc. return 1 ####################################### + def TestTimeShift(self): """ Test if time correction exceeds field @@ -2396,58 +2474,59 @@ class MainWindow: then determines if the resultant correction will exceed the field. I believe that this is un-necessary and definitely adds time. """ - # if replacing existing correction we just need to test if entered time exceeds - # field size + # if replacing existing correction we just need to test if entered time + # exceeds field size # convert sec to 0.0001 sec -# if self.TypeTimeCor.get(): - NewShiftmSec = (self.TSShift.get())/0.0001 - if -2**31 >= NewShiftmSec or NewShiftmSec >= (2**31)-1 : + # if self.TypeTimeCor.get(): + NewShiftmSec = (self.TSShift.get()) / 0.0001 + if -2**31 >= NewShiftmSec or NewShiftmSec >= (2**31) - 1: err = "Time Correction exceeds limits of field [-2**31 <= "\ "TimeCorr <= (2**31)-1]" return err - # if adding to existing we need to test all corrections for a given file to see if the - # resultant correction exceeds field size - #else: - ## open mseed file - #try: - #msfile=Mseed(ifile) - #(filesize,blksize)=msfile.sizes() - ##initialize variables, lists, and dicts for later - #filesize=msfile.filesize - #blksize=msfile.blksize - #(numblocks, odd_size)=divmod(filesize, blksize) - #except Exception as e: - #err= "Corrupt mseed: " + ifile - #msfile.close() - #return err - ## loop through file, snarf time corrections and test for size - #blk_err=0 - #n=0 - #while n < numblocks: - #hdrs=msfile.fixedhdr(n*blksize) - #oldshift= hdrs[3][4] * 0.0001 - ## if an old shift exists and is applied - #if oldshift: - #newshift = self.TSShift.get() + oldshift - #else: - #newshift = self.TSShift.get() - - #NewShiftmSec = newshift/0.0001 - #if -2**31 >= NewShiftmSec or NewShiftmSec >= - # (2**31)-1 : - #err= "Time Correction exceeds limits of - # field [-2**31 <= TimeCorr <= (2**31)-1]" - #return err - #n+=1 - #msfile.close() + # if adding to existing we need to test all corrections for a given + # file to see if the resultant correction exceeds field size + # else: + # open mseed file + # try: + # msfile=Mseed(ifile) + # (filesize,blksize)=msfile.sizes() + # initialize variables, lists, and dicts for later + # filesize=msfile.filesize + # blksize=msfile.blksize + # (numblocks, odd_size)=divmod(filesize, blksize) + # except Exception as e: + # err= "Corrupt mseed: " + ifile + # msfile.close() + # return err + # loop through file, snarf time corrections and test for size + # blk_err=0 + # n=0 + # while n < numblocks: + # hdrs=msfile.fixedhdr(n*blksize) + # oldshift= hdrs[3][4] * 0.0001 + # if an old shift exists and is applied + # if oldshift: + # newshift = self.TSShift.get() + oldshift + # else: + # newshift = self.TSShift.get() + + # NewShiftmSec = newshift/0.0001 + # if -2**31 >= NewShiftmSec or NewShiftmSec >= + # (2**31)-1 : + # err= "Time Correction exceeds limits of + # field [-2**31 <= TimeCorr <= (2**31)-1]" + # return err + # n+=1 + # msfile.close() return 0 ####################################### - def LoadTimeSelect(self,timeid): + + def LoadTimeSelect(self, timeid): """ loads info for selected stat:loc:net key """ - key=timeid + key = timeid self.ClearAll(self.ShiftVars) self.TypeTimeCor.set(0) self.TimeTagQuest.set("") @@ -2456,12 +2535,11 @@ class MainWindow: self.TSStartTime.set("") self.TSEndTime.set("") - # modify self.TimeShiftName if user wants wildcard if self.WildLoc.get(): self.WildCardLoc() - #load info if Dictionary already has entry for selection + # load info if Dictionary already has entry for selection if key in self.UpdateTimeDict: for var in self.ShiftVars: if var[0] in self.UpdateTimeDict[key]: @@ -2490,6 +2568,7 @@ class MainWindow: pass ####################################### + def RecalcStartEnd(self): """ recalculates start and endtimes for traces for a given @@ -2498,27 +2577,29 @@ class MainWindow: timeid = self.TimeShiftName.get() - #clear entry if time is already calculated and Traces loaded + # clear entry if time is already calculated and Traces loaded if timeid in self.TraceTimeDict: del self.TraceTimeDict[timeid] self.GetStartEnd() + ####################################### + def GetStartEnd(self): """ Gets start and endtimes for traces for a given stat:loc:net key """ -# self.WildButton.configure(state="disabled") + # self.WildButton.configure(state="disabled") timeid = self.TimeShiftName.get() if not timeid: self.addTextInfoBar("No Sta:Loc:Net selected", 'orange') - return + return # don't spend time here if time is already calculated # and Traces loaded if timeid in self.TraceTimeDict: try: if self.TraceTimeDict[timeid][0]: - #see if begin and end times exist + # see if begin and end times exist self.FillTime(timeid) return except Exception as e: @@ -2527,13 +2608,13 @@ class MainWindow: textstr = "Examining traces for key: " + timeid self.addTextInfoBar(textstr, 'lightblue') - (keystat,keyloc,keynet) = timeid.split(":") - cnt=0 + (keystat, keyloc, keynet) = timeid.split(":") + cnt = 0 for key in self.TraceDict: (stat, chan, loc, net, sps) = key.split(":") if keystat == stat and keynet == net and \ (keyloc == loc or keyloc == "*"): - for infile in self.TraceDict[key] : + for infile in self.TraceDict[key]: cnt += 1 if mod(cnt, 10): pass @@ -2551,21 +2632,21 @@ class MainWindow: # self.TraceTimeDict[timeid]: self.TraceTimeDict[timeid] = [] self.TraceTimeDict[timeid].append( - [begintime,endtime]) + [begintime, endtime]) self.TraceTimeDict[timeid].append( - [infile,begintime,endtime]) + [infile, begintime, endtime]) else: - if not [infile,begintime,endtime] \ + if not [infile, begintime, endtime] \ in self.TraceTimeDict[timeid]: - if begintime < self.TraceTimeDict[timeid][0][0]: + if begintime < self.TraceTimeDict[timeid][0][0]: # noqa: E501 self.TraceTimeDict[timeid][0][0] = \ begintime if endtime > self.TraceTimeDict[timeid][0][1]: self.TraceTimeDict[timeid][0][1] = endtime self.TraceTimeDict[timeid].append( - [infile,begintime,endtime]) + [infile, begintime, endtime]) except Exception as e: - logtext= "Corrupt mseed file: " + infile + logtext = "Corrupt mseed file: " + infile self.WriteLog(logtext, 'Time', 'red') msfile.close() else: @@ -2579,57 +2660,61 @@ class MainWindow: self.addTextInfoBar(err, 'red') ################################################################## + def FillTime(self, keyname): """ fills time and count for Time Shift nb """ - startepoch=self.TraceTimeDict[keyname][0][0] + startepoch = self.TraceTimeDict[keyname][0][0] # decided not to used micro sec accuracy since round off errors # are creating problems - #micro= int((startepoch - int(startepoch)) / 0.0001) - #micro=str(micro) - #numz=4-len(micro) - #micro=numz*"0" + micro + # micro= int((startepoch - int(startepoch)) / 0.0001) + # micro=str(micro) + # numz=4-len(micro) + # micro=numz*"0" + micro start = time.strftime('%Y:%j:%H:%M:%S', time.gmtime(startepoch)) - #start=start + "." + str(micro) + # start=start + "." + str(micro) self.TSStartTime.set(start) - endepoch=self.TraceTimeDict[keyname][0][1] + endepoch = self.TraceTimeDict[keyname][0][1] # to make sure we pickup the last block - endepoch+=1 + endepoch += 1 # decided not to used micro sec accuracy since round off errors # are creating problems - #micro= int((endepoch - int(endepoch)) / 0.0001) - #micro=str(micro) - #numz=4-len(micro) - #micro=numz*"0" + micro + # micro= int((endepoch - int(endepoch)) / 0.0001) + # micro=str(micro) + # numz=4-len(micro) + # micro=numz*"0" + micro end = time.strftime('%Y:%j:%H:%M:%S', time.gmtime(endepoch)) # end=end + "." + str(micro) self.TSEndTime.set(end) # first record has min/max time for keyname - cnt = len(self.TraceTimeDict[keyname]) - 1 + cnt = len(self.TraceTimeDict[keyname]) - 1 textstr = str(cnt) + " traces selected for key: " + keyname self.addTextInfoBar(textstr, 'lightblue') ################################################################## + def MkNumChar(self, instr, num): """ appends num-len(instr) 0 to input string or truncates string to num chars """ if len(instr) < num: - m= num - len(instr) - return instr + m*"0" + m = num - len(instr) + return instr + m * "0" elif len(instr) > num: return instr[0:num] else: return instr + ######################################################### + def WriteLog(self, info, type="", color="black"): """ writes text to log notebook """ - #local variables + # local variables LogAllappend = self.LogAll.append LogHeaderappend = self.LogHeader.append LogTimeappend = self.LogTime.append @@ -2639,7 +2724,7 @@ class MainWindow: if info: print(info) else: - info=info + "\n" + info = info + "\n" LogAllappend((info, color)) if type == "Header": @@ -2652,12 +2737,14 @@ class MainWindow: pass self.DisplayLog() + ################################################################## + def DisplayLog(self): """ filters log entries """ - #local variables + # local variables LogVarget = self.LogVar.get LogTextinsert = self.LogText.insert @@ -2672,11 +2759,13 @@ class MainWindow: textlist = self.LogEndian elif LogVarget() == 4: textlist = self.LogSummary - else: return + else: + return for (textcmd, color) in textlist: LogTextinsert('end', textcmd, color) ################################################################## + def FlushLogs(self): """ flushes logs @@ -2689,7 +2778,8 @@ class MainWindow: self.LogText.clear() ####################################### - def LaunchChangeEndian(self, endian) : + + def LaunchChangeEndian(self, endian): """ separated out so ChangeEndian could be run as a thread """ @@ -2699,18 +2789,19 @@ class MainWindow: self.ToEndian.set("big") else: self.ToEndian.set("little") - #launch thread - #eRun=threading.Thread(target=self.ChangeEndian) + # launch thread + # eRun=threading.Thread(target=self.ChangeEndian) self.ChangeEndian() - #eRun.start() + # eRun.start() # stay here until thread dies - #eRun.join() + # eRun.join() if self.RunChangeEndian.get(): self.KillCancelTL(self.RunChangeEndian) self.ActiveText.set("") ################################################################## + def ChangeEndian(self): """ rewrites all blockettes in either big or little endian @@ -2720,52 +2811,51 @@ class MainWindow: self.CancelTL(self.RunChangeEndian, "Change Endianess") self.ActiveText.set("Changing Endianess") - endian=self.ToEndian.get() + endian = self.ToEndian.get() if endian == "big": - inlist=self.LittleEndianList - outlist=self.BigEndianList - numfiles=len(self.LittleEndianList) + inlist = self.LittleEndianList + outlist = self.BigEndianList + numfiles = len(self.LittleEndianList) if not numfiles: - err="No Little Endian Files Found" + err = "No Little Endian Files Found" self.addTextInfoBar(err, "red") return else: - inlist=self.BigEndianList - outlist=self.LittleEndianList - numfiles=len(self.BigEndianList) + inlist = self.BigEndianList + outlist = self.LittleEndianList + numfiles = len(self.BigEndianList) if not numfiles: - err="No Big Endian Files Found" + err = "No Big Endian Files Found" self.addTextInfoBar(err, "red") return - files_left=numfiles - textstr="Files Remaining: " + files_left = numfiles + textstr = "Files Remaining: " self.wait(textstr, files_left) - - #write log and user information + # write log and user information self.WriteLog("\n<Change Endianess>", "Endian", "blue") - logtext= "\tSelected " + str(numfiles) + " traces to convert to " + \ + logtext = "\tSelected " + str(numfiles) + " traces to convert to " + \ endian + " endian headers" self.WriteLog(logtext, "Endian", "black") # loop over files reading & writing blockettes - corr_files=0 + corr_files = 0 while inlist: - ErrFlag=0 - #respond to cancel requests + ErrFlag = 0 + # respond to cancel requests if not self.RunChangeEndian.get(): break - ifile=inlist.pop() + ifile = inlist.pop() # info for user if mod(files_left, 5): pass else: self.wait(textstr, files_left) - files_left-=1 + files_left -= 1 - msfile=Mseed(ifile) - #local variables' + msfile = Mseed(ifile) + # local variables' fixedhdr = msfile.fixedhdr WriteFixedHdr = msfile.WriteFixedHdr typenxt = msfile.typenxt @@ -2777,39 +2867,39 @@ class MainWindow: (numblocks, odd_size) = divmod(filesize, blksize) outlist.append(ifile) - blk_err=0 - n=0 + blk_err = 0 + n = 0 while n < numblocks: - #read & rewrite fixed header - hdrs = fixedhdr(n*blksize) - bytes_written = WriteFixedHdr(hdrs, n*blksize, endian) + # read & rewrite fixed header + hdrs = fixedhdr(n * blksize) + bytes_written = WriteFixedHdr(hdrs, n * blksize, endian) numblk = hdrs[3][3] addseek = hdrs[3][6] b = 0 # loop over number of blockettes following fixed header at # block n while b < numblk: - seekval = (n*blksize)+addseek + seekval = (n * blksize) + addseek (blktype, next) = typenxt(seekval) blklist = GetBlk(blktype, seekval) if not blklist: # if blockette error encountered bail and undo endian # changes err = "\n\tCorrupt mseed: " + ifile - self.WriteLog(err,"Endian","red") + self.WriteLog(err, "Endian", "red") err = "\t\tFile removed from Trace db" - self.WriteLog(err,"Endian","red") + self.WriteLog(err, "Endian", "red") err = "\t\tRecord: " + str(n) - self.WriteLog(err,"Endian","red") + self.WriteLog(err, "Endian", "red") err = "\t\tUnrecognized Blockette: " + str(blktype) - self.WriteLog(err,"Endian","red") + self.WriteLog(err, "Endian", "red") msfile.close() self.UndoEndian(ifile, n, b, endian) - #remove file from list + # remove file from list outlist.pop() - #set error flag + # set error flag ErrFlag = 1 - #ensure outer while block will end + # ensure outer while block will end n += numblocks break else: @@ -2822,7 +2912,7 @@ class MainWindow: corr_files += 1 msfile.close() - #flush endian list to prevent redoing process + # flush endian list to prevent redoing process if endian == "big": self.LittleEndianList = inlist self.BigEndianList = outlist @@ -2833,7 +2923,7 @@ class MainWindow: self.NumBigFiles.set(len(self.BigEndianList)) self.NumLittleFiles.set(len(self.LittleEndianList)) - #write log and user information + # write log and user information logtext = "\n\tConverted " + str(corr_files) + " traces to " + \ endian + " endian headers" self.WriteLog(logtext, "Endian", 'black') @@ -2843,6 +2933,7 @@ class MainWindow: self.addTextInfoBar(infotext, 'green') ######################################################### + def UndoEndian(self, infile, recnum, blknum, endian): """ changes a corrupt mseed file back to original endianess @@ -2863,15 +2954,15 @@ class MainWindow: endian = "big" # loop upto position that gave a problem while n <= recnum: - #read & rewrite fixed header - hdrs = msfile.fixedhdr(n*blksize) - bytes_written = msfile.WriteFixedHdr(hdrs, n*blksize, endian) + # read & rewrite fixed header + hdrs = msfile.fixedhdr(n * blksize) + bytes_written = msfile.WriteFixedHdr(hdrs, n * blksize, endian) numblk = hdrs[3][3] addseek = hdrs[3][6] b = 0 - #correct upto the blockette that gave problems + # correct upto the blockette that gave problems while b < blknum: - seekval = (n*blksize)+addseek + seekval = (n * blksize) + addseek (blktype, next) = msfile.typenxt(seekval) blklist = msfile.GetBlk(blktype, seekval) bytes_written = msfile.PutBlk( @@ -2881,13 +2972,15 @@ class MainWindow: n += 1 msfile.close() return + ######################################################### + def SetFlag(self, instr, position, action="set"): """ sets/unsets flag in string representation of byte """ newstr = "" - b = len(instr)-1 + b = len(instr) - 1 for a in instr: if (b) == position: if action == "set": @@ -2897,7 +2990,9 @@ class MainWindow: newstr = newstr + a b -= 1 return newstr + ######################################################### + def ListTrace(self, master): """ provide a toplevel window listing traces for a given key @@ -2915,19 +3010,19 @@ class MainWindow: if self.tl_State == 1: self.TraceList_tl.tkraise() self.TraceListText.clear() - #display info on selected block + # display info on selected block else: self.TraceList_tl = Toplevel(master) -# self.TraceList_tl.title("Trace Listing") + # self.TraceList_tl.title("Trace Listing") self.ExitTraceList_b = Button(self.TraceList_tl, - activebackground = 'red', - cursor = 'pirate', - background = 'lightblue', + activebackground='red', + cursor='pirate', + background='lightblue', text="Dismiss", - command = Command(self.killWindow, - self.TraceList_tl) + command=Command(self.killWindow, + self.TraceList_tl) ) self.ExitTraceList_b.pack(side='bottom', fill='x', expand=1) @@ -2937,20 +3032,21 @@ class MainWindow: self.TraceListText.tag_config("odd", background="lightblue") - cnt=len(self.TraceDict[tracekey]) - wtitle= "Trace Listing: " + str(cnt) + " files listed" + cnt = len(self.TraceDict[tracekey]) + wtitle = "Trace Listing: " + str(cnt) + " files listed" self.TraceList_tl.title(wtitle) self.TraceDict[tracekey] = sorted(self.TraceDict[tracekey]) c = 0 for infile in self.TraceDict[tracekey]: - if c : + if c: self.TraceListText.insert("end", """%s\n""" % infile, "odd") c = 0 - else : + else: self.TraceListText.insert("end", """%s\n""" % infile) c += 1 ######################################################### + def ListTimeCor(self, master): """ provide a toplevel window listing time corrections in fixed headers @@ -2959,7 +3055,7 @@ class MainWindow: if not self.TimeShiftName.get(): self.addTextInfoBar("No Sta:Loc:Net selected", 'orange') return - tracekey=self.TimeShiftName.get() + tracekey = self.TimeShiftName.get() try: self.tl_State = self.TimeCorList_tl.winfo_exists() @@ -2969,18 +3065,18 @@ class MainWindow: if self.tl_State == 1: self.TimeCorList_tl.tkraise() self.TimeCorListText.clear() - #display info on selected block + # display info on selected block else: self.TimeCorList_tl = Toplevel(master) self.TimeCorList_tl.title("Time Corrections") self.ExitTimeCorList_b = Button(self.TimeCorList_tl, - activebackground = 'red', - cursor = 'pirate', - background = 'lightblue', + activebackground='red', + cursor='pirate', + background='lightblue', text="Dismiss", - command = Command( + command=Command( self.killWindow, self.TimeCorList_tl) ) @@ -2994,80 +3090,83 @@ class MainWindow: self.TimeCorListText.tag_config("yellow", background="yellow") self.TimeCorListText.tag_config("orange", background="orange") - TimeDict=self.GetTimeCor() + TimeDict = self.GetTimeCor() self.TimeCorListText.clear() - c=0 - addtext="\t******************************************" + c = 0 + addtext = "\t******************************************" self.TimeCorListText.insert("end", """%s\n""" % addtext, "yellow") - addtext="\t* Time Corrections Found in File Headers *" + addtext = "\t* Time Corrections Found in File Headers *" self.TimeCorListText.insert("end", """%s\n""" % addtext, "yellow") - addtext="\t******************************************" + addtext = "\t******************************************" self.TimeCorListText.insert("end", """%s\n""" % addtext, "yellow") tracelist = sorted(list(TimeDict.keys())) for key in tracelist: - if c : + if c: self.TimeCorListText.insert("end", """%s\n""" % key, "odd") - addtext = 4*SPACE + "Block Start Time" + 6*SPACE + "Cor(s)" \ - + 8*SPACE + "Status" + 14*SPACE + "Timing Questionable" + addtext = (4 * SPACE + "Block Start Time" + 6 * SPACE + + "Cor(s)" + 8 * SPACE + "Status" + 14 * SPACE + + "Timing Questionable") self.TimeCorListText.insert( "end", """%s\n""" % addtext, "odd") for tup in TimeDict[key]: - addtext = 4*SPACE + str(tup[0]) + addtext = 4 * SPACE + str(tup[0]) splen = 26 - len(addtext) - addtext = addtext + splen*SPACE + str(tup[1]) + addtext = addtext + splen * SPACE + str(tup[1]) splen = 40 - len(addtext) - addtext = addtext + splen*SPACE + str(tup[2]) + addtext = addtext + splen * SPACE + str(tup[2]) splen = 60 - len(addtext) - addtext = addtext + splen*SPACE + str(tup[3]) + addtext = addtext + splen * SPACE + str(tup[3]) self.TimeCorListText.insert( "end", """%s\n""" % addtext, "odd") c = 0 - else : + else: self.TimeCorListText.insert("end", """%s\n""" % key) - addtext = 4*SPACE + "Block Start Time" + 6*SPACE + "Cor(s)" \ - + 8*SPACE + "Status" + 14*SPACE + "Timing Questionable" + addtext = (4 * SPACE + "Block Start Time" + 6 * SPACE + + "Cor(s)" + 8 * SPACE + "Status" + 14 * SPACE + + "Timing Questionable") self.TimeCorListText.insert("end", """%s\n""" % addtext) for tup in TimeDict[key]: - addtext = 4*SPACE + str(tup[0]) + addtext = 4 * SPACE + str(tup[0]) splen = 26 - len(addtext) - addtext=addtext + splen*SPACE + str(tup[1]) + addtext = addtext + splen * SPACE + str(tup[1]) splen = 40 - len(addtext) - addtext=addtext + splen*SPACE + str(tup[2]) + addtext = addtext + splen * SPACE + str(tup[2]) splen = 60 - len(addtext) - addtext=addtext + splen*SPACE + str(tup[3]) + addtext = addtext + splen * SPACE + str(tup[3]) self.TimeCorListText.insert("end", """%s\n""" % addtext) c += 1 ######################################################### + def GetTimeCor(self): """ Get time corrections from trace headers """ - #local variables + # local variables FileCorDict = {} timeid = self.TimeShiftName.get() - (keystat,keyloc,keynet) = timeid.split(":") + (keystat, keyloc, keynet) = timeid.split(":") cnt = 0 for key in self.TraceDict: - (stat,chan,loc,net,sps) = key.split(":") + (stat, chan, loc, net, sps) = key.split(":") if keystat == stat and keynet == net and \ (keyloc == loc or keyloc == "*"): for infile in self.TraceDict[key]: if mod(cnt, 10): pass else: - #self.TimeCorListText.insert( + # self.TimeCorListText.insert( # "end", """%s\n""" % timeid) - textstr="Key: " + timeid + " Examining Trace: " + textstr = "Key: " + timeid + " Examining Trace: " self.wait(textstr, cnt) - cnt+=1 + cnt += 1 # at this point all files in TraceDict should be mseed # files, so not testing here msfile = Mseed(infile) - fixedhdr = msfile.fixedhdr #local var + fixedhdr = msfile.fixedhdr # local var filesize = msfile.filesize blksize = msfile.blksize @@ -3075,13 +3174,13 @@ class MainWindow: n = 0 while n < numblocks: - hdrs = msfile.fixedhdr(n*blksize) + hdrs = msfile.fixedhdr(n * blksize) (Year, Day, Hour, Min, Sec, junk, Micro) = hdrs[1] - Day = self.AddZero(Day,3) - Hour = self.AddZero(Hour,2) - Min = self.AddZero(Min,2) - Sec = self.AddZero(Sec,2) - hdtime = ":".join(map(str,( + Day = self.AddZero(Day, 3) + Hour = self.AddZero(Hour, 2) + Min = self.AddZero(Min, 2) + Sec = self.AddZero(Sec, 2) + hdtime = ":".join(map(str, ( Year, Day, Hour, Min, Sec))) (act, io, DQual, numblk, timcorr, bdata, bblock) = \ @@ -3090,29 +3189,30 @@ class MainWindow: if int(act[6]): corr = "applied" else: - corr="not applied" + corr = "not applied" # is timing questionable flag set if hdrs[3][2][0] == "1": timequest = "set" else: timequest = "unset" - timcorr=float(timcorr)/10000. + timcorr = float(timcorr) / 10000. try: FileCorDict[infile].append(( hdtime, timcorr, corr, timequest)) except KeyError: - FileCorDict[infile]=[] + FileCorDict[infile] = [] FileCorDict[infile].append(( hdtime, timcorr, corr, timequest)) - n+=1 + n += 1 msfile.close() else: continue return FileCorDict ######################################################### + def AddZero(self, var, num): """ pad header values to specified length with blank space @@ -3123,19 +3223,20 @@ class MainWindow: if varlength == num: return var elif varlength < num: - pad = num-varlength - newvar = "0"*pad + var + pad = num - varlength + newvar = "0" * pad + var return newvar ######################################################### + def DumpUpdateDicts(self, type=""): """ dump UpdateHdrDict to Log notebook """ - #make sure any current window edits get added + # make sure any current window edits get added if self.StationName.get(): self.UpdateHdr(self.StationName.get()) -# self.TimeDictSet() + # self.TimeDictSet() if not self.UpdateHdrDict and not self.UpdateTimeDict: err = "No updates to dump." @@ -3149,61 +3250,62 @@ class MainWindow: applied = "saved" not_applied = "saved" - #set color of entry based on whether applied or not + # set color of entry based on whether applied or not if self.UpdateHdrDict: if type == "dump": - self.WriteLog("\n<Dump Update Dictionary>","Header","blue") + self.WriteLog("\n<Dump Update Dictionary>", "Header", "blue") inlist = sorted(list(self.UpdateHdrDict.keys())) - + for key in inlist: - self.WriteLog(key,"Header","black") + self.WriteLog(key, "Header", "black") for subkey in self.UpdateHdrDict[key]: value = "\t" + subkey + SPACE + \ self.UpdateHdrDict[key][subkey] addsp = 25 - len(value) if key in self.SetHdrDict: if subkey in self.SetHdrDict[key]: - value = value + SPACE*addsp + applied + value = value + SPACE * addsp + applied tset = 'black' else: - value = value + SPACE*addsp + not_applied + value = value + SPACE * addsp + not_applied tset = 'red' else: - value = value + SPACE*addsp + not_applied + value = value + SPACE * addsp + not_applied tset = 'red' - #insert info on Log notebook - self.WriteLog(value,"Header",tset) + # insert info on Log notebook + self.WriteLog(value, "Header", tset) if type == "dump": - self.WriteLog("<end>","Header","blue") + self.WriteLog("<end>", "Header", "blue") if self.UpdateTimeDict: if type == "dump": - self.WriteLog("\n<Dump Update Dictionary>","Time","blue") + self.WriteLog("\n<Dump Update Dictionary>", "Time", "blue") inlist = sorted(list(self.UpdateTimeDict.keys())) for key in inlist: - self.WriteLog(key,"Time","black") + self.WriteLog(key, "Time", "black") for var in self.ShiftVars: if var[0] in self.UpdateTimeDict[key]: addsp = 15 - len(var[0]) - value = "\t" + var[0] + SPACE*addsp + \ + value = "\t" + var[0] + SPACE * addsp + \ str(self.UpdateTimeDict[key][var[0]]) addsp = 35 - len(value) if key in self.SetTimeDict: if var[0] in self.SetTimeDict[key]: - value = value + SPACE*addsp + applied + value = value + SPACE * addsp + applied tset = 'black' else: - value = value + SPACE*addsp + not_applied + value = value + SPACE * addsp + not_applied tset = 'red' else: - value = value + SPACE*addsp + not_applied + value = value + SPACE * addsp + not_applied tset = 'red' - #insert info on Log notebook - self.WriteLog(value,"Time",tset) + # insert info on Log notebook + self.WriteLog(value, "Time", tset) if type == "dump": - self.WriteLog("<end>","Time","blue") + self.WriteLog("<end>", "Time", "blue") ################################################################## + def Exit(self): """ a no questions asked exit @@ -3211,13 +3313,14 @@ class MainWindow: sys.exit(0) ################################################################## + def ExitCheck(self): """ before exitting test to see if any UpdateHdrDict values have not yet been applied and allow user to apply before exiting """ - #need to deal with case when neither of below are true + # need to deal with case when neither of below are true self.UpdateHdr() for var in self.UpdateHdrDict: self.addTextInfoBar(" " + var + "...", 'orange') @@ -3232,21 +3335,22 @@ class MainWindow: sys.exit(0) ################################################################## - def ExitWidget(self,master): + + def ExitWidget(self, master): """ Allow user to apply UpdateHdrDict entries that have not been applied """ -# first see if we got here from ExitCheck. If so kill window + # first see if we got here from ExitCheck. If so kill window try: self.tl_State = self.Check_tl.winfo_exists() - if self.tl_State : + if self.tl_State: self.killWindow(self.Check_tl) except Exception as e: pass -# Check to see if this window is lingering around. If so raise, -# else create + # Check to see if this window is lingering around. If so raise, + # else create try: self.tl_State = self.Exit_tl.winfo_exists() except Exception as e: @@ -3263,25 +3367,25 @@ class MainWindow: self.Exit_b = Button(self.Exit_tl, text="Exit", - relief = "ridge", + relief="ridge", cursor='pirate', activebackground='red', - command= Command(self.Exit) + command=Command(self.Exit) ) self.Exit_b.pack(side='bottom', fill='x') self.Return_b = Button(self.Exit_tl, text="Cancel", - relief = "ridge", + relief="ridge", cursor='pirate', activebackground='orange', - command= Command( + command=Command( self.killWindow, self.Exit_tl) ) self.Return_b.pack(side='bottom', fill='x') self.ExitEntry_fm = Frame(self.Exit_tl, - relief = 'groove', + relief='groove', borderwidth=2 ) self.ExitEntry_fm.pack(side='left', @@ -3295,6 +3399,7 @@ class MainWindow: ).pack(side='left', anchor='w') ######################################### + def killWindow(self, widget): """ Destroy Widget and Set InfoBar to Default @@ -3303,6 +3408,7 @@ class MainWindow: self.addTextInfoBar() ################################################################## + def ClearAllTrace(self, all=0): """ clear values in UpdateHdrDict if the associated trace @@ -3318,28 +3424,30 @@ class MainWindow: except Exception as e: pass - #clear entry boxes and check boxes + # clear entry boxes and check boxes self.ClearAll(self.NewVars) self.ClearAll(self.StatChanListVars) self.ClearAll(self.SetHdrVars) ################################################################## + def ClearAllGlobal(self, varlist): """ clear GU values and set global match to wildcard """ self.addTextInfoBar() - for var in varlist : + for var in varlist: self.setValue(var[1], "*") self.setValue(var[3]) ####################################### + def ResetTimeShift(self): """ set vars to display input format """ -# self.addTextInfoBar() + # self.addTextInfoBar() self.TypeTimeCor.set(0) self.TSShift.set(0.0) self.TimeTagQuest.set("") @@ -3354,22 +3462,25 @@ class MainWindow: self.WildLoc.set(0) ################################################################## - def ClearAll(self, varlist) : + + def ClearAll(self, varlist): """ clear a variable list """ self.addTextInfoBar() - for var in varlist : + for var in varlist: self.setValue(var[1]) ################################################################## - def ClearTxt(self, var) : + + def ClearTxt(self, var): """ clear text """ var.clear() ####################################### + def setValue(self, var, value=''): """ Sets Value of var @@ -3377,6 +3488,7 @@ class MainWindow: var.set(value) ####################################### + def addTextInfoBar(self, str='', bg='yellow'): """ Adds Text To InfoBar @@ -3398,6 +3510,7 @@ class MainWindow: self.InfoString_l.configure(background=bg, text=str) ####################################### + def wait(self, words, cnt): """ puts words plus cnt to info bar @@ -3408,11 +3521,12 @@ class MainWindow: self.addTextInfoBar(txt, 'lightblue') ####################################### + def ButtonState(self, newstate="normal"): """ changes state of activity buttons """ - #buttons that should be deactivated during activity + # buttons that should be deactivated during activity ButtonList = ( self.BuildTrcList_b, self.ModHdr_b, @@ -3424,17 +3538,19 @@ class MainWindow: ) for item in ButtonList: item.configure(state=newstate) + ########################################## - def getPath (self, var, clear=1) : + + def getPath(self, var, clear=1): """ Concatonate paths """ - self.var=var + self.var = var if clear: self.var.set('') - newpath_dd = DirectoryDialog (self.root) - self.path = newpath_dd.go (dir_or_file = os.getcwd()) - if self.path != None : + newpath_dd = DirectoryDialog(self.root) + self.path = newpath_dd.go(dir_or_file=os.getcwd()) + if self.path is not None: if self.var.get(): self.var.set(self.var.get() + ':') if len(self.path) == 1 and self.path[0] == "/": @@ -3445,12 +3561,13 @@ class MainWindow: self.var.set(self.var.get() + self.path) ####################################### + def CancelTL(self, runvar, title): """ creates a window for canceling trace modifications """ - #disable all buttons that write to traces + # disable all buttons that write to traces self.ButtonState("disabled") self.Cancel_tl = Toplevel(self.root) @@ -3458,15 +3575,15 @@ class MainWindow: self.Cancel_b = Button(self.Cancel_tl, text="Cancel", cursor='pirate', - relief = "ridge", + relief="ridge", activebackground='red', -# command= Command(self.setValue, runvar, 0) -command= Command(self.KillCancelTL, runvar) -) + # command= Command(self.setValue, runvar, 0) + command=Command(self.KillCancelTL, runvar) + ) self.Cancel_b.pack(side='bottom', fill='x') self.Text_fm = Frame(self.Cancel_tl, - relief = 'groove', + relief='groove', borderwidth=2 ) self.Text_fm.pack(side='top', @@ -3479,7 +3596,9 @@ command= Command(self.KillCancelTL, runvar) text=infotext, background='yellow' ).pack(side='left', anchor='w') + ####################################### + def KillCancelTL(self, runvar): """ kills cancel window and unsets runvar @@ -3489,6 +3608,7 @@ command= Command(self.KillCancelTL, runvar) self.ButtonState() ####################################### + def WarnWidget(self, master, action): """ Toplevel to warn user if headers have been modified @@ -3510,7 +3630,7 @@ command= Command(self.KillCancelTL, runvar) self.WarnWidgetCancel_b = Button(self.WarnWidget_tl, text="Cancel", cursor='pirate', - relief = "ridge", + relief="ridge", background='red', activebackgroun='red', command=Command( @@ -3530,8 +3650,8 @@ command= Command(self.KillCancelTL, runvar) self.WarnWidgetDismiss_b.pack(side='bottom', fill='x') self.ReBuildTrcList_b = Button(self.WarnWidget_tl, - activebackground = 'green', - relief = "ridge", + activebackground='green', + relief="ridge", background='lightblue', text="Rebuild db Now", command=Command( @@ -3551,27 +3671,28 @@ command= Command(self.KillCancelTL, runvar) self.WarnWidgetDismiss_b.pack(side='bottom', fill='x') self.NewOnly_b = Button(self.WarnWidget_tl, - activebackground = 'green', - relief = "ridge", + activebackground='green', + relief="ridge", background='lightblue', - text = "Apply Unapplied Only", - command = Command(self.NewOnlyTime) + text="Apply Unapplied Only", + command=Command(self.NewOnlyTime) ) self.NewOnly_b.pack(side='bottom', fill='x') elif action == "undo": self.WarnWidgetDismiss_b = Button(self.WarnWidget_tl, - text="Ignore & Undo Corrections", + text=("Ignore & Undo " + "Corrections"), cursor='pirate', relief="ridge", activebackground='orange', - command= Command( + command=Command( self.Ignore, action) ) self.WarnWidgetDismiss_b.pack(side='bottom', fill='x') self.Text_fm = Frame(self.WarnWidget_tl, - relief = 'groove', + relief='groove', borderwidth=2 ) self.Text_fm.pack(side='top', @@ -3579,7 +3700,7 @@ command= Command(self.KillCancelTL, runvar) pady=5 ) if action == "undo": - infotext="This will only remove single and cumulative "\ + infotext = "This will only remove single and cumulative "\ "corrections.\nReview 'List Time Corrections\' to "\ "better understand corrections\nalready applied to "\ "trace headers. Consider recalculating start"\ @@ -3601,6 +3722,7 @@ command= Command(self.KillCancelTL, runvar) ).pack(side='left', anchor='w') ####################################### + def CancelWarnTL(self): self.killWindow(self.WarnWidget_tl) self.ActiveText.set("") @@ -3608,6 +3730,7 @@ command= Command(self.KillCancelTL, runvar) self.CancelWarn.set(1) ####################################### + def Ignore(self, action): """ here user has ignored recommendation to rebuild db before proceeding @@ -3619,24 +3742,25 @@ command= Command(self.KillCancelTL, runvar) # let user know they may have problems if action == "time": text = "\n*****************************************" - self.WriteLog(text,"Time","red") + self.WriteLog(text, "Time", "red") text = "* WARNING: Ignored advice to rebuild db *" - self.WriteLog(text,"Time","red") + self.WriteLog(text, "Time", "red") text = "*****************************************" - self.WriteLog(text,"Time","red") + self.WriteLog(text, "Time", "red") self.IgnoreWarn.set(1) elif action == "headers": text = "\n*****************************************" - self.WriteLog(text,"Header","red") + self.WriteLog(text, "Header", "red") text = "* WARNING: Ignored advice to rebuild db *" - self.WriteLog(text,"Header","red") + self.WriteLog(text, "Header", "red") text = "*****************************************" - self.WriteLog(text,"Header","red") + self.WriteLog(text, "Header", "red") self.IgnoreWarn.set(1) elif action == "undo": self.IgnoreWarn.set(1) ####################################### + def saveWidget(self, master, type=""): """ Toplevel to save update dictionary or log text to file @@ -3654,7 +3778,7 @@ command= Command(self.KillCancelTL, runvar) # setup output file name (year, month, day, hour, minute, second, weekday, yearday, daylight) = time.localtime(time.time()) - now = ".".join(map(str, (year, yearday, hour, minute)), ) + now = ".".join(list(map(str, (year, yearday, hour, minute))), ) if type == "templ": self.Savefile.set("fixhdr_tmpl." + now) title = "Save Template File As:" @@ -3668,7 +3792,7 @@ command= Command(self.KillCancelTL, runvar) if self.LogVar.get() == 3: self.Savefile.set("fixhdr_LogEndian." + now) if self.LogVar.get() == 4: - textlist=self.Savefile.set("fixhdr_Summary." + now) + textlist = self.Savefile.set("fixhdr_Summary." + now) title = "Save Log File As:" box_length = len(self.Savefile.get()) + 15 @@ -3677,9 +3801,9 @@ command= Command(self.KillCancelTL, runvar) self.saveWidgetCancel_b = Button(self.saveWidget_tl, text="Cancel", cursor='pirate', - relief = "ridge", + relief="ridge", activebackground='red', - command= Command( + command=Command( self.killWindow, self.saveWidget_tl) ) @@ -3688,9 +3812,9 @@ command= Command(self.KillCancelTL, runvar) self.saveWidgetSave_b = Button(self.saveWidget_tl, text="Save", background='lightblue', - relief = "ridge", + relief="ridge", activebackground='green', - command = Command( + command=Command( self.writeFile, self.saveWidget_tl, self.Savefile, type) @@ -3698,7 +3822,7 @@ command= Command(self.KillCancelTL, runvar) self.saveWidgetSave_b.pack(side='bottom', fill='x') self.saveWidgetEntry_fm = Frame(self.saveWidget_tl, - relief = 'groove', + relief='groove', borderwidth=2 ) self.saveWidgetEntry_fm.pack(side='left', @@ -3707,13 +3831,14 @@ command= Command(self.KillCancelTL, runvar) ) self.saveWidgetEntry_e = Entry(self.saveWidgetEntry_fm, - textvariable = self.Savefile, - width = box_length + textvariable=self.Savefile, + width=box_length ) self.saveWidgetEntry_e.pack( side='left', anchor='w', fill='x', expand=1) ########################################## + def writeFile(self, master, file, type=""): """ Write File to disk @@ -3721,7 +3846,7 @@ command= Command(self.KillCancelTL, runvar) if os.path.isfile(file.get()): self.Continue_dl = Pmw.MessageDialog( - master,title="WARNING",defaultbutton=1, + master, title="WARNING", defaultbutton=1, buttons=('Overwrite', 'Cancel'), message_text='The File exists!' ) @@ -3729,14 +3854,14 @@ command= Command(self.KillCancelTL, runvar) else: self.Result = "Overwrite" - if ( self.Result == "Cancel"): + if (self.Result == "Cancel"): self.addTextInfoBar() - elif ( self.Result == "Overwrite"): + elif (self.Result == "Overwrite"): master.destroy() if type == "templ": try: - #make sure current entries are included + # make sure current entries are included self.UpdateHdr(self.StationName.get()) if self.UpdateHdrDict or self.UpdateTimeDict: outfile = open(file.get(), "w") @@ -3785,7 +3910,7 @@ command= Command(self.KillCancelTL, runvar) outfile.write("%s\n" % "timelist{") inlist = sorted(list(self.UpdateTimeDict.keys())) for key in inlist: - timekey=key + timekey = key for var in self.ShiftVars: if var[0] in self.UpdateTimeDict[key]: if var[0] == "Corr_Type": @@ -3807,19 +3932,19 @@ command= Command(self.KillCancelTL, runvar) # Write some log info if self.UpdateHdrDict: - self.WriteLog("\n<Save Template>","Header","blue") + self.WriteLog("\n<Save Template>", "Header", "blue") self.WriteLog("File: %s" % file.get(), - "Header","dkgreen") + "Header", "dkgreen") if self.UpdateTimeDict: - self.WriteLog("\n<Save Template>","Time","blue") + self.WriteLog("\n<Save Template>", "Time", "blue") self.WriteLog("File: %s" % file.get(), - "Time","dkgreen") + "Time", "dkgreen") if self.UpdateHdrDict or self.UpdateTimeDict: self.DumpUpdateDicts() if self.UpdateHdrDict: - self.WriteLog("<end>","Header","blue") + self.WriteLog("<end>", "Header", "blue") if self.UpdateTimeDict: - self.WriteLog("<end>","Time","blue") + self.WriteLog("<end>", "Time", "blue") self.addTextInfoBar("Wrote Template File: %s " % file.get(), 'green') @@ -3836,9 +3961,9 @@ command= Command(self.KillCancelTL, runvar) else: try: self.LogText.exportfile(file.get()) - self.WriteLog("\n<Save Log>","All","blue") - self.WriteLog("File: %s" % file.get(),"All","dkgreen") - self.WriteLog("<end>","All","blue") + self.WriteLog("\n<Save Log>", "All", "blue") + self.WriteLog("File: %s" % file.get(), "All", "dkgreen") + self.WriteLog("<end>", "All", "blue") self.addTextInfoBar("Wrote Log File: %s " % file.get(), 'green') except IOError as e: @@ -3852,20 +3977,19 @@ command= Command(self.KillCancelTL, runvar) """ Find a file and import into text window """ -# timelist=[] -# hdrlist=[] + # timelist=[] + # hdrlist=[] if self.BatchFile.get(): selection = self.BatchFile.get() else: - #if not self.DataDirList: - #err = "You must build a Trace db before loading template" - #self.addTextInfoBar(err, 'red') - #return - selection = askopenfilename\ - (filetypes = [("All", "*")]) + # if not self.DataDirList: + # err = "You must build a Trace db before loading template" + # self.addTextInfoBar(err, 'red') + # return + selection = askopenfilename(filetypes=[("All", "*")]) if selection: try: - inputfile = open(selection,"r") + inputfile = open(selection, "r") self.UpdateHdrDict = {} self.SetHdrDict = {} self.UpdateTimeDict = {} @@ -3873,23 +3997,24 @@ command= Command(self.KillCancelTL, runvar) self.ClearAll(self.NewVars) self.ClearAll(self.SetHdrVars) self.ClearAll(self.ShiftVars) - while 1: + while True: newline = inputfile.readline() - if not newline : + if not newline: break if newline[0] == "#" or newline[:-1] == "": continue if newline[0] == "}": print("ERROR in Template File Format") - if newline[:7] == "hdrlist" : - while 1: + if newline[:7] == "hdrlist": + while True: newline = inputfile.readline() - if not newline : + if not newline: break if newline[0] == "#" or newline[:-1] == "": continue - if newline[0] == "}": break - if len(newline[:-1].split()) != 2 : + if newline[0] == "}": + break + if len(newline[:-1].split()) != 2: self.UpdateTimeDict = {} break try: @@ -3897,9 +4022,9 @@ command= Command(self.KillCancelTL, runvar) except Exception as e: print("ERROR in Template File Format") break - if key not in self.UpdateHdrDict : + if key not in self.UpdateHdrDict: self.UpdateHdrDict[key] = {} - (stat,chan,loc,net) = newkey.split(":") + (stat, chan, loc, net) = newkey.split(":") if stat: stat = stat.upper() self.UpdateHdrDict[key]["Station_Name"] = stat @@ -3912,18 +4037,19 @@ command= Command(self.KillCancelTL, runvar) if net: net = net.upper() self.UpdateHdrDict[key]["Network_Code"] = net - elif newline[:8] == "timelist" : - while 1: + elif newline[:8] == "timelist": + while True: newline = inputfile.readline() - if not newline : break + if not newline: + break if newline[0] == "#" or newline[:-1] == "": continue if newline[0] == "}": break - if len(newline[:-1].split()) != 6 : - self.UpdateTimeDict={} + if len(newline[:-1].split()) != 6: + self.UpdateTimeDict = {} break - (id, stime,etime,shift,quest,type) = \ + (id, stime, etime, shift, quest, type) = \ newline[:-1].split() if id not in self.UpdateTimeDict: self.UpdateTimeDict[id] = {} @@ -3946,8 +4072,8 @@ command= Command(self.KillCancelTL, runvar) = quest.strip() if type: if shift != "NA" and shift != "na": - if type.strip() == "add":\ - type = 0 + if type.strip() == "add": + type = 0 elif type.strip() == "replace": type = 1 else: @@ -3962,44 +4088,36 @@ command= Command(self.KillCancelTL, runvar) return inputfile.close() if not BATCHMODE: - # Write some log info + # Write some log info if self.UpdateHdrDict: - self.WriteLog("\n<Load Template>", "Header","blue") + self.WriteLog("\n<Load Template>", "Header", "blue") self.WriteLog("File: %s" % selection, - "Header","dkgreen") + "Header", "dkgreen") if self.UpdateTimeDict: - self.WriteLog("\n<Load Template>", "Time","blue") + self.WriteLog("\n<Load Template>", "Time", "blue") self.WriteLog("File: %s" % selection, - "Time","dkgreen") + "Time", "dkgreen") if self.UpdateHdrDict or self.UpdateTimeDict: self.DumpUpdateDicts("load") if self.UpdateHdrDict: - self.WriteLog("<end>","Header","blue") + self.WriteLog("<end>", "Header", "blue") if self.UpdateTimeDict: - self.WriteLog("<end>","Time","blue") + self.WriteLog("<end>", "Time", "blue") info = "Load Template: %s successful" % selection self.addTextInfoBar(info, 'green') except IOError as e: err = "ERROR: Can't Load Template: %s" % selection, e self.addTextInfoBar(err, 'red') - if BATCHMODE: sys.exit(1) + if BATCHMODE: + sys.exit(1) if not BATCHMODE: self.DisplayLog() -########################################## - - def killWindow(self, widget): - """ - Destroy Widget and Set InfoBar to Default - """ - widget.destroy() -# self.addTextInfoBar() - - ####################################### - def buildHelp(self,master): + + def buildHelp(self, master): """ Populate Help NoteBook """ @@ -4007,20 +4125,21 @@ command= Command(self.KillCancelTL, runvar) self.Help_nb = master.add('Help') self.TemplateFormat_b = Button(self.Help_nb, - activebackground = 'green', - background = 'lightblue', + activebackground='green', + background='lightblue', text="Template Format", - activeforeground= 'black', - command = Command( + activeforeground='black', + command=Command( self.TemplateFormat, self.Help_nb) ) self.TemplateFormat_b.pack(side='top', anchor='e', padx=5, pady=5) - self.balloon.bind(self.TemplateFormat_b, "Display example format \nfor 'Template' file.") + self.balloon.bind(self.TemplateFormat_b, + "Display example format \nfor 'Template' file.") self.HelpText = Pmw.ScrolledText(self.Help_nb, borderframe=1) self.HelpText.pack(side='bottom', fill='both', expand=1) - #local variables + # local variables HelpTextinsert = self.HelpText.insert self.HelpText.tag_config("hdr1", foreground="blue") @@ -4068,8 +4187,8 @@ command= Command(self.KillCancelTL, runvar) HelpTextinsert("end", """ and """) HelpTextinsert("end", "[Global Modify]\n", "hdr2") HelpTextinsert("end", """ provide a means to read and modify mseed header fields (station, channel, - location code, and network code) for files found beneath a specified - directory list. """) + location code, and network code) for files found beneath a specified + directory list. """) # noqa: E501 HelpTextinsert("end", "[Time Shift] ", "hdr2") HelpTextinsert("end", """allows the user to apply a bulk time shift to traces that fall between a start and end time and to set a header @@ -4078,19 +4197,20 @@ command= Command(self.KillCancelTL, runvar) HelpTextinsert("end", """converts traces between little and big, or big and little endian headers. The """) HelpTextinsert("end", "[Log]", "hdr2") - HelpTextinsert("end", """ notebook + HelpTextinsert("end", """ notebook maintains records of key events.\n""") HelpTextinsert("end", "\n [Root Window]\n", "hdr2") HelpTextinsert("end", """ Buttons:\n""") HelpTextinsert("end", " <Load Template>", "bttn") HelpTextinsert("end", """: loads a previously saved or user created mapping - of header and timing modification that then can be applied.\n""") + of header and timing modification that then can be applied.\n""") # noqa: E501 HelpTextinsert("end", " <Save Template>", "bttn") - HelpTextinsert("end", """: saves a map of all header and timing modifications.\n""") + HelpTextinsert( + "end", """: saves a map of all header and timing modifications.\n""") # noqa: E501 HelpTextinsert("end", " <Exit>", "bttn") HelpTextinsert("end", """: Exits fixhdr and will query if not all mappings in - Updata_Dictionary have been applied.\n""") + Updata_Dictionary have been applied.\n""") # noqa: E501 HelpTextinsert("end", "\n [Trace Headers]", "hdr2") HelpTextinsert("end", """ @@ -4107,29 +4227,31 @@ command= Command(self.KillCancelTL, runvar) Directories" entry box (a colon separated list) and builds a list of mseed files found indexing them on unique values of <sta><chn><loc><net><sps>. You can narrow your search by entering stations in the "Find Only Stations" - entry box (a colon separated list).\n""") + entry box (a colon separated list).\n""") # noqa: E501 HelpTextinsert("end", " <Find>", "bttn") HelpTextinsert("end", """: Launches a file browser allowing the user to add directories to the "Data Directories" entry box. Double clicking selects - the new directory.\n""") + the new directory.\n""") # noqa: E501 HelpTextinsert("end", " <Clear>", "bttn") - HelpTextinsert("end", """: Clears the "Data Directories" entry box.\n""") + HelpTextinsert( + "end", """: Clears the "Data Directories" entry box.\n""") HelpTextinsert("end", " <List Traces>", "bttn") - HelpTextinsert("end", """: Lists all traces for the selected Sta:Chan:Loc:Net:Sps.\n""") + HelpTextinsert( + "end", """: Lists all traces for the selected Sta:Chan:Loc:Net:Sps.\n""") # noqa: E501 HelpTextinsert("end", " <Modify Headers>", "bttn") HelpTextinsert("end", """: Applies all current values in the Update_Dictionary - (that can be viewed in the """) + (that can be viewed in the """) # noqa: E501 HelpTextinsert("end", "[Log] ", "hdr2") HelpTextinsert("end", """notebook) to the current trace list that was built using """) HelpTextinsert("end", "<Build Trace db>\n", "bttn") HelpTextinsert("end", " <Clear Current>", "bttn") - HelpTextinsert("end", """: clears all entries in the Update_Dictionary and - display for the currently selected sta:chan:loc:net:sps that - have not been applied.\n""") + HelpTextinsert("end", """: clears all entries in the Update_Dictionary and + display for the currently selected sta:chan:loc:net:sps that + have not been applied.\n""") # noqa: E501 HelpTextinsert("end", " <Clear All>", "bttn") HelpTextinsert("end", """: clears all entries in the Update_Dictionary that - have not been applied.\n""") + have not been applied.\n""") # noqa: E501 HelpTextinsert("end", "\n [Global Modify]", "hdr2") HelpTextinsert("end", """ @@ -4143,7 +4265,7 @@ command= Command(self.KillCancelTL, runvar) Update_Dictionary using For Headers Matching" entries to determine which <sta><chn><loc><net><sps> to modify. This only creates entries in the dictionary and does NOT apply them to the mseed headers. You must - use""") + use""") # noqa: E501 HelpTextinsert("end", " [Trace Headers]->", "hdr2") HelpTextinsert("end", "<Modify Headers> ", "bttn") HelpTextinsert("end", """to apply these updates.\n""") @@ -4163,16 +4285,17 @@ command= Command(self.KillCancelTL, runvar) flags in the mseed file's Fixed Section of Data Header >> "Applied" indicators notify a user when corrections have been appied in this instance of fixhdr. - Buttons:\n""") - HelpTextinsert("end", " <How to Treat Existing Corrections>", "bttn") - HelpTextinsert("end", """: you can choose to either add to any - correction listed in the Fixed Header or Replace + Buttons:\n""") # noqa: E501 + HelpTextinsert( + "end", " <How to Treat Existing Corrections>", "bttn") + HelpTextinsert("end", """: you can choose to either add to any + correction listed in the Fixed Header or Replace any existing correction with the one entered.\n""") HelpTextinsert("end", " <Undo Time Corrections>", "bttn") - HelpTextinsert("end", """: Allows user to un-apply previously - applied timing corrections. Note: Use with caution. This - will only remove single and cumulative corrections. - Review 'List Time Corrections' to better understand + HelpTextinsert("end", """: Allows user to un-apply previously + applied timing corrections. Note: Use with caution. This + will only remove single and cumulative corrections. + Review 'List Time Corrections' to better understand corrections already applied to trace headers.\n""") HelpTextinsert("end", " <List Time Corrections>", "bttn") HelpTextinsert("end", """: Displays time corrections for traces @@ -4180,15 +4303,15 @@ command= Command(self.KillCancelTL, runvar) HelpTextinsert("end", " <Apply Time Correction> ", "bttn") HelpTextinsert("end", """to apply these updates.\n""") HelpTextinsert("end", " <Time Set>", "bttn") - HelpTextinsert("end", """: Allows user to build a dictionary of timing corrections - to be applied with the "Apply Time Corrections" button. i.e. + HelpTextinsert("end", """: Allows user to build a dictionary of timing corrections + to be applied with the "Apply Time Corrections" button. i.e. timing corrections for multiple Stat:Loc:Net selections can - be set prior to applying in a single instance.\n""") + be set prior to applying in a single instance.\n""") # noqa: E501 HelpTextinsert("end", " <Recalc Start/End>", "bttn") - HelpTextinsert("end", """: resets the start and end times from the trace - headers. The first time a trace is read in the start and end - times are cached for future use. If you change these times, - this button is used to update the cache and display.\n""") + HelpTextinsert("end", """: resets the start and end times from the trace + headers. The first time a trace is read in the start and end + times are cached for future use. If you change these times, + this button is used to update the cache and display.\n""") # noqa: E501 HelpTextinsert("end", " <Clear All>", "bttn") HelpTextinsert("end", """: clears all current entries.\n""") @@ -4197,11 +4320,13 @@ command= Command(self.KillCancelTL, runvar) General: >> displays the number of big and little endian files found. Allows user to convert between big and little endian headers. - Buttons:\n""") + Buttons:\n""") # noqa: E501 HelpTextinsert("end", " <Convert to Big>", "bttn") - HelpTextinsert("end", """: Converts headers from little to big endian\n""") + HelpTextinsert( + "end", """: Converts headers from little to big endian\n""") HelpTextinsert("end", " <Convert to Little>", "bttn") - HelpTextinsert("end", """: Converts headers from big to little endian\n""") + HelpTextinsert( + "end", """: Converts headers from big to little endian\n""") HelpTextinsert("end", "\n [Log]", "hdr2") HelpTextinsert("end", """ @@ -4209,10 +4334,10 @@ command= Command(self.KillCancelTL, runvar) >> displays key events (e.g. "Build Trace db", "Modify Headers", etc.). Radio buttons allow you to select all log messages or window only those messages related to Header events, Time events, or changes in endianess - Buttons:\n""") + Buttons:\n""") # noqa: E501 HelpTextinsert("end", " <Dump UpdateHdrDict>", "bttn") HelpTextinsert("end", """: Dumps the current values in the Update_Dictionary and - indicates whether or not they have been applied (i.e.""") + indicates whether or not they have been applied (i.e.""") # noqa: E501 HelpTextinsert("end", " <Modify Headers>\n", "bttn") HelpTextinsert("end", """ has been run).\n""") HelpTextinsert("end", " <Save Log File>", "bttn") @@ -4221,7 +4346,8 @@ command= Command(self.KillCancelTL, runvar) HelpTextinsert("end", """: Clears text window and flushes buffer.\n""") HelpTextinsert("end", "\nKEYWORDS", "hdr1") - HelpTextinsert("end", """ mseed; header information; header modification\n""") + HelpTextinsert( + "end", """ mseed; header information; header modification\n""") HelpTextinsert("end", "\nSEE ALSO", "hdr1") HelpTextinsert("end", """ mseedhdr & SEED manual\n""") @@ -4233,7 +4359,7 @@ command= Command(self.KillCancelTL, runvar) ######################################## - def TemplateFormat(self,master): + def TemplateFormat(self, master): """ Template file format help and examples """ @@ -4251,11 +4377,11 @@ command= Command(self.KillCancelTL, runvar) self.helpFileFormat_tl.title("Template Format") self.ExitFileHelp_b = Button(self.helpFileFormat_tl, - activebackground = 'red', - cursor = 'pirate', - background = 'lightblue', + activebackground='red', + cursor='pirate', + background='lightblue', text="Done", - command = Command( + command=Command( self.killWindow, self.helpFileFormat_tl) ) @@ -4264,7 +4390,7 @@ command= Command(self.KillCancelTL, runvar) borderframe=1, ) self.FileFormatText.pack(side='bottom', fill='both', expand=1) - #local variable + # local variable FileFormatTextinsert = self.FileFormatText.insert self.FileFormatText.tag_config("highlight", foreground="red") @@ -4277,7 +4403,7 @@ command= Command(self.KillCancelTL, runvar) FileFormatTextinsert("end", "timelist", "highlight") FileFormatTextinsert("end", """. These list are delimitted by '{}'. Comments are allowed in the template file - and are denoted by a '#' in the first column. + and are denoted by a '#' in the first column. For the """) FileFormatTextinsert("end", "hdrlist", "highlight") @@ -4290,8 +4416,8 @@ command= Command(self.KillCancelTL, runvar) sta:loc:net Start_Time End_Time Shift(s) Time_Tag Corr_Type sta:loc:net yyyy:ddd:hh:mm:ss yyyy:ddd:hh:mm:ss float/NA set/unset/NA add/replace/NA - EXAMPLE:""") - FileFormatTextinsert("end",""" + EXAMPLE:""") # noqa: E501 + FileFormatTextinsert("end", """ # Header Changes # stat:chan:loc:net:sps stat:chan:loc:net @@ -4306,10 +4432,11 @@ command= Command(self.KillCancelTL, runvar) timelist{ 9294::SS 2005:304:00:00:00 2005:305:22:15:10 0.56 set add } - \n""", "example") + \n""", "example") # noqa: E501 ################################################################## - def buildMSformat(self,master): + + def buildMSformat(self, master): """ Populate MSEED format definition noteBook """ @@ -4319,7 +4446,6 @@ command= Command(self.KillCancelTL, runvar) borderframe=1) self.MSformatText.pack(side='bottom', fill='both', expand=1) - self.MSformatText.settext("""Appendix A From "SEED Reference Manual, v2.3, Feb. 1993: Channel Naming Contributed by Scott Halbert @@ -4626,7 +4752,7 @@ individual elements of an array. Refer to blockettes 35, 400, & Orientation Code I Incoherent Beam C Coherent Beam - F FK Beam + F FK Beam O Origin Beam Dip/Azimuth: Ground motion vector (reverse dip/azimuth if signal polarity incorrect) @@ -4658,9 +4784,11 @@ the number of characters in the record (including the carriage return and line feed that terminates each line). Log messages are packed into records until a message falls into a new minute. Log records have no blockettes, so the strings start at offset -48.""") +48.""") # noqa: E501 + ################################################################## + def main(): if BatchFile: mw = MainWindow("fixhdr %s" % VERSION, BatchFile) @@ -4668,9 +4796,7 @@ def main(): mw = MainWindow("fixhdr %s" % VERSION) mw.root.geometry("650x400") mw.root.mainloop() - # import profile - # profile.run("mw.root.mainloop()") -if __name__ == '__main__' : - main() +if __name__ == '__main__': + main() diff --git a/setup.py b/setup.py index 8dfa0dc43980feae59095867190df9241ec54ead..e41ace994e4f2fc5ac47c2a4517648afb67ac597 100644 --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ setup( ], }, install_requires=['Pmw @ https://github.com/schrodinger/pmw-patched/archive/master.tar.gz'], - setup_requires = [], + setup_requires=[], extras_require={ 'dev': [ 'pip',