def main(): OperandDescriptor = Assembler.OperandDescriptor desc = Assembler.InstructionDescriptor( 0x05, 'Call', (OperandDescriptor.UInt8, OperandDescriptor.UInt8)) desc.operands[0] print(desc) opr = Assembler.Operand() print(opr.descriptor.encoding) f = Assembler.Flags.StartBlock | Assembler.Flags.EndBlock print(f) inst = Assembler.Instruction() blk = Assembler.CodeBlock(None) tbl = Assembler.InstructionTable(None) blk.instructions[0] inst.branches[0] tbl.decriptors[0] print(f.isStartBlock) print(f.isEndBlock) console.pause('done')
def main(): file_name = sys.argv[1] assem = Assembler(file_name) machine_code = assem.get_machine_code() f = open(file_name+".asm", 'w') f.write(machine_code) f.close()
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hk:o:", ["help", "kernel-name", "output-file"]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) kid = "my_kernel" outfile = None for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-k", "--kernel-name"): kid = a if o in ("-o", "--output-file"): outfile = a if len(args) != 1: usage() sys.exit(2) infile = args[0] if outfile == None: stderr.write("No output file specified\n") sys.exit(2) i = open(infile, "r") asm = Assembler() try: asm.assemble(i) except CompilationError,e: stderr.write(str(e)+"\n") sys.exit(1)
def nextRound(self): if self.__game is not None: # print player's best assemblies humanBestAssembly = Assembler.Assembler.getBestAssembly( Assembler.Assembler( self.__game.getRound().getHuman().getHand()), Assembler.Assembler()) self.consoleLog("Human: " + humanBestAssembly.__str__()) computerBestAssembly = Assembler.Assembler.getBestAssembly( Assembler.Assembler( self.__game.getRound().getComputer().getHand()), Assembler.Assembler()) self.consoleLog("Computer: " + computerBestAssembly.__str__()) # remove assemblies from human's hand and add remaining cards score to running score self.__game.getRound().getHuman().setHand( humanBestAssembly.getRemainingCards()) self.__game.getRound().getHuman().addToScore( self.__game.getRound().getHuman().getPointsInHand()) self.consoleLog( "You earned " + self.__game.getRound().getHuman().getPointsInHand().__str__() + " points.") # do the same for computer self.__game.getRound().getComputer().setHand( computerBestAssembly.getRemainingCards()) self.__game.getRound().getComputer().addToScore( self.__game.getRound().getComputer().getPointsInHand()) self.consoleLog("The computer earned " + self.__game.getRound( ).getComputer().getPointsInHand().__str__() + " points.") self.updateBoard() # check if game should continue if self.__game.getRound().getRoundNumber() < self.__game.MAX_ROUND: # next round should be loaded self.consoleLog("Loading next round...") # player to go out begins next round humanStartsNextRound = self.__game.getRound().getHumanNext() self.__game.nextRound(humanStartsNextRound) self.btnMove["state"] = NORMAL self.btnNextRound["state"] = DISABLED self.updateBoard() else: # end of game - no more rounds self.consoleLog("That was the last round.") humanScore = self.__game.getRound().getHuman().getScore() computerScore = self.__game.getRound().getComputer().getScore() # print game winner if humanScore < computerScore: self.consoleLog("Congrats, you won the game!") elif computerScore < humanScore: self.consoleLog("The computer won. Better luck next time.") else: self.consoleLog("Amazing, it's a tie!") self.consoleLog("Please start or load a game.") else: self.consoleLog("Start a game before starting the next round.")
def Run(source: str, debug: bool): try: prog = Program(source) preproc = Preprocessor() preproc.preprocess(prog) # for l in prog.preprocessed: # print(l) assembler = Assembler() assembler.assemble(prog) # for l in prog.labels: # print(l, f" Position: {l.position}") # for i in prog.instructions: # print(i, f" Position: {i.position} Label: {i.labelName}") # for p in i.parameters: # print(" ", p, end = "") # if p.labelName != None: # print(f" {p.labelName}") # else: # print("") # for b in prog.binary: # print("%04X " % b, end = "") # print("") computer = Computer() computer.loadProgram(prog) if debug == False: computer.run() for l in prog.labels: if l.size > 0: print("%13s (%6s[%3d]): " % (l.name, l.datatype, l.size), end ="") for i in range(l.position, l.position + l.size): print("%d " % computer.memory[i], end = "") print("") else: debugger = Debugger(computer, prog) debugger.run() except PreprocessorError as e: print(e) except AssemblerError as e: print(e) except CompilerError as e: print(e) except Exception as e: raise e
def goOut(self): bestAss = Assembler.Assembler.getBestAssembly(Assembler.Assembler(self.__hand), Assembler.Assembler()) if len(bestAss.getRemainingCards()) == 0: # player can assemble all cards - remove hand self.clearHand() # return the best attempt at assembling return bestAss
def __init__(self): self.memory = Memory() self.loader = Loader(self.memory) self.assembler = Assembler() self.CI = 0 # 12 bits self.ACC = 0 # 8 bits self.output = []
def testLabels(): p = Parser.Program() p.AddLabel("loop") p.AddOperation(Assembler.AddressInstruction(56)) assert(p.table.HasSymbol("loop")) assert(p.table.GetSymbolValue("loop") == 0) p.AddOperation(Assembler.AddressInstruction("loop")) p.ReplaceSymbols() text = p.ToBinary() print(text)
def humanCanGoOut(self): bestAss = Assembler.Assembler.getBestAssembly( Assembler.Assembler(self.getRound().getHuman().getHand()), Assembler.Assembler()) if len(bestAss.getRemainingCards()) == 0: print("HUMAN SHOULD GO OUT: " + bestAss.__str__()) return True else: return False
def Parse(self, line): self.newAddress = None self.newTarget = None self.newCommand = None self.newJump = None self.newLabel = None parsed = self.oneline.parseString(line) if self.newAddress is not None: result = Assembler.AddressInstruction(self.newAddress) return result elif self.newCommand is not None: #print(self.newCommand.Expression) if self.newTarget is None: self.newTarget = Assembler.DestinationBits() if self.newJump is None: self.newJump = Assembler.JumpBits() result = Assembler.ControlInstruction(self.newCommand, self.newTarget, self.newJump) return result elif self.newTarget is not None: cmd = self.newTarget.ToPlainStr() self.newCommand = Assembler.InstructionBits(cmd) self.newTarget = Assembler.DestinationBits() if self.newJump is None: self.newJump = Assembler.JumpBits() result = Assembler.ControlInstruction(self.newCommand, self.newTarget, self.newJump) elif self.newLabel is not None: result = self.newLabel return result else: return None
def run(self): #Report start self.reportProgamStarted() #Load PSLG self.reportMeshLoadingStarted() self.pslg = FemIo.loadEle(self.eleFilename) self.parameters.initialize(self.pslg) self.reportMeshLoadingFinished() #Create shape functions self.reportBuildingShapeFunctionsStarted() slopeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(self.pslg) self.reportBuildingShapeFunctionsFinished() #Precompute matrices self.reportPrecomputingMatricesStarted() (G, A, BPrime) = Assembler.precomputeMatrices(slopeFunctions, self.parameters) self.reportPrecomputingMatricesFinished() #Solve self.reportSolvingStarted() Solver.Solve(self.pslg, slopeFunctions, self.parameters, G, A, BPrime, self.femFilename, self.releaseFilename) self.reportSolvingFinished() #Report finished self.reportProgamFinished()
def run(): print("start", sys.argv[0], "\n") asmfile = sys.argv[1] if not asmfile.find(".asm"): asmfile = asmfile + ".asm" hackfile = asmfile[:-4] + ".hack" pre_process = SymbolTable.SymbolTable(asmfile) while (True): if pre_process.process_line(): pass else: break table = pre_process.table print(table) pre_process.file.close() hack = open(hackfile, "w+") file = Parser.Parser(asmfile, table) more = file.hasMoreCommands() while more != '': com_type = file.commandType(more) assembler = Assembler.Assembler(more, com_type) destination, compare, jump, address = \ assembler.process_type(more, com_type, file) compute = compare + destination + jump assembler.write(compute, address, hack) more = file.hasMoreCommands() hack.seek(0, 0) print(hack.read()) hack.close() print("end")
def SolveInTime(slopeFunctions, parameters, MostOfLeftSide, PartOfRightSide, BPrime, zt, t): #Initialize the variables deltaT = parameters.deltaT alpha = parameters.releaseEfficiency #Report solving stared reportSolvingForTime(t + deltaT) #Calculate the iteration independent values prodT = Assembler.computeProductionVector(zt, slopeFunctions, parameters) LeftSide = MostOfLeftSide - (deltaT / 2.0) * alpha(t + deltaT) * BPrime MostOfRightSide = (PartOfRightSide + (deltaT / 2.0) * alpha(t) * BPrime) * zt + \ (deltaT / 2.0) * prodT #Set the initial value zPrev = scipy.zeros((parameters.n, 1)) for i in range(0, parameters.n): zPrev[i,0] = zt[i,0] #Iterate diff = 10000 epoch = 0 while diff >= parameters.maxDiff: zNew = SolveSingleStep(slopeFunctions, parameters, deltaT, LeftSide, MostOfRightSide, zPrev); diff = abs(zPrev - zNew).max() if (epoch + 1) % parameters.reportEpoch == 0: reportSolutionChange(epoch, diff) zPrev = zNew epoch += 1 #Return the result return zPrev
def OnDeleteLine(self, n): ans = idaapi.askyn_c( 1, "HIDECANCEL\nAre you sure you want to delete function [%s] @ [%s]?" % (self.items[n][3], self.items[n][4])) if ans == 1: asms = Assembler.LoadSavedAssemblers() item = int(self.items[n][2], 16) if asms != None and len(asms.keys()) > 0: for asm in asms.itervalues(): if asm.functions.has_key(item): print "Removed [%08x]!" % item del asm.functions[item] asm.SaveState() opty_ea = int(self.items[n][4], 16) print "set_name[%08x]" % opty_ea idc.MakeComm(opty_ea, "") idaapi.set_name(opty_ea, "") idc.DelFunction(opty_ea) comment = idc.Comment(item) comment = re.sub(r"(?i)OPTY@\[[\d+abcdef]+\];\s*", "", comment) idc.MakeComm(item, comment) self.populate_items() return n
def testComputeProductionVector3(self): #Define grid pslg = ElementAwarePslg.ElementAwarePslg() x1 = Pslg.GridPoint(0,-2) x2 = Pslg.GridPoint(-2,0) x3 = Pslg.GridPoint(0,0) x4 = Pslg.GridPoint(2,0) x5 = Pslg.GridPoint(0,2) x1.index = 0 x2.index = 1 x3.index = 2 x4.index = 3 x5.index = 4 x1.boundaryMarker = Parameters.Parameters.omegaDIdentifier x4.boundaryMarker = Parameters.Parameters.omegaDIdentifier x5.boundaryMarker = Parameters.Parameters.omegaDIdentifier s1 = Pslg.Segment(x1, x4) s2 = Pslg.Segment(x4, x5) s3 = Pslg.Segment(x5, x2) s4 = Pslg.Segment(x2, x1) s5 = Pslg.Segment(x1, x3) s6 = Pslg.Segment(x3, x5) s7 = Pslg.Segment(x2, x3) s8 = Pslg.Segment(x3, x4) e1 = ElementAwarePslg.Element(x2, x3, x5, Parameters.Parameters.omegaThreeIdentifier, 0) e2 = ElementAwarePslg.Element(x3, x4, x5, 0, 1) e3 = ElementAwarePslg.Element(x2, x1, x3, Parameters.Parameters.omegaThreeIdentifier, 2) e4 = ElementAwarePslg.Element(x3, x1, x4, 0, 3) pslg.points.extend([x1, x2, x3, x4, x5]) pslg.segments.extend([s1, s2, s3, s4, s5, s6, s7, s8]) pslg.elements.extend([e1, e2, e3, e4]) #Create the coefficient vector z = numpy.matrix([1.0/11.0, 15.0/44.0, 1.0/8.0, -1.0/11.0, 7.0/44.0]).transpose() #Create parameters parameters = Parameters.Parameters() parameters.initialize(pslg) #Tweak the parameters parameters.productionEffciency = lambda x,y: 1.0 parameters.productionThreshold = 1.0 #Get shape functions shapeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(pslg) #Get the matrices P = Assembler.computeProductionVector(z, shapeFunctions, parameters) #Test values expected = numpy.matrix([295.0/528.0, 45.0/44.0, 289.0/264.0, 0, 283.0/528.0]).transpose() self.assertTrue((abs(P - expected) < 1E-10).all()) return
def SolveInTime(slopeFunctions, parameters, MostOfLeftSide, PartOfRightSide, BPrime, zt, t): #Initialize the variables deltaT = parameters.deltaT alpha = parameters.releaseEfficiency #Report solving stared reportSolvingForTime(t + deltaT) #Calculate the iteration independent values prodT = Assembler.computeProductionVector(zt, slopeFunctions, parameters) LeftSide = MostOfLeftSide - (deltaT / 2.0) * alpha(t + deltaT) * BPrime MostOfRightSide = (PartOfRightSide + (deltaT / 2.0) * alpha(t) * BPrime) * zt + \ (deltaT / 2.0) * prodT #Set the initial value zPrev = scipy.zeros((parameters.n, 1)) for i in range(0, parameters.n): zPrev[i, 0] = zt[i, 0] #Iterate diff = 10000 epoch = 0 while diff >= parameters.maxDiff: zNew = SolveSingleStep(slopeFunctions, parameters, deltaT, LeftSide, MostOfRightSide, zPrev) diff = abs(zPrev - zNew).max() if (epoch + 1) % parameters.reportEpoch == 0: reportSolutionChange(epoch, diff) zPrev = zNew epoch += 1 #Return the result return zPrev
def GotTarget(self, trg): self.newTarget = trg[0] #print(trg) if self.newTarget not in Tables.dest_table: raise Exception("wrong target expression") self.newTarget = Assembler.DestinationBits("A" in trg[0], "D" in trg[0], "M" in trg[0])
def testComputeProductionVector1(self): #Define grid pslg = ElementAwarePslg.ElementAwarePslg() x1 = Pslg.GridPoint(0,-2) x2 = Pslg.GridPoint(0,0) x3 = Pslg.GridPoint(0,2) x4 = Pslg.GridPoint(-2,0) x5 = Pslg.GridPoint(2,0) x1.index = 0 x2.index = 1 x3.index = 2 x4.index = 3 x5.index = 4 s1 = Pslg.Segment(x1, x5) s2 = Pslg.Segment(x5, x3) s3 = Pslg.Segment(x3, x4) s4 = Pslg.Segment(x4, x1) s5 = Pslg.Segment(x4, x2) s6 = Pslg.Segment(x2, x5) s7 = Pslg.Segment(x3, x2) s8 = Pslg.Segment(x2, x1) e1 = ElementAwarePslg.Element(x1, x2, x4, 0, 0) e2 = ElementAwarePslg.Element(x1, x2, x5, Parameters.Parameters.omegaThreeIdentifier, 1) e3 = ElementAwarePslg.Element(x4, x2, x3, 0, 2) e4 = ElementAwarePslg.Element(x3, x2, x5, Parameters.Parameters.omegaThreeIdentifier, 3) pslg.points.extend([x1, x2, x3, x4, x5]) pslg.segments.extend([s1, s2, s3, s4, s5, s6, s7, s8]) pslg.elements.extend([e1, e2, e3, e4]) #Create the coefficient vector z = numpy.matrix([1, 1, -1, 100, 1]).transpose() #Create parameters parameters = Parameters.Parameters() parameters.initialize(pslg) #Tweak the parameters parameters.productionEffciency = lambda x,y: 1.0 parameters.productionThreshold = 1.0 #Get shape functions shapeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(pslg) #Get the matrices P = Assembler.computeProductionVector(z, shapeFunctions, parameters) #Test symetry self.assertAlmostEqual(P[0,0], 0, 9) self.assertAlmostEqual(P[1,0], 1.0/3.0, 9) self.assertAlmostEqual(P[2,0], 2.0/3.0, 9) self.assertAlmostEqual(P[3,0], 0, 9) self.assertAlmostEqual(P[4,0], 1.0/3.0, 9) return
def optimice(): ea = idc.ScreenEA() print "Starting optimization @ [%08x]" % ea f = Function.Function(ea) cfg = CFGOptimization.ReduceJMP(f) peep = CodeOptimization.PeepHole(f) dead = CodeOptimization.DeadCodeElimination(f) modified = True while modified: modified = False f.AssertCFGStructure() modified |= cfg.Reduce() modified |= cfg.JccReduce() modified |= cfg.JccReduceComplementary() modified |= peep.OptimizeFunction() modified |= dead.OptimizeFunction() f.CleanUp() #f.PrintBlocks() f.CleanUp() f.AssertCFGStructure() #f.PrintBlocks() asms = Assembler.LoadSavedAssemblers() if asms != None and len(asms.keys()) > 1: print "Ask user to choose one!" elif asms != None and len(asms.keys()) == 1: asm = asms.values()[0] else: asm = Assembler.Assemble() asm.Assemble(f) asm.SaveState() print "Optimization ended!"
def __init__(self, lineStr, address=-1): super(Instruction, self).__init__(size=1, startAddress=address, lineStr=lineStr) asmLine = lineStr.split('//')[0].strip() regex = re.compile(r"[,\s()=\[|\]]+") args = [arg for arg in (re.split(regex, asmLine)) if arg != ""] for x in args: if re.search(r'[^\w\d.\-]', x): raise Exception('Invalid character encountered:', asmLine) self.asmLine = asmLine self.type = self.getType() self.args = Instruction.__splitLine__(lineStr) self.op = self.args[0] self.rd: str self.ra: str self.rb: str self.rc: str # decode fields self.opcode: int self.func: int self.rdi: int self.rai: int self.rbi: int self.rci: int = 0 self.imm: int self.p: int self.x: int self.s: int self.n: int self.imm_L: int self.imm_R: int self.offset: int self.operands: list # list of operands Assembler.decodeInstruction(self)
def __test_execute(self,source = ''): if len(source) != 0: program = Assembler(Lexer(source).lex()).assemble() vObj = VM(program) vObj.run() return vObj else: raise Exception('SOURCE CANNOT BE EMPTY DURING TEST EXCEUTE')
def test(): print(ED6FC.ScenaOpTable) print() dis = Assembler.Disassembler(ED6FC.ScenaOpTable) fs = fileio.FileStream() fs.OpenMemory(open('tests\\T2610_1 ._SN', 'rb').read()) fs.Position = 0x64 info = Assembler.DisassembleInfo(fs) fun = dis.disasmFunction(info) fun.name = 'test' print('\n'.join(dis.formatFuncion(fun)))
def SolveSingleStep(slopeFunctions, parameters, deltaT, LeftSide, MostOfRightSide, zPrev): prodPrev = Assembler.computeProductionVector(zPrev, slopeFunctions, parameters) RightSide = (deltaT / 2.0) * prodPrev + MostOfRightSide zNew = scipy.sparse.linalg.bicgstab(LeftSide, RightSide, zPrev, parameters.maxIterativeDiff)[0] zNew = scipy.matrix(zNew).transpose() return zNew
def __execute(self,paths = []): if len(paths) != 0: for path in paths: print('Executing file: {}'.format(path)) source = file_get_contents(path) program = Assembler(Lexer(source).lex()).assemble() vObj = VM(program) vObj.run() print()
def test__assembleC__(self): fileName = 'add/Add.asm' assembler = Assembler(fileName) command = 'D=D+A' expected = '1110000010010000' result = assembler.__assembleC__(command) self.assertTrue(result == expected) command = 'M=D' expected = '1110001100001000' result = assembler.__assembleC__(command) self.assertTrue(result == expected) command = '0;JMP' expected = '1110101010000111' result = assembler.__assembleC__(command) self.assertTrue(result == expected)
def test__output__(self): fileName = 'add/Add.asm' assembler = Assembler(fileName) outputName = assembler.assemble() self.assertTrue(outputName == 'add/Add.hack') insts = [ '0000000000000010', '1110110000010000', '0000000000000011', '1110000010010000', '0000000000000000', '1110001100001000' ] parsedList = [] file = open('add/Add.hack', "r") for line in file: parsedList.append(line.strip()) file.close() self.assertTrue(parsedList == insts)
def test__init__(self): self.assertRaises(RuntimeError, Assembler, '.asm') fileName = 'add/Add.asm' assembler = Assembler(fileName) self.assertTrue(assembler.inputFileName == 'add/Add.asm') self.assertTrue(assembler.outputFileName == 'add/Add.hack') self.assertTrue(assembler.code) self.assertTrue(assembler.st)
def build_text_files(listing, hash_manager, verbose=False): has_emitted = [] print("Assembling...") # Lines are already stripped, with comments and empty lines removed for entry in listing: archive_name = entry[0].split('/')[0] object_name = entry[0].split('/')[1] if archive_name not in has_emitted: has_emitted.append(archive_name) print(archive_name, end=", ") require_dir("./build/") # Output file. Base 26 for smallest path. dest = fmt_gath(entry[1]) dest_path = os.path.join('./build/', dest) if verbose: print("entry: " + str(entry)) if hash_manager.check(entry[0], ".\\asm\\"): if verbose: print("Hashed! Skipping %s %s" % entry) else: assembler = Assembler.Assembler() assembler.assemble('./asm/%s' % entry[0], dest_path, True) # TODO: Validate success, and potentially hash options hash_manager.save(entry[0], ".\\asm\\") print(dest_path) patches = postprocess_elf(open(dest_path, 'rb')) source_bytes = list(open(dest_path, 'rb').read()) for patch in patches[0]: assert len(patch.dest) <= patch.src_size for j in range(patch.src_size): if j >= len(patch.dest): c = 0 else: c = ord(patch.dest[j]) source_bytes[patch.position + j] = c # Patch ctor align nP = 0 for p in patches[1]: source_bytes[p + 0] = 0 source_bytes[p + 1] = 0 source_bytes[p + 2] = 0 source_bytes[p + 3] = 4 nP += 1 if nP > 1: print("Patched ctors + dtors") with open(dest_path, 'wb') as file: file.write(bytes(source_bytes))
def test__firstPass__(self): #test that we can handle a simple file fileName = 'add/Add.asm' assembler = Assembler(fileName) addList = ['@2', 'D=A', '@3', 'D=D+A', '@0', 'M=D'] assembler.__firstPass__() self.assertTrue(assembler.parser.toParse == addList) #test that we can handle a more complex file including deleting appropriate stuff fileName = 'rect/RectL.asm' assembler = Assembler(fileName) expected = [ '@0', 'D=M', '@23', 'D;JLE', '@16', 'M=D', '@16384', 'D=A', '@17', 'M=D', '@17', 'A=M', 'M=-1', '@17', 'D=M', '@32', 'D=D+A', '@17', 'M=D', '@16', 'MD=M-1', '@10', 'D;JGT', '@23', '0;JMP' ] assembler.__firstPass__() self.assertTrue(assembler.parser.toParse == expected)
def GotJump(self, jmp): self.newJump = jmp[0] #print(jmp) if self.newJump not in Tables.jump_table: raise Exception("wrong jump expression") self.newJump = Assembler.JumpBits() if "G" in jmp[0]: self.newJump.AddJ3() if "E" in jmp[0]: self.newJump.AddJ2() if "N" in jmp[0]: self.newJump.RemoveJ2() if "L" in jmp[0]: self.newJump.AddJ1() if "P" in jmp[0]: self.newJump.AddJ1() self.newJump.AddJ2() self.newJump.AddJ3()
def populate_items(self): asms = Assembler.LoadSavedAssemblers() lst = [] if asms != None and len(asms.keys()) > 0: for asm in asms.itervalues(): for key in asm.functions.iterkeys(): lst.append([ "%08x" % asm.segment_start, idc.GetFunctionName(key), "%08x" % key, idc.GetFunctionName(asm.functions[key][0]), "%08x" % asm.functions[key][0] ]) del asms self.items = lst return self.items
def main(): askForFile = True while (askForFile): try: fileName = input("Please enter file name to read: ") asmFile = open(fileName, 'r') askForFile = False FileParser = Parser.Parser(asmFile) #close file asmFile.close() #list of commands to be interpreted rawCommands = FileParser.getContents HackAssembler = Assembler.Assembler(rawCommands, fileName) HackAssembler.addUserSymbols() HackAssembler.translate() HackAssembler.outputFile() except: print("Error, no such file")
def gen_m(config): num = config['TOTAL_NUM'] features = pre_process_config(config['FEATURES']) # print(features) theta1_list = gen_theta(features['theta1'],num) theta2_list = gen_theta(features['theta2'],num) theta3_list = gen_theta(features['theta3'],num) theta4_list = gen_theta(features['theta4'],num) theta5_list = gen_theta(features['theta5'],num) theta6_list = gen_theta(features['theta6'],num) theta7_list = gen_theta(features['theta7'],num) theta8_list = gen_theta(features['theta8'],num) theta9_list = gen_theta(features['theta9'],num) k1_list = gen_theta(features['k1'],num) k2_list = gen_theta(features['k2'],num) season_list = [] noise_list = [] trend_list = [] for i in range(0,num): noise_generator = ng.NoiseGeneratorFactory().get_generator(None) trend_generator = tg.TrendGenerator() season_generator = sg.SeasonGeneratorFactory(theta5_list[i],theta3_list[i],theta4_list[i],k1_list[i],k2_list[i],forking_depth=7).get_generator(None) season = season_generator.gen_season() noise = noise_generator.gen(theta6_list[i],theta7_list[i],theta8_list[i],theta9_list[i],len(season[0])) trend = trend_generator.gen(theta1_list[i],theta2_list[i],len(season[0])) season_list.append(season) noise_list.append(noise) trend_list.append(trend) # print(noise[1].shape,trend[1].shape,season[1].shape) # print(noise[0].shape,trend[0].shape,season[0].shape) print(noise) print(trend) print(season) assembler = assem.AbstractAssembler(season_list,noise_list,trend_list) assembler.assemble() assembler.save(path=out_path)
def SolveSingleStep(slopeFunctions, parameters, deltaT, LeftSide, MostOfRightSide, zPrev): prodPrev = Assembler.computeProductionVector(zPrev, slopeFunctions, parameters) RightSide = (deltaT / 2.0) * prodPrev + MostOfRightSide zNew = scipy.sparse.linalg.bicgstab(LeftSide, RightSide, zPrev, parameters.maxIterativeDiff)[0] zNew = scipy.matrix(zNew).transpose() return zNew;
def testSolveSingleStep1(self): #Define grid pslg = ElementAwarePslg.ElementAwarePslg() x1 = Pslg.GridPoint(0,-2) x2 = Pslg.GridPoint(-2,0) x3 = Pslg.GridPoint(0,0) x4 = Pslg.GridPoint(2,0) x5 = Pslg.GridPoint(0,2) x1.index = 0 x2.index = 1 x3.index = 2 x4.index = 3 x5.index = 4 x1.boundaryMarker = Parameters.Parameters.omegaDIdentifier x4.boundaryMarker = Parameters.Parameters.omegaDIdentifier x5.boundaryMarker = Parameters.Parameters.omegaDIdentifier s1 = Pslg.Segment(x1, x4) s2 = Pslg.Segment(x4, x5) s3 = Pslg.Segment(x5, x2) s4 = Pslg.Segment(x2, x1) s5 = Pslg.Segment(x1, x3) s6 = Pslg.Segment(x3, x5) s7 = Pslg.Segment(x2, x3) s8 = Pslg.Segment(x3, x4) e1 = ElementAwarePslg.Element(x2, x3, x5, Parameters.Parameters.omegaThreeIdentifier, 0) e2 = ElementAwarePslg.Element(x3, x4, x5, 0, 1) e3 = ElementAwarePslg.Element(x2, x1, x3, Parameters.Parameters.omegaThreeIdentifier, 2) e4 = ElementAwarePslg.Element(x3, x1, x4, 0, 3) pslg.points.extend([x1, x2, x3, x4, x5]) pslg.segments.extend([s1, s2, s3, s4, s5, s6, s7, s8]) pslg.elements.extend([e1, e2, e3, e4]) #Create the coefficient vector zOriginal = numpy.matrix([0, 0, 0, 0, 0]).transpose() zPrev = numpy.matrix([0, 0, 0, 0, 0]).transpose() #Create parameters parameters = Parameters.Parameters() parameters.initialize(pslg) #Tweak the parameters parameters.diffusionTensor = [[lambda x, y: 1.0, lambda x, y: 1.0], [lambda x, y: 1.0, lambda x, y: 1.0]] parameters.productionEffciency = lambda x,y: 1.0 parameters.productionThreshold = 1.0 parameters.releaseEfficiency = lambda t: 0.0 parameters.initialDensity = lambda x,y: 0.0 #Get shape functions shapeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(pslg) #Get the matrices (G, A, BPrime) = Assembler.precomputeMatrices(shapeFunctions, parameters) P = Assembler.computeProductionVector(zOriginal, shapeFunctions, parameters) #Set time parameters.deltaT = 0.01 parameters.tEnd = 1.0 t = 0 #Compute parts of equation LeftSide = G - parameters.deltaT / 2.0 * (A + parameters.releaseEfficiency(t + parameters.deltaT) * BPrime) MostOfRightSide = (G + parameters.deltaT / 2.0 * (A + parameters.releaseEfficiency(t) * BPrime)) * zOriginal + parameters.deltaT / 2.0 * P #Perform test zNew = Solver.SolveSingleStep(shapeFunctions, parameters, parameters.deltaT, LeftSide, MostOfRightSide, zPrev) #Test values expected = numpy.matrix([1.0/11.0, 15.0/44.0, 1.0/8.0, -1.0/11.0, 7.0/44.0]).transpose() self.assertTrue((abs(zNew - expected) < 1E-10).all())
def testAMatrix1(self): #Define grid pslg = ElementAwarePslg.ElementAwarePslg() p1 = Pslg.GridPoint(0,0) p2 = Pslg.GridPoint(1,1) p3 = Pslg.GridPoint(2,2) p4 = Pslg.GridPoint(0,2) p5 = Pslg.GridPoint(2,0) p1.index = 0 p2.index = 1 p3.index = 2 p4.index = 3 p5.index = 4 e1 = ElementAwarePslg.Element(p4, p2, p1, 1, 0) e2 = ElementAwarePslg.Element(p4, p2, p3, 2, 1) e3 = ElementAwarePslg.Element(p2, p5, p3, 3, 2) e4 = ElementAwarePslg.Element(p1, p2, p5, 4, 3) pslg.points.extend([p1, p2, p3, p4, p5]) pslg.elements.extend([e1, e2, e3, e4]) #Create parameters parameters = Parameters.Parameters() parameters.initialize(pslg) parameters.diffusionTensor = [[lambda x,y: 2, lambda x,y: 3], [lambda x,y: 5, lambda x,y: 7]] #Get shape functions shapeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(pslg) #Get the matrices (G, A, BPrime) = Assembler.precomputeMatrices(shapeFunctions, parameters) self.assertAlmostEqual(A[0,0], -17.0/2.0, 9) self.assertAlmostEqual(A[0,1], 17.0/2.0, 9) self.assertAlmostEqual(A[0,2], 0, 9) self.assertAlmostEqual(A[0,3], 3.0/4.0, 9) self.assertAlmostEqual(A[0,4], -3.0/4.0, 9) self.assertAlmostEqual(A[1,0], 17.0/2.0, 9) self.assertAlmostEqual(A[1,1], -18, 9) self.assertAlmostEqual(A[1,2], 17.0/2.0, 9) self.assertAlmostEqual(A[1,3], 0.5, 9) self.assertAlmostEqual(A[1,4], 0.5, 9) self.assertAlmostEqual(A[2,0], 0, 9) self.assertAlmostEqual(A[2,1], 17.0/2.0, 9) self.assertAlmostEqual(A[2,2], -17.0/2.0, 9) self.assertAlmostEqual(A[2,3], -3.0/4.0, 9) self.assertAlmostEqual(A[2,4], 3.0/4.0, 9) self.assertAlmostEqual(A[3,0], 7.0/4.0, 9) self.assertAlmostEqual(A[3,1], 0.5, 9) self.assertAlmostEqual(A[3,2], -7.0/4.0, 9) self.assertAlmostEqual(A[3,3], -1.0/2.0, 9) self.assertAlmostEqual(A[3,4], 0, 9) self.assertAlmostEqual(A[4,0], -7.0/4.0, 9) self.assertAlmostEqual(A[4,1], 0.5, 9) self.assertAlmostEqual(A[4,2], 7.0/4.0, 9) self.assertAlmostEqual(A[4,3], 0, 9) self.assertAlmostEqual(A[4,4], -1.0/2.0, 9) return
# 'test2_flip', # 'test3_add', # 'test4_gt0', # 'test5_array', # 'test5a_array', # 'test6_mult', # 'test8_fill', # 'test8a_fill', # 'test9_rect', # 'test9a_rect', # 'test9d_rect', # 'test10_pong', # 'test11_xor', # 'test12_shiftLeft', # 'test12a_shiftLeft', # 'test13_shiftRight', # 'test13a_shiftRight', # 'demo_eo6', # 'demo_eo6_color', ] subdir = 'Tests/Chapter_6_assembly/' # subdir = 'Demos/' for file in files: # print(file) input = subdir + file + '.hasm' output = subdir + 'bin/' + file + '.bin' Assembler.asm_to_bin( input, output )
def testGMatrix2(self): #Define grid pslg = ElementAwarePslg.ElementAwarePslg() x1 = Pslg.GridPoint(0,-2) x2 = Pslg.GridPoint(-2,0) x3 = Pslg.GridPoint(0,0) x4 = Pslg.GridPoint(2,0) x5 = Pslg.GridPoint(0,2) x1.index = 0 x2.index = 1 x3.index = 2 x4.index = 3 x5.index = 4 x1.boundaryMarker = Parameters.Parameters.omegaDIdentifier x4.boundaryMarker = Parameters.Parameters.omegaDIdentifier x5.boundaryMarker = Parameters.Parameters.omegaDIdentifier s1 = Pslg.Segment(x1, x4) s2 = Pslg.Segment(x4, x5) s3 = Pslg.Segment(x5, x2) s4 = Pslg.Segment(x2, x1) s5 = Pslg.Segment(x1, x3) s6 = Pslg.Segment(x3, x5) s7 = Pslg.Segment(x2, x3) s8 = Pslg.Segment(x3, x4) e1 = ElementAwarePslg.Element(x2, x3, x5, Parameters.Parameters.omegaThreeIdentifier, 0) e2 = ElementAwarePslg.Element(x3, x4, x5, 0, 1) e3 = ElementAwarePslg.Element(x2, x1, x3, Parameters.Parameters.omegaThreeIdentifier, 2) e4 = ElementAwarePslg.Element(x3, x1, x4, 0, 3) pslg.points.extend([x1, x2, x3, x4, x5]) pslg.segments.extend([s1, s2, s3, s4, s5, s6, s7, s8]) pslg.elements.extend([e1, e2, e3, e4]) #Create parameters parameters = Parameters.Parameters() parameters.initialize(pslg) #Get shape functions shapeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(pslg) #Get the matrices (G, A, BPrime) = Assembler.precomputeMatrices(shapeFunctions, parameters) #Test symetry for i in range(0, len(pslg.points)): for j in range(0, len(pslg.points)): self.assertAlmostEqual(G[i,j], G[j,i], 9) #Test values self.assertAlmostEqual(G[0,0], 4.0/3.0, 9) self.assertAlmostEqual(G[0,1], 0.0, 9) self.assertAlmostEqual(G[0,2], 0.0, 9) self.assertAlmostEqual(G[0,3], 0.0, 9) self.assertAlmostEqual(G[0,4], 0.0, 9) self.assertAlmostEqual(G[1,0], 0.0, 9) self.assertAlmostEqual(G[1,1], 4.0/3.0, 9) self.assertAlmostEqual(G[1,2], 0.0, 9) self.assertAlmostEqual(G[1,3], 0.0, 9) self.assertAlmostEqual(G[1,4], 0.0, 9) self.assertAlmostEqual(G[2,0], 0.0, 9) self.assertAlmostEqual(G[2,1], 0.0, 9) self.assertAlmostEqual(G[2,2], 8.0/3.0, 9) self.assertAlmostEqual(G[2,3], 0.0, 9) self.assertAlmostEqual(G[2,4], 0.0, 9) self.assertAlmostEqual(G[3,0], 0.0, 9) self.assertAlmostEqual(G[3,1], 0.0, 9) self.assertAlmostEqual(G[3,2], 0.0, 9) self.assertAlmostEqual(G[3,3], 4.0/3.0, 9) self.assertAlmostEqual(G[3,4], 0.0, 9) self.assertAlmostEqual(G[4,0], 0.0, 9) self.assertAlmostEqual(G[4,1], 0.0, 9) self.assertAlmostEqual(G[4,2], 0.0, 9) self.assertAlmostEqual(G[4,3], 0.0, 9) self.assertAlmostEqual(G[4,4], 4.0/3.0, 9) return
# ## Modules ## import sys import os #checking if module exists, is executable and can be imported if not os.path.exists("./Assembler.py"): print "Error: Assembler does not exist"; sys.exit(1) elif not os.access("./Assembler.py", os.X_OK): print "Error: Assembler is not executable"; sys.exit(1) try: from Assembler import * except: print "Error: Unable to import Assembler.py"; sys.exit(1) if not os.path.exists("./code_1.txt"): print "Error: code_1.txt does not exist, must add a readable sample assembly file named code_1.txt for this program to function"; sys.exit(6) #Testing Assembler Class Creation try: test = Assembler("code_1.txt") except: print "Error: Unable to create Assembler object"; sys.exit(2) #Testing parseInstruction Function try: integer = test.parseInstruction('lw $t7,!1000') except: print "Error: Unable to execute parseInstruction function"; sys.exit(3) if(integer != 125730816): print "Error: parseInstruction function has incorrect output with test lw $t7,!1000. Function output was %d, should be 125730816" % (integer); sys.exit(4) try: integer = test.parseInstruction('sub $t4,$t3,1') except: print "Error: Unable to execute parseInstruction function"; sys.exit(3) if(integer != 469776385): print "Error: parseInstruction function has incorrect output with test sub $t4,$t3,1. Function output was %d, should be 469776385" % (integer); sys.exit(5)
def testGMatrix1(self): #Define grid pslg = ElementAwarePslg.ElementAwarePslg() p1 = Pslg.GridPoint(0,0) p2 = Pslg.GridPoint(1,1) p3 = Pslg.GridPoint(2,2) p4 = Pslg.GridPoint(0,2) p5 = Pslg.GridPoint(2,0) p1.index = 0 p2.index = 1 p3.index = 2 p4.index = 3 p5.index = 4 e1 = ElementAwarePslg.Element(p4, p2, p1, Parameters.Parameters.omegaThreeIdentifier, 0) e2 = ElementAwarePslg.Element(p4, p2, p3, Parameters.Parameters.omegaThreeIdentifier, 1) e3 = ElementAwarePslg.Element(p2, p5, p3, 0, 2) e4 = ElementAwarePslg.Element(p1, p2, p5, 0, 3) pslg.points.extend([p1, p2, p3, p4, p5]) pslg.elements.extend([e1, e2, e3, e4]) #Create parameters parameters = Parameters.Parameters() parameters.initialize(pslg) #Get shape functions shapeFunctions = ShapeFunctions.buildShapeFunctionsForPslg(pslg) #Get the matrices (G, A, BPrime) = Assembler.precomputeMatrices(shapeFunctions, parameters) #Test symetry for i in range(0, len(pslg.points)): for j in range(0, len(pslg.points)): self.assertAlmostEqual(G[i,j], G[j,i], 9) #Test values self.assertAlmostEqual(G[0,0], 2.0/3.0, 9) self.assertAlmostEqual(G[0,1], 0.0, 9) self.assertAlmostEqual(G[0,2], 0.0, 9) self.assertAlmostEqual(G[0,3], 0.0, 9) self.assertAlmostEqual(G[0,4], 0.0, 9) self.assertAlmostEqual(G[1,0], 0.0, 9) self.assertAlmostEqual(G[1,1], 4.0/3.0, 9) self.assertAlmostEqual(G[1,2], 0.0, 9) self.assertAlmostEqual(G[1,3], 0.0, 9) self.assertAlmostEqual(G[1,4], 0.0, 9) self.assertAlmostEqual(G[2,0], 0.0, 9) self.assertAlmostEqual(G[2,1], 0.0, 9) self.assertAlmostEqual(G[2,2], 2.0/3.0, 9) self.assertAlmostEqual(G[2,3], 0.0, 9) self.assertAlmostEqual(G[2,4], 0.0, 9) self.assertAlmostEqual(G[3,0], 0.0, 9) self.assertAlmostEqual(G[3,1], 0.0, 9) self.assertAlmostEqual(G[3,2], 0.0, 9) self.assertAlmostEqual(G[3,3], 2.0/3.0, 9) self.assertAlmostEqual(G[3,4], 0.0, 9) self.assertAlmostEqual(G[4,0], 0.0, 9) self.assertAlmostEqual(G[4,1], 0.0, 9) self.assertAlmostEqual(G[4,2], 0.0, 9) self.assertAlmostEqual(G[4,3], 0.0, 9) self.assertAlmostEqual(G[4,4], 2.0/3.0, 9) return
def setUp(self): self.asm = Assembler.hackAssembler()