How to use _getAttributes method in pyatom

Best Python code snippet using pyatom_python

interpret.py

Source:interpret.py Github

copy

Full Screen

1import re2import xml.etree.ElementTree as ElementTree3import argparse4import sys5class ParameterException(Exception):6 pass7class InputFileException(Exception):8 pass9class OutputFileException(Exception):10 pass11class SemanticException(Exception):12 pass13class FormatException(Exception):14 pass15class OperandTypeException(Exception):16 pass17class UndeclaredVarException(Exception):18 pass19class FrameDoesNotExistException(Exception):20 pass21class MissingValueException(Exception):22 pass23class StringOperationException(Exception):24 pass25class InstuctionPoiner(object):26 def __init__(self):27 self.IP=028 self.labels=dict()29 self.callStack=list()30 def RegisterLabel(self,Label:str):31 if Label in self.labels:32 raise SemanticException()33 self.labels[Label]=self.IP34 def GoToLabel(self,Label:str):35 if Label not in self.labels:36 raise SemanticException()37 self.callStack.append(self.IP)38 self.IP=self.labels[Label]39 def Return(self):40 if len(self.callStack)==0:41 raise MissingValueException()42 self.IP=self.callStack.pop()43 def ResetPointer(self):44 self.IP=045 self.callStack=list()46class InstructionProcessor(object):47 def __init__(self, instructionsList):48 self.instructions = instructionsList49 self.symTable=SymbolTable()50 self.InstuctionPoiner=InstuctionPoiner()51 self.stack=list()52 super().__init__()53 def __GetInstruction(self):54 if self.InstuctionPoiner.IP < len(self.instructions):55 ins = self.instructions[self.InstuctionPoiner.IP]56 self.InstuctionPoiner.IP+=157 return ins58 return None59 def Execute(self):60 currentInstruction=self.__GetInstruction()61 while currentInstruction is not None:62 if not isinstance(currentInstruction,LabelInstruction):63 currentInstruction.Execute(self.InstuctionPoiner,self.symTable,self.stack)64 currentInstruction=self.__GetInstruction()65 def RegisterLabels(self):66 currentInstruction=self.__GetInstruction()67 while currentInstruction is not None:68 if isinstance(currentInstruction,LabelInstruction):69 currentInstruction.Execute(self.InstuctionPoiner,self.symTable,self.stack)70 currentInstruction=self.__GetInstruction()71 self.InstuctionPoiner.ResetPointer()72class SymbolTable(object):73 def __init__(self):74 self.GlobalSymbols = dict()75 self.TemporarySymbols=None76 self.LocalSymbols=list()77 return super().__init__()78 def getRequestedSymbolTable(self,symbol:str):79 symbolSourceName = symbol.split("@")[0]80 if symbolSourceName=="TF":81 return self.TemporarySymbols82 elif symbolSourceName=="GF":83 return self.GlobalSymbols84 elif symbolSourceName=="LF":85 if len(self.LocalSymbols)==0:86 raise FrameDoesNotExistException()87 return self.LocalSymbols[-1]88 else:89 raise SyntaxError90 def Insert(self, symbolName:str):91 symbolTable=self.getRequestedSymbolTable(symbolName)92 symbol=Symbol(symbolName)93 if symbolTable==None:94 raise FrameDoesNotExistException()95 if symbol.name in symbolTable.keys():96 raise UndeclaredVarException()97 symbolTable[symbol.name] = symbol;98 def Get(self, symbolName , expectedType=None): 99 symbolTable=self.getRequestedSymbolTable(symbolName)100 101 symbolName = symbolName[symbolName.index('@')+1:]102 if symbolTable==None:103 raise FrameDoesNotExistException()104 if symbolName in symbolTable.keys():105 symbol = symbolTable[symbolName]106 if expectedType!=None and symbol.type!=expectedType:107 raise OperandTypeException()108 return symbol109 raise UndeclaredVarException()110 def CreateFrame(self):111 self.TemporarySymbols=dict()112 def PushFrame(self):113 if self.TemporarySymbols==None:114 raise FrameDoesNotExistException()115 self.LocalSymbols.append(self.TemporarySymbols)116 self.TemporarySymbols=None117 def PopFrame(self):118 if len(self.LocalSymbols)==0:119 raise FrameDoesNotExistException()120 self.TemporarySymbols=self.LocalSymbols.pop()121from enum import Enum122class DataType(Enum):123 INT = 1,124 BOOL = 2,125 STRING = 3126class Symbol(object):127 def __init__(self, name: str):128 self.name = name[name.index('@')+1:]129 self.type = None130 self.value = None131 def __eq__(self, other):132 return self.name == other.name133 def SetValue(self,value):134 if isinstance(value,Symbol):135 self.type=value.type136 self.value=value.value 137 elif isinstance(value,bool): 138 self.type=DataType.BOOL139 self.value=value 140 elif isinstance(value,int) or isinstance(value,float):141 self.type=DataType.INT142 self.value=int(value)143 elif BoolArgumentValidator().Is(value): 144 self.type=DataType.BOOL145 self.value= value != "false"146 elif StringArgumentValidator().Is(value): 147 self.type=DataType.STRING148 self.value=value149 elif isinstance(value,str): 150 self.type=DataType.STRING151 self.value=value 152 elif IntArgumentValidator().Is(value):153 self.type=DataType.INT154 self.value=int(value)155 else:156 raise SemanticException()157 def ExtractValue(value,symTable:SymbolTable,RequiredType:DataType):158 if VarArgumentValidator().Is(value):159 sym=symTable.Get(value,RequiredType)160 if sym.type == None:161 return None162 return sym.value163 if isinstance(value,bool):164 if RequiredType!=None and RequiredType != DataType.BOOL:165 raise OperandTypeException()166 return value167 if isinstance(value,int):168 if RequiredType!=None and RequiredType != DataType.INT:169 raise OperandTypeException()170 return value171 if isinstance(value,str):172 if RequiredType!=None and RequiredType != DataType.STRING:173 raise OperandTypeException()174 return value175 raise SemanticException()176class XmlParser(object):177 def Parse(self, xmlPath):178 tree = ElementTree.parse(xmlPath)179 180 root = tree.getroot();181 self.__CheckRoot(root)182 instructions=list()183 for instruction in root:184 if instruction.tag == 'name' or instruction.tag == 'description':185 continue186 if instruction.tag == 'instruction':187 if int(instruction.get("order"))!=len(instructions)+1:188 raise FormatException()189 instructions.append(self.__CreateInstruction(instruction))190 else:191 raise FormatException()192 return instructions193 def __CheckRoot(self, rootElement):194 if rootElement.tag != 'program' or len(rootElement.attrib) > 3 or rootElement.attrib.get(195 'language') != 'IPPcode18':196 raise FormatException()197 def __CreateInstruction(self, instructionElemment):198 instrucitonCode = instructionElemment.get("opcode")199 if instrucitonCode == "MOVE":200 return MoveInstruction(instructionElemment)201 elif instrucitonCode == "CREATEFRAME":202 return CreateFrameInstruction(instructionElemment)203 elif instrucitonCode == "PUSHFRAME":204 return PushFrameInstruction(instructionElemment)205 elif instrucitonCode == "POPFRAME":206 return PopFrameInstruction(instructionElemment)207 elif instrucitonCode == "DEFVAR":208 return DefVarInstruction(instructionElemment)209 elif instrucitonCode == "CALL":210 return CallInstruction(instructionElemment)211 elif instrucitonCode == "RETURN":212 return ReturnInstruction(instructionElemment)213 elif instrucitonCode == "PUSHS":214 return PushsInstruction(instructionElemment)215 elif instrucitonCode == "POPS":216 return PopsInstruction(instructionElemment)217 elif instrucitonCode == "ADD":218 return AddInstruction(instructionElemment)219 elif instrucitonCode == "SUB":220 return SubInstruction(instructionElemment)221 elif instrucitonCode == "MUL":222 return MulInstruction(instructionElemment)223 elif instrucitonCode == "IDIV":224 return IDivInstruction(instructionElemment)225 elif instrucitonCode == "LT":226 return LTInstruction(instructionElemment)227 elif instrucitonCode == "GT":228 return GTInstruction(instructionElemment)229 elif instrucitonCode == "EQ":230 return EQInstruction(instructionElemment)231 elif instrucitonCode == "AND":232 return AndInstruction(instructionElemment)233 elif instrucitonCode == "OR":234 return OrInstruction(instructionElemment)235 elif instrucitonCode == "NOT":236 return NotInstruction(instructionElemment)237 elif instrucitonCode == "INT2CHAR":238 return IntToCharInstruction(instructionElemment)239 elif instrucitonCode == "STRI2INT":240 return StringToIntInstruction(instructionElemment)241 elif instrucitonCode == "READ":242 return ReadInstruction(instructionElemment)243 elif instrucitonCode == "WRITE":244 return WriteInstruction(instructionElemment)245 elif instrucitonCode == "CONCAT":246 return ConcatInstruction(instructionElemment)247 elif instrucitonCode == "STRLEN":248 return StrLenInstruction(instructionElemment)249 elif instrucitonCode == "GETCHAR":250 return GetCharInstruction(instructionElemment)251 elif instrucitonCode == "SETCHAR":252 return SetCharInstruction(instructionElemment)253 elif instrucitonCode == "TYPE":254 return TypeInstruction(instructionElemment)255 elif instrucitonCode == "LABEL":256 return LabelInstruction(instructionElemment)257 elif instrucitonCode == "JUMP":258 return JumpInstruction(instructionElemment)259 elif instrucitonCode == "JUMPIFEQ":260 return JumpIfEqInstruction(instructionElemment)261 elif instrucitonCode == "JUMPIFNEQ":262 return JumpIfNotEqInstruction(instructionElemment)263 elif instrucitonCode == "DPRINT":264 return DPrintInstruction(instructionElemment)265 elif instrucitonCode == "BREAK":266 return BreakInstruction(instructionElemment)267 else:268 raise SyntaxError269class ValidatorBase(object):270 def Validate(self, inputData: str):271 if not self.Is(inputData):272 raise SyntaxError273 def Is(self, inputData: str):274 raise NotImplemented275class VarNameValidator(ValidatorBase):276 def Is(self, inputData: str):277 return re.match(r"^([a-zA-Z]|-|[_$&%*])([a-zA-Z]|-|[_$&%*]|[0-9]+)*$$", inputData) is not None278class IntArgumentValidator(ValidatorBase):279 def Is(self, inputData: str):280 return re.match(r"^[\x2B\x2D]?[0-9]+$", inputData) is not None281class StringArgumentValidator(ValidatorBase):282 def Is(self, inputData: str):283 return re.match(r"^([a-zA-Z\u0021\u0022\u0024-\u005B\u005D-\uFFFF|(\\\\[0-90-90-9])*$", inputData) is not None284class BoolArgumentValidator(ValidatorBase):285 def Is(self, inputData: str):286 return inputData=="true" or inputData=="false"287class LabelArgumentValidator(ValidatorBase):288 def Is(self, inputData: str):289 return VarNameValidator().Is(inputData)290class TypeArgumentValidator(ValidatorBase):291 def Is(self, inputData: str):292 return inputData == "int" or inputData == "string" or inputData == "bool"293class VarArgumentValidator(ValidatorBase):294 def Is(self, inputData: str):295 if not isinstance(inputData,str):296 return False297 inputParts = inputData.split("@")298 if len(inputParts) < 2:299 return False300 if inputParts[1].find("@") != -1:301 identifier = input[:inputData.find("@") + 1]302 else:303 identifier = inputParts[1]304 return (inputParts[0] == "LF" or inputParts[0] == "TF" or inputParts[0] == "GF") and VarNameValidator().Is(305 identifier)306class AttributeType(Enum):307 INT = 0,308 BOOL = 1,309 STRING = 2,310 LABEL = 3,311 TYPE = 4,312 VAR = 5313 SYMBOL = 6314class Instruction(object):315 def __init__(self, xmlElement):316 pass317 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):318 raise NotImplementedError("This method is abstract")319 def _GetAttributeType(self, element):320 if element.tag != "arg1" and element.tag != "arg2" and element.tag != "arg3":321 raise FormatException()322 typeAttr = element.get("type")323 if typeAttr == "int":324 return AttributeType.INT325 elif typeAttr == "bool":326 return AttributeType.BOOL327 elif typeAttr == "string":328 return AttributeType.STRING329 elif typeAttr == "label":330 return AttributeType.LABEL331 elif typeAttr == "type":332 return AttributeType.TYPE333 elif typeAttr == "var":334 return AttributeType.VAR335 else:336 raise SyntaxError337 def GetAttributeValue(self, element, expectedType):338 type = self._GetAttributeType(element)339 if expectedType == AttributeType.SYMBOL:340 if type != AttributeType.INT and type != AttributeType.BOOL and type != AttributeType.STRING and type != AttributeType.VAR:341 raise SyntaxError342 elif expectedType != type:343 raise OperandTypeException()344 innerText = element.text345 if innerText==None:346 innerText=""347 if type == AttributeType.INT:348 IntArgumentValidator().Validate(innerText)349 return int(innerText)350 elif type == AttributeType.BOOL:351 BoolArgumentValidator().Validate(innerText)352 return innerText=="true"353 elif type == AttributeType.STRING:354 StringArgumentValidator().Validate(innerText)355 return innerText356 elif type == AttributeType.VAR:357 VarArgumentValidator().Validate(innerText)358 return innerText359 elif type == AttributeType.TYPE:360 TypeArgumentValidator().Validate(innerText)361 return innerText362 elif type == AttributeType.LABEL:363 LabelArgumentValidator().Validate(innerText)364 return innerText365 else:366 SyntaxError367 def _GetAttributes(self, element, expectedCount):368 attrs = list(element);369 if len(attrs) != expectedCount:370 raise SyntaxError371 return attrs372class MoveInstruction(Instruction):373 def __init__(self, xmlElement):374 attributes = self._GetAttributes(xmlElement, 2)375 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)376 self.symbol = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)377 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):378 if VarArgumentValidator().Is(self.symbol):379 value=SymTable.Get(self.symbol)380 else:381 value=self.symbol382 target=SymTable.Get(self.var)383 target.SetValue(value)384class CreateFrameInstruction(Instruction):385 def __init__(self, xmlElement):386 self._GetAttributes(xmlElement, 0)387 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):388 SymTable.CreateFrame()389class PushFrameInstruction(Instruction):390 def __init__(self, xmlElement):391 self._GetAttributes(xmlElement, 0)392 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):393 SymTable.PushFrame()394class PopFrameInstruction(Instruction):395 def __init__(self, xmlElement):396 self._GetAttributes(xmlElement, 0)397 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):398 SymTable.PopFrame()399class DefVarInstruction(Instruction):400 def __init__(self, xmlElement):401 attributes = self._GetAttributes(xmlElement, 1)402 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)403 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):404 SymTable.Insert(self.var)405 406class CallInstruction(Instruction):407 def __init__(self, xmlElement):408 attributes = self._GetAttributes(xmlElement, 1)409 self.label = self.GetAttributeValue(attributes[0], AttributeType.LABEL)410 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):411 IP.GoToLabel(self.label)412class ReturnInstruction(Instruction):413 def __init__(self, xmlElement):414 self._GetAttributes(xmlElement, 0)415 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):416 IP.Return()417class PushsInstruction(Instruction):418 def __init__(self, xmlElement):419 attributes = self._GetAttributes(xmlElement, 1)420 self.sym = self.GetAttributeValue(attributes[0], AttributeType.SYMBOL)421 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):422 423 op1=Symbol.ExtractValue(self.sym,SymTable,None)424 Stack.append(op1)425class PopsInstruction(Instruction):426 def __init__(self, xmlElement):427 attributes = self._GetAttributes(xmlElement, 1)428 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)429 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):430 if len(Stack)==0:431 raise MissingValueException()432 SymTable.Get(self.var).SetValue(Stack.pop())433class AddInstruction(Instruction):434 def __init__(self, xmlElement):435 attributes = self._GetAttributes(xmlElement, 3)436 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)437 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)438 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)439 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):440 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.INT)441 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.INT)442 SymTable.Get(self.var).SetValue(op1+op2)443class SubInstruction(Instruction):444 def __init__(self, xmlElement):445 attributes = self._GetAttributes(xmlElement, 3)446 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)447 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)448 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)449 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):450 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.INT)451 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.INT)452 SymTable.Get(self.var).SetValue(op1-op2)453class MulInstruction(Instruction):454 def __init__(self, xmlElement):455 attributes = self._GetAttributes(xmlElement, 3)456 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)457 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)458 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)459 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):460 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.INT)461 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.INT)462 SymTable.Get(self.var).SetValue(op1*op2)463class IDivInstruction(Instruction):464 def __init__(self, xmlElement):465 attributes = self._GetAttributes(xmlElement, 3)466 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)467 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)468 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)469 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):470 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.INT)471 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.INT)472 SymTable.Get(self.var).SetValue(op1/op2)473class LTInstruction(Instruction):474 def __init__(self, xmlElement):475 attributes = self._GetAttributes(xmlElement, 3)476 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)477 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)478 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)479 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):480 op1=Symbol.ExtractValue(self.sym1,SymTable,None)481 op2=Symbol.ExtractValue(self.sym2,SymTable,None)482 if type(op1) is not type(op2):483 raise OperandTypeException()484 SymTable.Get(self.var).SetValue(op1<op2) 485class GTInstruction(Instruction):486 def __init__(self, xmlElement):487 attributes = self._GetAttributes(xmlElement, 3)488 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)489 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)490 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)491 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):492 op1=Symbol.ExtractValue(self.sym1,SymTable,None)493 op2=Symbol.ExtractValue(self.sym2,SymTable,None)494 if type(op1) is not type(op2):495 raise OperandTypeException()496 SymTable.Get(self.var).SetValue(op1>op2)497class EQInstruction(Instruction):498 def __init__(self, xmlElement):499 attributes = self._GetAttributes(xmlElement, 3)500 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)501 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)502 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)503 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):504 op1=Symbol.ExtractValue(self.sym1,SymTable,None)505 op2=Symbol.ExtractValue(self.sym2,SymTable,None)506 if type(op1) is not type(op2):507 raise OperandTypeException()508 SymTable.Get(self.var).SetValue(op1==op2) 509class AndInstruction(Instruction):510 def __init__(self, xmlElement):511 attributes = self._GetAttributes(xmlElement, 3)512 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)513 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)514 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)515 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):516 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.BOOL)517 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.BOOL)518 SymTable.Get(self.var).SetValue(op1 and op2)519class OrInstruction(Instruction):520 def __init__(self, xmlElement):521 attributes = self._GetAttributes(xmlElement, 3)522 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)523 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)524 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)525 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):526 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.BOOL)527 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.BOOL)528 SymTable.Get(self.var).SetValue(op1 or op2)529class NotInstruction(Instruction):530 def __init__(self, xmlElement):531 attributes = self._GetAttributes(xmlElement, 2)532 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)533 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)534 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):535 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.BOOL)536 SymTable.Get(self.var).SetValue( not op1)537class IntToCharInstruction(Instruction):538 def __init__(self, xmlElement):539 attributes = self._GetAttributes(xmlElement, 2)540 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)541 self.sym = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)542 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):543 op1=Symbol.ExtractValue(self.sym,SymTable,DataType.INT)544 545 try:546 char=chr(op1)547 except ValueError:548 raise StringOperationException()549 SymTable.Get(self.var).SetValue(char)550class StringToIntInstruction(Instruction):551 def __init__(self, xmlElement):552 attributes = self._GetAttributes(xmlElement, 3)553 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)554 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)555 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)556 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):557 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.STRING)558 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.INT)559 if (len(op1)-1)<op2 or op2>(len(op1)-1):560 raise StringOperationException()561 SymTable.Get(self.var).SetValue(ord(op1[op2]))562class ReadInstruction(Instruction):563 def __init__(self, xmlElement):564 attributes = self._GetAttributes(xmlElement, 2)565 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)566 self.type = self.GetAttributeValue(attributes[1], AttributeType.TYPE)567 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list): 568 inData = input()569 sym=SymTable.Get(self.var)570 if self.type=="bool":571 data = inData.lower() == "true"572 elif self.type=="int":573 if IntArgumentValidator().Is(inData):574 data = int(inData);575 else:576 data = ""577 elif self.type=="string":578 if StringArgumentValidator().Is(inData):579 data=inData580 else:581 data=""582 sym.SetValue(data)583class WriteInstruction(Instruction):584 def __init__(self, xmlElement):585 attributes = self._GetAttributes(xmlElement, 1)586 self.sym = self.GetAttributeValue(attributes[0], AttributeType.SYMBOL)587 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):588 val = Symbol.ExtractValue(self.sym,SymTable,None)589 if isinstance(val,bool):590 if val:591 val="true"592 else:593 val="false"594 elif isinstance(val,str):595 val=self.__unEscape(val)596 print(val)597 598 def __unEscape(self,s):599 s = re.sub(r"\x5c([0-9][0-9][0-9])", lambda w: chr(int(w.group(1))), s)600 return s601class ConcatInstruction(Instruction):602 def __init__(self, xmlElement):603 attributes = self._GetAttributes(xmlElement, 3)604 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)605 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)606 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)607 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):608 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.STRING)609 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.STRING)610 SymTable.Get(self.var).SetValue(op1+op2)611class StrLenInstruction(Instruction):612 def __init__(self, xmlElement):613 attributes = self._GetAttributes(xmlElement, 2)614 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)615 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)616 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):617 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.STRING)618 SymTable.Get(self.var).SetValue(len(op1))619class GetCharInstruction(Instruction):620 def __init__(self, xmlElement):621 attributes = self._GetAttributes(xmlElement, 3)622 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)623 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)624 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)625 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):626 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.STRING)627 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.INT)628 if (len(op1)-1)<op2 or op2>(len(op1)-1):629 raise StringOperationException()630 SymTable.Get(self.var).SetValue(op1[op2])631class TypeInstruction(Instruction):632 def __init__(self, xmlElement):633 attributes = self._GetAttributes(xmlElement, 2)634 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)635 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)636 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):637 val = Symbol.ExtractValue(self.sym1,SymTable,None)638 if val==None:639 SymTable.Get(self.var).SetValue("")640 elif type(val)==bool: 641 SymTable.Get(self.var).SetValue("bool")642 elif type(val)==int: 643 SymTable.Get(self.var).SetValue("int")644 elif type(val)==str: 645 SymTable.Get(self.var).SetValue("string")646 else:647 raise SystemError648class SetCharInstruction(Instruction):649 def __init__(self, xmlElement):650 attributes = self._GetAttributes(xmlElement, 3)651 self.var = self.GetAttributeValue(attributes[0], AttributeType.VAR)652 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)653 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)654 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):655 op1=Symbol.ExtractValue(self.sym1,SymTable,DataType.INT)656 op2=Symbol.ExtractValue(self.sym2,SymTable,DataType.STRING)657 varString=Symbol.ExtractValue(self.var,SymTable,DataType.STRING)658 if (len(varString)-1)<op1 or op1>(len(varString)-1):659 raise StringOperationException()660 if len(op2)==0:661 raise StringOperationException()662 charList=list(varString)663 charList[op1]=op2[0]664 SymTable.Get(self.var).SetValue("".join(charList))665class LabelInstruction(Instruction):666 def __init__(self, xmlElement):667 attributes = self._GetAttributes(xmlElement, 1)668 self.label = self.GetAttributeValue(attributes[0], AttributeType.LABEL)669 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):670 IP.RegisterLabel(self.label)671class JumpInstruction(Instruction):672 def __init__(self, xmlElement):673 attributes = self._GetAttributes(xmlElement, 1)674 self.label = self.GetAttributeValue(attributes[0], AttributeType.LABEL)675 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):676 IP.GoToLabel(self.label)677class JumpIfEqInstruction(Instruction):678 def __init__(self, xmlElement):679 attributes = self._GetAttributes(xmlElement, 3)680 self.label = self.GetAttributeValue(attributes[0], AttributeType.LABEL)681 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)682 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)683 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):684 op1=Symbol.ExtractValue(self.sym1,SymTable,None)685 op2=Symbol.ExtractValue(self.sym2,SymTable,None)686 687 if type(op1) is not type(op2):688 raise OperandTypeException()689 if op1==op2:690 IP.GoToLabel(self.label)691class JumpIfNotEqInstruction(Instruction):692 def __init__(self, xmlElement):693 attributes = self._GetAttributes(xmlElement, 3)694 self.label = self.GetAttributeValue(attributes[0], AttributeType.LABEL)695 self.sym1 = self.GetAttributeValue(attributes[1], AttributeType.SYMBOL)696 self.sym2 = self.GetAttributeValue(attributes[2], AttributeType.SYMBOL)697 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):698 op1=Symbol.ExtractValue(self.sym1,SymTable,None)699 op2=Symbol.ExtractValue(self.sym2,SymTable,None)700 if type(op1) is not type(op2):701 raise OperandTypeException()702 if op1!=op2:703 IP.GoToLabel(self.label)704class DPrintInstruction(Instruction):705 def __init__(self, xmlElement):706 attributes = self._GetAttributes(xmlElement, 1)707 self.sym = self.GetAttributeValue(attributes[0], AttributeType.SYMBOL)708 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):709 val=Symbol.ExtractValue(self.sym,SymTable,None)710 if val==None:711 val=""712 sys.stderr.write(val)713 sys.stderr.write("\n")714 715class BreakInstruction(Instruction):716 def __init__(self, xmlElement):717 self._GetAttributes(xmlElement, 0)718 def Execute(self,IP:InstuctionPoiner,SymTable:SymbolTable,Stack:list):719 sys.stderr.write("IP = " + str(IP.IP))720 sys.stderr.write("\n")721 722try: 723 argParser = argparse.ArgumentParser()724 argParser.add_argument("--source",nargs=1,required=True)725 try:726 args = argParser.parse_args()727 except SystemExit as ex:728 if ex.code==0:729 exit(0)730 else:731 raise ParameterException()732 733 parser = XmlParser()734 pathToXml = args.source[0]735 instructions = parser.Parse(pathToXml)736 737 instructionProcessor = InstructionProcessor(instructions)738 instructionProcessor.RegisterLabels()739 instructionProcessor.Execute()740except ParameterException:741 exit(10)742except InputFileException:743 exit(11)744except OutputFileException:745 exit(12)746except FormatException:747 exit(31)748except SyntaxError:749 exit(32)750except SemanticException:751 exit(52)752except OperandTypeException:753 exit(53)754except UndeclaredVarException:755 exit(54)756except FrameDoesNotExistException:757 exit(55)758except MissingValueException:759 exit(56)760except ZeroDivisionError:761 exit(57)762except StringOperationException:763 exit(58)764except SystemExit as ex:765 exit(ex.code)766except BaseException:...

Full Screen

Full Screen

web_product.py

Source:web_product.py Github

copy

Full Screen

...45 contents = etree.Element("contents")46 # Look for and add basemaps47 if not os.path.exists(os.path.join(directory, "FFM.geojson")):48 raise FileNotFoundError("Missing FFM geojson file.")49 file_attrib, format_attrib = self._getAttributes(50 "modelmaps", "Finite Fault Model Maps ", "FFM.geojson", "text/plain"51 )52 maps = etree.SubElement(contents, "file", file_attrib)53 grid_caption = etree.SubElement(maps, "caption")54 caption_str = "Map representation of the finite fault model "55 grid_caption.text = etree.CDATA(caption_str)56 etree.SubElement(maps, "format", format_attrib)57 basemap = self._checkDownload(directory, "*base*.png")58 kmls = self._checkDownload(directory, "*.kml")59 kmzs = self._checkDownload(directory, "*.kmz")60 if len(kmls) > 0:61 self._paths["kmls"] = (kmls[0], "finite_fault.kml")62 file_attrib, format_attrib = self._getAttributes(63 "", "", "finite_fault.kml", "application/vnd.google-earth.kml+xml"64 )65 etree.SubElement(maps, "format", format_attrib)66 if len(kmzs) > 0:67 self._paths["kmzs"] = (kmzs[0], "finite_fault.kmz")68 file_attrib, format_attrib = self._getAttributes(69 "", "", "finite_fault.kmz", "application/vnd.google-earth.kmz"70 )71 etree.SubElement(maps, "format", format_attrib)72 if len(basemap) > 0:73 self._paths["basemap"] = (basemap[0], "basemap.png")74 file_attrib, format_attrib = self._getAttributes(75 "basemap", "Base Map ", "basemap.png", "image/png"76 )77 etree.SubElement(maps, "format", format_attrib)78 # Look for data and model fits79 fits = self._checkDownload(directory, "fits.zip")80 zipped = ""81 if len(fits) == 0:82 zipped = self.zip_files(83 directory,84 [85 "*waves*.png",86 "*wave_*.png",87 "*_descending_fit.png",88 "*_ascending_fit.png",89 ],90 "fits",91 )92 if len(fits) > 0 or zipped != "":93 self._paths["fits"] = (os.path.join(directory, "fits.zip"), "fits.zip")94 file_attrib, format_attrib = self._getAttributes(95 "fits",96 "Data and Model Fits ",97 "fits.zip",98 "application/zip",99 )100 file_tree = etree.SubElement(contents, "file", file_attrib)101 caption = etree.SubElement(file_tree, "caption")102 caption.text = etree.CDATA(103 "Seismic and/or geodetic observations and model fits "104 )105 etree.SubElement(file_tree, "format", format_attrib)106 # CMT solution107 cmt = self._checkDownload(directory, "*CMTSOLUTION*")108 if len(cmt) > 0:109 self._paths["cmtsolution"] = (cmt[0], "CMTSOLUTION")110 file_attrib, format_attrib = self._getAttributes(111 "cmtsolution", "CMT Solution ", "CMTSOLUTION", "text/plain"112 )113 file_tree = etree.SubElement(contents, "file", file_attrib)114 caption = etree.SubElement(file_tree, "caption")115 caption.text = etree.CDATA(116 "Full CMT solution for every point in finite fault " "region "117 )118 etree.SubElement(file_tree, "format", format_attrib)119 # inversion files120 param = self._checkDownload(directory, "*.param")121 fsp = self._checkDownload(directory, "*.fsp")122 if len(fsp) > 0 or len(param) > 0:123 if len(param) > 0:124 self._paths["inpfile1"] = (param[0], "basic_inversion.param")125 file_attrib, format_attrib = self._getAttributes(126 "inpfiles",127 "Inversion Parameters ",128 "basic_inversion.param",129 "text/plain",130 )131 file_tree = etree.SubElement(contents, "file", file_attrib)132 caption = etree.SubElement(file_tree, "caption")133 caption.text = etree.CDATA(134 "Files of inversion parameters for the finite fault "135 )136 etree.SubElement(file_tree, "format", format_attrib)137 self._paths["inpfile2"] = (fsp[0], "complete_inversion.fsp")138 file_attrib, format_attrib = self._getAttributes(139 "inpfiles",140 "Inversion Parameters ",141 "complete_inversion.fsp",142 "text/plain",143 )144 etree.SubElement(file_tree, "format", format_attrib)145 else:146 self._paths["inpfile2"] = (fsp[0], "complete_inversion.fsp")147 file_attrib, format_attrib = self._getAttributes(148 "inpfiles",149 "Inversion Parameters ",150 "complete_inversion.fsp",151 "text/plain",152 )153 file_tree = etree.SubElement(contents, "file", file_attrib)154 caption = etree.SubElement(file_tree, "caption")155 caption.text = etree.CDATA(156 "Files of inversion parameters for the finite fault "157 )158 etree.SubElement(file_tree, "format", format_attrib)159 # Coulomb inp160 coul = self._checkDownload(directory, "*coulomb.inp")161 if len(coul) > 0:162 self._paths["coulomb"] = (coul[0], "coulomb.inp")163 file_attrib, format_attrib = self._getAttributes(164 "coulomb", "Coulomb Input File ", "coulomb.inp", "text/plain"165 )166 file_tree = etree.SubElement(contents, "file", file_attrib)167 caption = etree.SubElement(file_tree, "caption")168 caption.text = etree.CDATA(169 "Format necessary for compatibility with Coulomb3 "170 "(http://earthquake.usgs.gov/research/software/coulomb/) "171 )172 etree.SubElement(file_tree, "format", format_attrib)173 # Moment rate174 mr_plot = self._checkDownload(directory, "*mr*.png")175 mr_ascii = self._checkDownload(directory, "*.mr")176 if len(mr_ascii) > 0:177 self._paths["momentrate1"] = (mr_ascii[0], "moment_rate.mr")178 file_attrib, format_attrib = self._getAttributes(179 "momentrate",180 "Moment Rate Function Files ",181 "moment_rate.mr",182 "text/plain",183 )184 file_tree = etree.SubElement(contents, "file", file_attrib)185 caption = etree.SubElement(file_tree, "caption")186 caption.text = etree.CDATA(187 "Files of time vs. moment rate for source time " "functions "188 )189 etree.SubElement(file_tree, "format", format_attrib)190 self._paths["momentrate2"] = (mr_plot[0], "moment_rate.png")191 file_attrib, format_attrib = self._getAttributes(192 "momentrate",193 "Moment Rate Function Files ",194 "moment_rate.png",195 "image/png",196 )197 etree.SubElement(file_tree, "format", format_attrib)198 else:199 self._paths["momentrate2"] = (mr_plot[0], "moment_rate.png")200 file_attrib, format_attrib = self._getAttributes(201 "momentrate",202 "Moment Rate Function Files ",203 "moment_rate.png",204 "image/png",205 )206 file_tree = etree.SubElement(contents, "file", file_attrib)207 caption = etree.SubElement(file_tree, "caption")208 caption.text = etree.CDATA(209 "Files of time vs. moment rate for source time " "functions "210 )211 etree.SubElement(file_tree, "format", format_attrib)212 # surface displacement213 surf = self._checkDownload(directory, "*.disp")214 if len(surf) > 0:215 self._paths["deformation"] = (surf[0], "surface_deformation.disp")216 file_attrib, format_attrib = self._getAttributes(217 "surface",218 "Surface Deformation File ",219 "surface_deformation.disp",220 "text/plain",221 )222 file_tree = etree.SubElement(contents, "file", file_attrib)223 caption = etree.SubElement(file_tree, "caption")224 caption.text = etree.CDATA(225 "Surface displacement resulting from finite fault, "226 "calculated using Okada-style deformation codes "227 )228 etree.SubElement(file_tree, "format", format_attrib)229 # shakemap polygon230 poly = self._checkDownload(directory, "shakemap_polygon.txt")231 if len(poly) > 0:232 self._paths["shakemap_polygon"] = (poly[0], "shakemap_polygon.txt")233 file_attrib, format_attrib = self._getAttributes(234 "shakemap_polygon",235 "ShakeMap Rupture Polygon File ",236 "shakemap_polygon.txt",237 "text/plain",238 )239 file_tree = etree.SubElement(contents, "file", file_attrib)240 caption = etree.SubElement(file_tree, "caption")241 caption.text = etree.CDATA("Geometry of finite fault slipped area ")242 etree.SubElement(file_tree, "format", format_attrib)243 # look InSAR files244 insar_files = self._checkDownload(directory, "resampled_interferograms.zip")245 zipped = ""246 if len(insar_files) == 0:247 zipped = self.zip_files(248 directory,249 ["*ascending.txt", "*descending.txt"],250 "resampled_interferograms",251 )252 if len(insar_files) > 0 or zipped != "":253 self._paths["insar"] = (254 os.path.join(directory, "resampled_interferograms.zip"),255 "resampled_interferograms.zip",256 )257 file_attrib, format_attrib = self._getAttributes(258 "resampled_interferograms",259 "Resampled Interferogram ",260 "resampled_interferograms.zip",261 "application/zip",262 )263 file_tree = etree.SubElement(contents, "file", file_attrib)264 caption = etree.SubElement(file_tree, "caption")265 caption.text = etree.CDATA(266 "Resampled InSAR line-of-sight surface displacement observations "267 )268 etree.SubElement(file_tree, "format", format_attrib)269 tree = etree.ElementTree(contents)270 self._contents = tree271 return tree272 def createTimeseriesGeoJSON(self):273 """274 Create the timerseries geojson file.275 """276 station_points = []277 for key in self.timeseries_dict:278 props = {}279 props["station"] = key280 station = self.timeseries_dict[key]281 props["data"] = station["data"]282 props["metadata"] = station["data"]283 station_points += [284 {285 "type": "Feature",286 "properties": props,287 "geometry": {"type": "Point", "coordinates": []},288 }289 ]290 geo = {"type": "FeatureCollection", "features": station_points}291 self._timeseries_geojson = geo292 @property293 def event(self):294 """295 Helper to return event dictionary.296 Returns:297 dictionary: Event information.298 """299 return self._event300 @event.setter301 def event(self, event):302 """303 Helper to set event dictionary.304 event (dictionary): Event information.305 """306 self._event = event307 @property308 def grid(self):309 """310 Helper to return grid dictionary.311 Returns:312 dictionary: Grid information.313 """314 return self._grid315 @grid.setter316 def grid(self, grid):317 """318 Helper to set grid dictionary.319 grid (dictionary): Grid information.320 """321 self._grid = grid322 @classmethod323 def fromDirectory(324 cls,325 directory,326 eventsource,327 eventid,328 model_number,329 crustal_model=DEFAULT_MODEL,330 comment=None,331 version=1,332 suppress_model=False,333 ):334 """335 Create instance based upon a directory and eventid.336 Args:337 directory (string): Path to directory.338 eventid (string): Eventid used for file naming. Default is empty339 string.340 version (int): Product version number. Default is 1.341 Returns:342 WebProduct: Instance set for information for the web product.343 """344 product = cls()345 product._properties = {}346 wave_prop = os.path.join(directory, "wave_properties.json")347 if os.path.exists(wave_prop):348 with open(wave_prop, "r") as f:349 wave_dict = json.loads(f.read())350 if (351 "num_pwaves" not in wave_dict352 or "num_shwaves" not in wave_dict353 or "num_longwaves" not in wave_dict354 ):355 raise Exception(356 "Missing one of the required properties: "357 "num_pwaves, num_shwaves, num_longwaves."358 )359 else:360 product._properties["number-pwaves"] = wave_dict["num_pwaves"]361 product._properties["number-shwaves"] = wave_dict["num_shwaves"]362 product._properties["number-longwaves"] = wave_dict["num_longwaves"]363 provided = True364 else:365 provided = False366 unavailable, files = product._files_unavailable(367 directory, waves_provided=provided368 )369 file_strs = [f[0] + ": " + f[1] for f in files]370 if unavailable is True:371 raise Exception("Missing required files %r" % file_strs)372 try:373 with open(directory + "/analysis.txt", "r") as f:374 analysis = "".join(f.readlines())375 product.writeAnalysis(analysis, directory, eventid)376 except:377 analysis = "Not available yet."378 fsp_file = glob.glob(directory + "/" + "*.fsp")[0]379 fault = Fault.fromFiles(fsp_file, directory)380 product.event = fault.event381 product.segments = fault.segments382 fault.createGeoJSON()383 fault.corners["metadata"]["eventid"] = eventid384 product.grid = fault.corners385 product.solution = model_number386 product.crustal_model = crustal_model387 product._properties["version"] = version388 product.comment = comment389 product.suppress_model = suppress_model390 product._timeseries_dict = fault.timeseries_dict391 calculated_sizes = fault.segment_sizes392 product.writeGrid(directory)393 product.storeProperties(directory, eventsource, eventid, calculated_sizes)394 product.writeContents(directory)395 return product396 @property397 def paths(self):398 """399 Helper to return path dictionary.400 Returns:401 dictionary: Path information.402 """403 return self._paths404 @property405 def properties(self):406 """407 Helper to return properties dictionary.408 Returns:409 dictionary: Properties information.410 """411 return self._properties412 @property413 def segments(self):414 """415 Helper to return list of segments.416 Returns:417 list: List of segments (dict)418 """419 return self._segments420 @segments.setter421 def segments(self, segments):422 """423 Helper to set list of segments.424 segments (list): List of segments (dict)425 """426 self._segments = segments427 def storeProperties(428 self, directory, eventsource, eventsourcecode, calculated_sizes=None429 ):430 """431 Store PDL properties and creates properties.json.432 Args:433 directory (string): Path to directory.434 eventsource (string): Eventid source used for file naming.435 eventsourcecode (string): Eventid code used for file naming.436 calculated_sizes (dict): Dictionary of calculated sizes.437 """438 props = {}439 props["eventsourcecode"] = eventsourcecode440 props["eventsource"] = eventsource441 if os.path.exists(os.path.join(directory, "Readlp.das")):442 wave_file = os.path.join(directory, "Readlp.das")443 props["number-pwaves"], props["number-shwaves"] = self._countWaveforms(444 wave_file445 )446 if os.path.exists(os.path.join(directory, "synm.str_low")):447 try:448 with open(os.path.join(directory, "synm.str_low"), "rt") as f:449 props["number-longwaves"] = int(f.readline().strip())450 except:451 props["number-longwaves"] = 0452 elif not os.path.exists(os.path.join(directory, "wave_properties.json")):453 props["number-longwaves"] = 0454 URL_TEMPLATE = (455 "https://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/[EVENTID].geojson"456 )457 url = URL_TEMPLATE.replace("[EVENTID]", eventsource + eventsourcecode)458 try:459 fh = urlopen(url)460 data = fh.read()461 fh.close()462 jdict = json.loads(data.decode())463 locstr = jdict["properties"]["place"]464 except:465 locstr = "%.4f, %.4f" % (self.event["lat"], self.event["lon"])466 props["latitude"] = self.event["lat"]467 props["longitude"] = self.event["lon"]468 props["location"] = locstr469 props["derived-magnitude"] = self.event["mag"]470 props["scalar-moment"] = self.event["moment"]471 props["derived-magnitude-type"] = "Mw"472 props["depth"] = self.event["depth"]473 props["eventtime"] = self.event["date"]474 props["average-rise-time"] = self.event["avTr"]475 props["average-rupture-velocity"] = self.event["avVr"]476 props["hypocenter-x"] = float(self.event["Hypx"])477 props["hypocenter-z"] = float(self.event["Hypz"])478 props["maximum-frequency"] = float(self.event["Fmax"])479 props["minimum-frequency"] = float(self.event["Fmin"])480 props["model-dip"] = self.event["dip"]481 props["model-length"] = self.event["length"]482 props["model-rake"] = self.event["rake"]483 props["model-strike"] = self.event["strike"]484 props["model-top"] = self.event["htop"]485 props["model-width"] = self.event["width"]486 props["time-windows"] = int(self.event["time_windows"])487 props["velocity-function"] = self.event["velocity_func"]488 props["segments"] = len(self.segments)489 max_vals = {"slip": [], "depth": [], "rise": []}490 for i, segment in enumerate(self.segments):491 idx = str(i + 1)492 if calculated_sizes is not None:493 props["subfault-" + idx + "-width"] = calculated_sizes[i]["width"]494 props["subfault-" + idx + "-length"] = calculated_sizes[i]["length"]495 props["subfault-" + idx + "-area"] = calculated_sizes[i]["area"]496 props["segment-" + idx + "-strike"] = segment["strike"]497 props["segment-" + idx + "-dip"] = segment["dip"]498 slips = segment["slip"].flatten()499 depths = segment["depth"].flatten()500 rises = segment["rise"].flatten()501 max_vals["slip"] += [slips[np.argmax(slips)]]502 max_vals["depth"] += [depths[np.argmax(depths)]]503 max_vals["rise"] += [rises[np.argmax(rises)]]504 props["maximum-slip"] = max_vals["slip"][np.argmax(max_vals["slip"])]505 props["maximum-rise"] = max_vals["rise"][np.argmax(max_vals["rise"])]506 props["crustal-model"] = self.crustal_model507 if not self.suppress_model:508 props["model-number"] = self.solution509 if self.comment is not None:510 props["comment"] = self.comment511 if self.properties is None:512 self._properties = props513 else:514 copy_props = copy.deepcopy(self._properties)515 copy_props.update(props)516 self._properties = copy_props517 @property518 def timeseries_dict(self):519 """520 Helper to return time series dictionary.521 Returns:522 dictionary: Dictionary of time series for each station.523 """524 return self._timeseries_dict525 @property526 def timeseries_geojson(self):527 """528 Helper to return time series geojson.529 Returns:530 dictionary: geojson of time series for each station.531 """532 return self._timeseries_geojson533 @timeseries_dict.setter534 def timeseries_dict(self, timeseries_dict):535 """536 Helper to set time series dictionary.537 Args:538 timeseries_dictents (dictionary): Dictionary of time series for539 each station.540 """541 self._timeseries_dict = timeseries_dict542 def writeAnalysis(self, analysis, directory, eventid):543 """544 Write the analysis.html file.545 Args:546 analysis (str): Analysis string.547 directory (str): Path to directory where contents.xml will be548 written.549 """550 outfile = os.path.join(directory, "analysis.html")551 with open(outfile, "w") as analysis_file:552 analysis_file.write(analysis)553 if self.paths is None:554 self._paths = {}555 self._paths["analysis"] = (outfile, "analysis.html")556 def writeContents(self, directory):557 """558 Write the contents.xml file.559 Args:560 directory (str): Path to directory where contents.xml will be561 written.562 """563 tree = self.createContents(directory)564 outdir = os.path.join(directory, "contents.xml")565 tree.write(outdir, pretty_print=True, encoding="utf8")566 if self.paths is None:567 self._paths = {}568 self._paths["contents"] = (outdir, "contents.xml")569 # Add other files570 slip = self._checkDownload(directory, "*slip*.png")571 if len(slip) > 0:572 self._paths["slip"] = (slip[0], "slip.png")573 else:574 raise Exception("No slip image provided.")575 # Write property json for review576 prop_file = os.path.join(directory, "properties.json")577 serialized_prop = self._serialize(self.properties)578 with open(prop_file, "w") as f:579 json.dump(serialized_prop, f, indent=4, sort_keys=True)580 self._paths["properties"] = (prop_file, "properties.json")581 def writeGrid(self, directory):582 """583 Writes grid in a GeoJSON format.584 Args:585 directory (str): Directory where the file will be written.586 """587 if self.grid is None:588 raise Exception("The FFM grid dictionary has not been set.")589 write_path = os.path.join(directory, "FFM.geojson")590 with open(write_path, "w") as outfile:591 json.dump(self.grid, outfile, indent=4, sort_keys=True)592 if self.paths is None:593 self._paths = {}594 self._paths["geojson"] = (write_path, "FFM.geojson")595 def writeTimeseries(self, directory):596 """597 Writes time series in a JSON format.598 Args:599 directory (str): Directory where the file will be written.600 """601 if self.timeseries_geojson is None:602 raise Exception("The time series geojson has not been set.")603 write_path = os.path.join(directory, "timeseries.geojson")604 with open(write_path, "w") as outfile:605 json.dump(self.timeseries_dict, outfile, indent=4, sort_keys=True)606 def zip_files(self, directory, match, filename):607 """608 Zips up wave plot or insar files.609 Args:610 directory (str): Directory where the file will be written.611 Returns:612 string: path to directory if wave plots are found or '' if they613 are not.614 """615 files = []616 for m in match:617 files += glob.glob(os.path.join(directory, m))618 if len(files) > 0:619 path = os.path.join(directory, filename)620 if not os.path.exists(path):621 os.makedirs(path)622 for plot_path in files:623 base_file = os.path.basename(plot_path)624 new_file = os.path.join(path, base_file)625 shutil.copy(plot_path, new_file)626 shutil.make_archive(path, "zip", path)627 shutil.rmtree(path)628 print(path + ".zip")629 return path + ".zip"630 else:631 return ""632 def _checkDownload(self, directory, pattern):633 """634 Helper to check for a file and set download dictionary section.635 Args:636 directory (str): Path to directory.637 pattern (string): File patterns to check.638 """639 files = []640 # attempt to find file or use default641 file_paths = glob.glob(os.path.join(directory, pattern))642 if len(file_paths) > 0:643 file_path = file_paths[0]644 files += [file_path]645 return files646 def _countWaveforms(self, filename):647 """648 Count the number of wave forms.649 Args:650 filename (str): Path to wave file.651 """652 with open(filename, "rt") as f:653 lines = f.readlines()654 num_lines = int(lines[4].strip())655 ns = 0656 np = 0657 # read the int value of the 8th column of each line.658 # if greater than 2, increment ns, otherwise increment np659 for i in range(5, num_lines):660 parts = lines[i].split()661 if float(parts[8]) > 2:662 ns += 1663 else:664 np += 1665 return (np, ns)666 def _files_unavailable(self, directory, waves_provided=False):667 """668 Helper to check for required files.669 Args:670 directory (string): Path to directory of FFM data.671 waves_provided (bool): Values for wave numbers have been provided.672 """673 if waves_provided:674 required = {675 "Moment Rate PNG": "*mr*.png",676 "Base Map PNG": "*base*.png",677 "Slip PNG": "*slip*.png",678 "FSP File": "*.fsp",679 "Shakemap Polygon": "shakemap_polygon.txt",680 }681 else:682 required = {683 "Moment Rate PNG": "*mr*.png",684 "Base Map PNG": "*base*.png",685 "Slip PNG": "*slip*.png",686 "FSP File": "*.fsp",687 "Wave File": "Readlp.das",688 "Shakemap Polygon": "shakemap_polygon.txt",689 }690 unavailable = []691 for file_type in required:692 path = os.path.join(directory, required[file_type])693 if len(glob.glob(path)) < 1:694 unavailable += [(file_type, required[file_type])]695 if len(unavailable) > 0:696 return (True, unavailable)697 else:698 return (False, [])699 def _getAttributes(self, id, title, href, type):700 """701 Created contents attributes.702 Args:703 id (string): File id.704 title (string): File title.705 href (string): File name.706 type (string): File type707 """708 file_attrib = {"id": id, "title": title}709 format_attrib = {"href": href, "type": type}710 return file_attrib, format_attrib711 def _serialize(self, properties):712 """713 Helper function for making dictionary json serializable....

Full Screen

Full Screen

printer.py

Source:printer.py Github

copy

Full Screen

...16 print("\nrunning cmd:" + cmd)17 os.popen(cmd)18 print("\nprinting " + filename) 19 def getState(self):20 att = self._getAttributes()21 return PrinterState(att['printer-state'])22 23 def getErrorMessage(self):24 return self._getAttributes()['printer-state-message']25 26 def _getAttributes(self):...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pyatom automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful