def __init__(self, **options): super(Procedural, self).__init__(**options) keys = {"q": self.kill, "i": self.__zoomIn, "o": self.__zoomOut} self.bindKeys(**keys) self._ui.state("zoomed") self._ui.grid_rowconfigure(0, weight=1) self._ui.grid_columnconfigure(0, weight=1) self.__frame = tk.Frame(self._ui, bg="#FF0000", bd=-2) self.__frame.grid(row=0, column=0, sticky="NSEW") self.__frame.grid_rowconfigure(0, weight=1) self.__frame.grid_columnconfigure(0, weight=1) self.__canvas = tk.Canvas(self.__frame, bg="#000000", bd=-2) self.__canvas.grid(row=0, column=0, sticky="NSEW") self.__canvas.bind("<Configure>", self.__resize) self.__xdis = self.__canvas.winfo_width() // 2 self.__ydis = self.__canvas.winfo_height() // 2 self.__zoomScale = 1 self.__zoomStep = 5 self.__system = System(2, 1, 3) self._ui.title(self.__system.getName()) self.__run()
def test_NegativegetSysDistance(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) secondSys = "" with self.assertRaises(TypeError): testSys.getSysDistance(secondSys)
class StreamPiControls: def __init__(self, btn_pwr, re_a, re_b, re_btn): self._volume = Volume() self._player = Player() self._rotary_encoder = RotaryEncoder(re_a, re_b, re_btn, self.re_callback, self.re_btn_callback) self._system = System() GPIO.setup(btn_pwr, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(btn_pwr, GPIO.FALLING, callback=self.pwr_callback, bouncetime=200) def re_callback(self, direction, btn_pressed): if direction == RotaryEncoder.DIRECTION_CLOCKWISE: self._volume.volume_up() elif direction == RotaryEncoder.DIRECTION_COUNTERCLOCKWISE: self._volume.volume_down() def re_btn_callback(self): if(self._player.is_playing()): self._player.stop() else: self._player.play("http://icecast.omroep.nl/3fm-bb-mp3") def pwr_callback(self, channel): self._system.shutdown()
def avgXOverFocus(totalSamples=50, startF=0, endF=101, extra=False): path = "output_model_data/avg_x_over_focus/" if not os.path.exists(path): os.mkdir(path) if startF < 0: startF = int(0) if endF > 101: endF = int(101) path += "sum_log-f%03d-%03d_s%d_" % (startF, endF - 1, totalSamples) i = 1 while os.path.exists(path + str(i) + ".csv"): i += 1 path += str(i) + ".csv" with open(path, "w") as out: header = "focus,age_joined,age_left,avg_spirit" if extra: header += ",church_joined_total,club_joined_total,actually_left_total" out.write(header + "\n") ppl = simplePopInit() # or -> betterPopInit() for _ in range(totalSamples): print("_", end="") print(flush=True) for _ in range(totalSamples): f = random.uniform(startF / 100, (endF - 1) / 100) s = System(f, 200, deepcopy(ppl)) s.run(40 * YEAR, verbosity=0) summary = f'{f},{wAvg(s.clubJoined)},{wAvg(s.clubLeft)},{s.averageClubSpirit()}' if extra: summary += f',{s.sundayJoined},{sum(s.clubJoined)},{s.leftActually()}' out.write(summary + "\n") print("\u2588", end="", flush=True)
def bulkRuns(focus=0.5, each_run=3, verbosity=0, samples=40, initializer=simplePopInit, log=False): record = [[], []] for i in range(samples): peeps = initializer() s = System(focus, 200, peeps) s.run(each_run * YEAR, verbosity, log) record[0].append(sum(s.clubJoined)) record[1].append(len(list(filter(lambda h: h.club_ == LEFT, s.people)))) if verbosity < 1: print("-", end=("\n" if i % 60 == 59 else ""), flush=True) if len(record[0]) == 0: print(" 0 samples ") return print() print(" average joining club members per year: ", sum(record[0]) / len(record[0]) / each_run, "; median: ", sorted(record[0])[len(record[0]) // 2] / each_run, sep="") print(" average members leaving per year:", sum(record[1]) / len(record[1]) / each_run)
def test_PositivegetSysDistance(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) line = self.secondSys secondSys = System().build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) self.assertEqual(convert(self.distances[0], 1)/1000, int(testSys.getSysDistance(secondSys)), "Fail: System distances are not getting calculated correctly")
def test_Negative_jumps_Route(self): self.testRoute = RouteFinder(self.testRoutes[0][0], self.testRoutes[0][1], self.systems) self.testSys = System() line = self.testSysLine self.testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6],line[7]) with self.assertRaises(GeneralError): self.testRoute.jumpsRoute('normal',start=self.testSys) with self.assertRaises(GeneralError): self.testRoute.jumpsRoute('normal',end=self.testSys)
def betterPopInit(focus=0.5, pop_size=200): peeps = simplePopInit(pop_size) count = len(list(filter(lambda h: h.club(), peeps))) while (count < 14 or 22 < count): peeps = simplePopInit(pop_size) count = len(list(filter(lambda h: h.club(), peeps))) s = System(focus, pop_size, peeps) s.run(10 * YEAR, 1) return s.people
class App: def __init__(self, name="Procedural System", winSize=(500, 500), tick=60): self.running = True self.clock = pygame.time.Clock() self.tick = tick self.__xdis = winSize[0] // 2 self.__ydis = winSize[1] // 2 self.__zoomScale = 0.5 self.__zoomStep = 1.1 self.__system = System(50, 90) pygame.init() self.window = pygame.display.set_mode(winSize) self.mainloop() def mainloop(self): while self.running: #keyboard processing keys = pygame.key.get_pressed() if keys[pygame.K_q]: pygame.event.post(pygame.event.Event(pygame.QUIT)) if keys[pygame.K_i]: self.__zoomScale = min(self.__zoomScale * self.__zoomStep, 1) if keys[pygame.K_o]: self.__zoomScale = max(self.__zoomScale / self.__zoomStep, 0.01) #event processing for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() self.running = False #not sure if redundant if not self.running: break self.window.fill("black") #draw self.__system.nextFrame() self.display() pygame.display.flip() pygame.event.pump() self.clock.tick(self.tick) def display(self): for b in self.__system.getBodies(): d = b.getData() pygame.draw.circle(self.window, d[5], ((d[2][0] * self.__zoomScale) + self.__xdis, (d[2][1] * self.__zoomScale) + self.__ydis), d[1] * self.__zoomScale)
class Application(object): settings = None log = system = None # Placeholders to be filled later. growl = None # Can be 'None' if no Growl found. def __init__(self, is_daemon=True): self.settings = self._assembleSettings(is_daemon=is_daemon) self.log = Logger(self) self.log.install() self.log.debug("Logging installed.") self.system = System(self) self.log.debug("Application initialisation finished.") def _assembleSettings(self, is_daemon): """Assemple application settings (such as log dir, etc).""" return _AppConfig({ "is_daemon": is_daemon, "log_dir": os.path.join(os.path.dirname(__file__), "logs"), }) def doWork(self): """Called when caller wants for application to perform its actual functionality.""" self.system.loadPlugins() self.log.debug("System plugins loaded.") # Growl app is so specific and widespread that it makes sense to # care about it even on the top application level. if self.system.plugins.growl.isRunning(): self.growl = self.system.plugins.growl self.growl.setGlobalGrowlingApplicationOptions("OsXRuleActions") # Now to call call user configuration. from config import main as mainConfig try: mainConfig.execute(self.system) except: self.log.exception("Error happened during config run.") @classmethod def consoleRun(cls, options): """Called when application is initialized from console.""" _app = cls(is_daemon=options.is_daemon) try: _app.doWork() except: _app.showBadException("Error in main application loop.") def showBadException(self, msg): """Show top-level exception. Called only when everything else fails.""" _str = StringIO() traceback.print_exc(file=_str) _str.seek(0, 0) _str = _str.read() _pop = subprocess.Popen("open -tf", shell=True, stdin=subprocess.PIPE) _pop.stdin.write("Error happend: %s\n%s" % (msg, _str)) _pop.communicate()
def loadAll(load_name): global system_list global planet_list global ship_list global crew_list global game_folder makePartsList() path_to_load = game_folder + '/' + 'Save' + '/' + str(load_name) file_to_read = open(path_to_load + '/' + 'system', 'r') tmp = [] for line in file_to_read: tmp.append(line.split(':')[1]) if line.split(':')[0] == 'state': system = System() system.load(tmp) system_list.append(system) tmp = [] file_to_read.close() file_to_read = open(path_to_load + '/' + 'planet', 'r') tmp = [] for line in file_to_read: tmp.append(line.split(':')[1]) if line.split(':')[0] == 'resourse': planet = Planet() planet.load(tmp) planet_list.append(planet) tmp = [] file_to_read.close() file_to_read = open(path_to_load + '/' + 'ship', 'r') tmp = [] for line in file_to_read: tmp.append(line.split(':')[1]) if line.split(':')[0] == 'spot': ship = Ship() ship.load(tmp) ship_list.append(ship) tmp = [] file_to_read.close() file_to_read = open(path_to_load + '/' + 'crew', 'r') tmp = [] for line in file_to_read: tmp.append(line.split(':')[1]) if line.split(':')[0] == 'weapon': crew = Crew() crew.load(tmp) crew_list.append(crew) tmp = [] file_to_read.close() gui.paintWindowGalaxy()
def test_PositiveBuildSys(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) self.assertTrue(isinstance(testSys, System), "Fail: test system is not an instance of system") self.assertEqual(line[0], testSys.getName(), "Fail: test system name not correct") self.assertEqual(line[1], testSys.getConstellation(), "Fail: test system constellation not correct") self.assertEqual(line[2], testSys.getRegion(), "Fail: test system region not correct") self.assertEqual(line[3], testSys.getID(), "Fail: test system ID not correct") self.assertEqual(convert(line[4], 1), testSys.getPOS()[0], "Fail: test system PosX not correct") self.assertEqual(convert(line[5], 1), testSys.getPOS()[1], "Fail: test system PosY not correct") self.assertEqual(convert(line[6], 1), testSys.getPOS()[2], "Fail: test system PosZ not correct") self.assertEqual(round(float(line[7]),1), testSys.getSecurity(), "Fail: test system Security not correct")
def test_NegativeaddgetGatePos(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) line = self.corruptMissingGateData with self.assertRaises(IndexError): testSys.addGatePos(line[4], [line[1], line[2]]) line = self.corruptWrongGateData with self.assertRaises(ValueError): testSys.addGatePos(line[5], [line[1], line[2], line[3]]) with self.assertRaises(KeyError): testSys.getGatePos("fail")
def test_NegativesetgetParent(self): self.main.loadSystems() line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) parent = self.main.systems[self.correctGateData[0][5]] with self.assertRaises(TypeError): testSys.setParent("Fail", parent) with self.assertRaises(TypeError): testSys.setParent(1, "Fail") with self.assertRaises(IndexError): testSys.getParent(9)
def computeSolution(self, structure): #print (structure) nodes = [] for key in structure: nodeA, nodeB = structure[key] if nodeA not in nodes: nodes.append(nodeA) if nodeB not in nodes: nodes.append(nodeB) connections = [(nodes.index(structure[key][0]), nodes.index(structure[key][1])) for key in structure] nodeLoad = 10000 loads = [Load(-1 * nodeLoad, 'y', idx) for idx in range(len(nodes))] #print("Nodes {}".format(nodes)) maxRight = (0, 0) maxIdx = 0 for idx in range(len(nodes)): if nodes[idx][0] > maxRight[0]: maxRight = nodes[idx] maxIdx = idx if nodes[idx][0] == maxRight[0]: if nodes[idx][1] < maxRight[1]: maxRight = nodes[idx] maxIdx = idx maxLeft = (float("inf"), float("inf")) minIdx = 0 for idx in range(len(nodes)): if nodes[idx][0] < maxLeft[0]: maxLeft = nodes[idx] minIdx = idx if nodes[idx][0] == maxLeft[0]: if nodes[idx][1] < maxLeft[1]: maxLeft = nodes[idx] minIdx = idx #not a good way to fix this. think of a better way if minIdx == maxIdx: maxIdx += 1 fixedNodes = [minIdx, maxIdx] #print("fixedNodes {}".format(fixedNodes)) #print(fixedNodes) #print("structure {}".format(structure)) system = System(modulus=30e6, area=10, inertia=100, nodes=nodes, fixedNodes=fixedNodes, connectivity=connections, loads=loads) return system.computeDisplacements()
def test_PositiveaddSysCorrectSysObject(self): line = self.correctSysLine testSys = System() #Create a sys object testSys = testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6],line[7]) self.assertEquals(testSys, self.main.addSys(line), "Fail: Systems not equal") try: self.assertEquals(testSys, self.main.systems[line[3]], "Fail: System not added correctly to system list:Systems not equal") except KeyError: self.fail("Fail: System not added correctly to system list: KeyError") self.assertTrue(line[0] in self.main.nameList, "Fail: Name list does not contain system name") try: self.assertEquals(line[3], self.main.sysNames[line[0]], "Fail: sys Name list does not contain correct sys ID") except KeyError: self.fail("Fail: sys Name list does not contain system name")
def __init__(self, name="Procedural System", winSize=(500, 500), tick=60): self.running = True self.clock = pygame.time.Clock() self.tick = tick self.__xdis = winSize[0] // 2 self.__ydis = winSize[1] // 2 self.__zoomScale = 0.5 self.__zoomStep = 1.1 self.__system = System(50, 90) pygame.init() self.window = pygame.display.set_mode(winSize) self.mainloop()
def test_PositivesetgetParent(self): self.main.loadSystems() line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) parent = self.main.systems[self.correctGateData[0][5]] testSys.setParent(0, parent) self.assertEqual(testSys.getParent(0), parent, "Fail: Parent stored incorrectly or at incorrect num") parent = self.main.systems[self.correctGateData[1][5]] testSys.setParent(10, parent) self.assertEqual(testSys.getParent(10), parent, "Fail: Parent stored incorrectly or at incorrect num")
def demo(years=40, focus=0.5, out="console"): peeps = simplePopInit() # print("initial club members:") # print the club members # print(list(map(str, filter(lambda h: h.club(), peeps)))) s = System(focus, 200, peeps) if out == "console": s.run(YEAR * years, 2) elif out == "log": s.run(YEAR * years, 1, log=True) elif out == "both": s.run(YEAR * years, 2, log=True) elif out == "silent": s.run(YEAR * years, 1) else: print("invalid option:", out)
def addSys(self, line): tempSys = System() #Create a sys object try: tempSys = tempSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6],line[7]) except IndexError: self.handleError(2, "Systems") return "Error, System file missing data, error passed to GUI" except ValueError: self.handleError(3, "Systems") return "Error, System file data corrupt, error passed to GUI" self.systems[line[3]] = tempSys; #Add the sys object to the systems dict, with the sys id as key self.nameList.append(line[0]); #Append the sys name to the name list self.sysNames[line[0]] = line[3]; #Add the sys name to the sysNames array, putting it in the entry corosponding to its id return tempSys
def _run(self): data = Data() data.training = self.training system = System(data) system.use_best_feature_set() system.create_features() system.train() system.eval(quiet=True) self.result_event_event = system.evaluation_accuracy_event_event self.result_event_timex = system.evaluation_accuracy_event_timex
def __init__(self): self.data = Data() self.system = System(self.data) self.system.use_all_features() self.system.use_feature_selection() self.system.create_features() self.system.train() self.system.save_predictions_to_relations() self.relations = self._get_relations() same_sentence, not_same_sentence = self._sort_relations_after_in_same_sentence() print "Same sentence event-event:" truth, predicted = self._get_truth_and_prediction(same_sentence) print Result(truth, predicted) print "Same sentence event-timex:" truth, predicted = self._get_truth_and_prediction(same_sentence, event_event=False) print Result(truth, predicted) print "Not same sentence event-event:" truth, predicted = self._get_truth_and_prediction(not_same_sentence) print Result(truth, predicted) print "Not same sentence event-timex:" truth, predicted = self._get_truth_and_prediction(not_same_sentence, event_event=False) print Result(truth, predicted)
def test_PositivesetgetParent(self): self.main.loadSystems() line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) parent = self.main.systems[self.correctGateData[0][5]] testSys.setParent(0, parent) self.assertEqual( testSys.getParent(0), parent, "Fail: Parent stored incorrectly or at incorrect num") parent = self.main.systems[self.correctGateData[1][5]] testSys.setParent(10, parent) self.assertEqual( testSys.getParent(10), parent, "Fail: Parent stored incorrectly or at incorrect num")
def run_tests(learning_rate, time_step, no_iteration): #no_iteration = int(np.load("results/counter.npy")) #np.save("counter.npy", np.array([1 + no_iteration])) print("Iteration began: ", no_iteration) meta = open("results/iteration_metadata.txt", "a+") meta.write( str(no_iteration) + " " + str(learning_rate) + " " + str(time_step) + "\n") meta.close() p = generate_particles(particles, dimensions) nqs = NeuralQuantumState(initial_sigma, nx, nh, dimensions) h = Hamiltonian(nqs) sys = System(p, h) sim = Simulation(sys) nqs_opt = sim.stochastic_gradient_descent(tolerance, learning_rate, mc_iterations, max_iterations, sampling, update_radius, time_step, burn_in_percentage, no_iteration) #end_time = time.time() #print("Time spent: ", end_time - start_time, " seconds.") return 5 * learning_rate
def __init__(self, is_daemon=True): self.settings = self._assembleSettings(is_daemon=is_daemon) self.log = Logger(self) self.log.install() self.log.debug("Logging installed.") self.system = System(self) self.log.debug("Application initialisation finished.")
def __init__(self, btn_pwr, re_a, re_b, re_btn): self._volume = Volume() self._player = Player() self._rotary_encoder = RotaryEncoder(re_a, re_b, re_btn, self.re_callback, self.re_btn_callback) self._system = System() GPIO.setup(btn_pwr, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(btn_pwr, GPIO.FALLING, callback=self.pwr_callback, bouncetime=200)
def main(): b1 = System.create_bank("PKO") b2 = System.create_bank("MBank") b3 = System.create_bank("Millenium") System.allocate_customers("clients_list.JSON", b1, b2, b3) print(b1) print(b2) print(b3) b1.deposit("Karol", 130) b2.withdraw("Robert", 1200) b3.credit("Maciek", 100) b1.investment("Julia", 130) b2.withdraw("Ola", 1200) b3.credit("Tymon", 100) b1.deposit("Dorian", 130) b2.investment("Ola", 1200) b3.withdraw("Krystian", 1200)
def addSys(self, line): tempSys = System() #Create a sys object try: tempSys = tempSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) except IndexError: self.handleError(2, "Systems") return "Error, System file missing data, error passed to GUI" except ValueError: self.handleError(3, "Systems") return "Error, System file data corrupt, error passed to GUI" self.systems[line[3]] = tempSys #Add the sys object to the systems dict, with the sys id as key self.nameList.append(line[0]) #Append the sys name to the name list self.sysNames[line[0]] = line[3] #Add the sys name to the sysNames array, putting it in the entry corosponding to its id return tempSys
def focusSensitivity(granularity=10, samples=1, startF=0, endF=101): path = "output_model_data/focus_sensitivity_" i = 1 while os.path.exists(path + str(i)): i += 1 path += str(i) + "/" if startF < 0: startF = 0 if endF > 101: endF = 101 ppl = simplePopInit() # or -> betterPopInit() for _ in range(len(range(startF, endF, granularity)) * samples): print("_", end="") print(flush=True) for f in range(startF, endF, granularity): for _ in range(samples): s = System(f / 100, 200, deepcopy(ppl)) s.run(40 * YEAR, verbosity=0, log=True, logDir=path) print("\u2588", end="", flush=True)
def run(json_string, q=None, watchDogQueue=None, marsRunningQueue=None, debugMode=False, ipAddress=None): config = parseConfig(json_string) timestamp = initOutput(config, q, debugMode) System(config, timestamp, q, watchDogQueue, marsRunningQueue, ipAddress)
def test_NegativeBuildSys(self): line = self.corruptMissingDataSysLine testSys = System() with self.assertRaises(TypeError): testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6]) line = self.corruptWrongDataSysLine with self.assertRaises(ValueError): testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) with self.assertRaises(ValueError): testSys.build(line[0], line[1], line[2], line[3], "Ten", line[5], line[6], line[7])
def test_PositiveaddAdjSysandgetAdjSys(self): self.main.loadSystems() line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) testID = self.correctGateData[0][5] testSys.addadjSys(self.main.systems[testID]) self.assertEqual(self.main.systems[testID], testSys.getadjSys(testID), "Fail: adjacent system not added correctly")
def warp_to_system(self, x, y): del self.window_list['System'].components[:] del self.sidebar_list['System'].components[:] self.station = None self.system = System(panel=self, font=self.font, small_font=self.small_font, x=x, y=y, add_station=True) self.window_list['System'].components.append(self.system.system_map) self.sidebar_list['System'].components.append(self.system) # self.system_map_index = len(self.window_list['System'].components)-1 self.sidebar_list['System'].components.append(self.back_to_console) self.event.adhoc_event(picture=self.system.family_portrait(), text='Warped to system: {0}'.format(self.system.name), goto='console')
def test_pendulum(self): # This matches the example here: # http://www.aoengr.com/Dynamics/LagrangianMechanicsPendulum.pdf A_theta = Symbol("A_theta") A_theta_dot = Symbol("A_theta_dot") g = Symbol("g") l = Symbol("l") m_A = Symbol("m_A") single_pendulum = System({ 'particles': [{ 'name': 'A', 'placement': { 'type': 'pole', 'origin': { 'type': 'fixed', 'position': (0, 0) }, 'length': l } }], 'gravity': True }) assert single_pendulum.kinetic_energy( ) == 0.5 * A_theta_dot**2 * m_A * l**2 assert single_pendulum.potential_energy() == m_A * g * l * cos(A_theta) assert single_pendulum.lagrangian( ) == 0.5 * A_theta_dot**2 * m_A * l**2 - m_A * g * l * cos(A_theta) assert single_pendulum.equations_of_motion() == { A_theta: g * sin(A_theta) / l }
def __init__(self,width=540,height=320,scale=2): self.width = width self.height = height self.scale = scale self.photoimage = [] self.system = System() self.frame = self.createframe() self.menu = MainMenu(self.frame,self).createmenu() self.frame.config(menu=self.menu) SecretaryPanel(self.frame,self.width,self.height,self.scale,self).showView() #loginPanel(self.frame,self.width,self.height,self).showView() self.frame.mainloop()
def test_PositiveaddAdjSysandgetAdjSys(self): self.main.loadSystems() line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) testID = self.correctGateData[0][5] testSys.addadjSys(self.main.systems[testID]) self.assertEqual(self.main.systems[testID],testSys.getadjSys(testID),"Fail: adjacent system not added correctly")
def test_double_pendulum(self): double_pendulum = System({ 'particles': [{ 'name': 'A', 'placement': { 'type': 'pole', 'origin': { 'type': 'fixed', 'position': (0, 0) }, 'length': 1 } }, { 'name': 'B', 'mass': 1, 'placement': { 'type': 'pole', 'origin': { 'type': 'particle', 'particle': 'A' }, 'length': 1 } }], 'gravity': True }) A_theta = Symbol("A_theta") B_theta = Symbol("B_theta") g = Symbol("g") m_A = Symbol("m_A") self.assertEquals( double_pendulum.equations_of_motion(), { A_theta: g * (m_A + 1.0) * sin(A_theta) / m_A, B_theta: g * sin(B_theta) })
def test_PositiveaddSysCorrectSysObject(self): line = self.correctSysLine testSys = System() #Create a sys object testSys = testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) self.assertEquals(testSys, self.main.addSys(line), "Fail: Systems not equal") try: self.assertEquals( testSys, self.main.systems[line[3]], "Fail: System not added correctly to system list:Systems not equal" ) except KeyError: self.fail( "Fail: System not added correctly to system list: KeyError") self.assertTrue(line[0] in self.main.nameList, "Fail: Name list does not contain system name") try: self.assertEquals( line[3], self.main.sysNames[line[0]], "Fail: sys Name list does not contain correct sys ID") except KeyError: self.fail("Fail: sys Name list does not contain system name")
def _run_systems(self): for k in range(1, self.max_len+1): features = list(set(self._feature_series(k, self.features_event_event) + self._feature_series(k, self.features_event_timex))) print features data = Data() data.training = TrainingSet(False, False, "data/training/TBAQ-cleaned/TimeBank/") system = System(data, features) system.create_features() system.cross_validation() now = list(set(self._feature_series(k, self.features_event_event))) if k > 1: prev = list(set(self._feature_series(k-1, self.features_event_event))) if k > 1: if now != prev: self.accuracies_event_event.append(system.crossval_accuracy_event_event) print system.crossval_accuracy_event_event else: self.accuracies_event_event.append(system.crossval_accuracy_event_event) print system.crossval_accuracy_event_event now = list(set(self._feature_series(k, self.features_event_timex))) if k > 1: prev = list(set(self._feature_series(k-1, self.features_event_timex))) if k > 1: if now != prev: self.accuracies_event_timex.append(system.crossval_accuracy_event_timex) print system.crossval_accuracy_event_timex else: self.accuracies_event_timex.append(system.crossval_accuracy_event_timex) print system.crossval_accuracy_event_timex print
def test_PositiveGetGateDistance(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) line = self.correctGateData testSys.addGatePos(line[0][5], [line[0][1], line[0][2], line[0][3]]) testSys.addGatePos(line[1][5], [line[1][1], line[1][2], line[1][3]]) expectedResult = round( (convert(self.distances[1], 1) / 1000) / 149597871, 1) actualResult = int(testSys.getGateDistance(line[0][5], line[1][5])) self.assertEqual(expectedResult, actualResult, "Fail: Gate distances not calculated correctly")
def test_PositiveGetGateDistance(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) line = self.correctGateData testSys.addGatePos(line[0][5], [line[0][1], line[0][2], line[0][3]]) testSys.addGatePos(line[1][5], [line[1][1], line[1][2], line[1][3]]) expectedResult = round((convert(self.distances[1], 1)/1000)/149597871, 1) actualResult = int(testSys.getGateDistance(line[0][5], line[1][5])) self.assertEqual(expectedResult, actualResult, "Fail: Gate distances not calculated correctly")
def test_mc_cycle_importance_sampling(self): wf = Gaussian() energy_model = HarmonicOscillator(wf, 1) d = np.random.randint(1, 4) N = np.random.randint(2, 10) particles = generate_particles(N, d) system = System(particles, energy_model) parameters = Parameters(1) sim = Simulation(system, parameters) alpha = np.array([0.5]) result = sim.mc_cycle(alpha, mc_iterations=1000, use_importance_sampling=True) npt.assert_almost_equal(result.energy_average, 0.5 * d * N)
def test_PositiveaddgetGatePos(self): self.main.loadSystems() line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) line = self.correctGateData[0] testSys.addGatePos(line[5], [line[1], line[2], line[3]]) pos = testSys.getGatePos(line[5]) self.assertEqual(convert(line[1], 2), pos[0], "Fail: PosX not added correctly") self.assertEqual(convert(line[2], 2), pos[1], "Fail: PosY not added correctly") self.assertEqual(convert(line[3], 2), pos[2], "Fail: PosZ not added correctly")
def test_gradient_descent_importance_sampling(self): wf = Gaussian() energy_model = HarmonicOscillator(wf, 1) d = np.random.randint(1, 4) N = np.random.randint(2, 10) particles = generate_particles(N, d) system = System(particles, energy_model) parameters = Parameters(1) sim = Simulation(system, parameters) initial_alpha = np.array([0.75]) result = sim.gradient_descent(initial_alpha, max_iterations=100, mc_iterations=1000, use_importance_sampling=True) npt.assert_almost_equal(result, 0.5)
def test_PositivegetSysDistance(self): line = self.correctSysLine testSys = System() testSys.build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) line = self.secondSys secondSys = System().build(line[0], line[1], line[2], line[3], line[4], line[5], line[6], line[7]) self.assertEqual( convert(self.distances[0], 1) / 1000, int(testSys.getSysDistance(secondSys)), "Fail: System distances are not getting calculated correctly")
def generateSystems(star_count): global system_list position_list = [] for i in range(0, star_count): system = System() system.id = i * 10 + 100 system.name = 'SYSTEM NAME ' + str(i) while True: x = random.randint(0, star_count - 1) y = random.randint(0, star_count - 1) flag = False if [x, y] not in position_list: system.position = [x, y] position_list.append([x, y]) break system.intensity = [0, random.random()] system.setColor() system.size = random.randint(1, 5) system.planets = [] for j in range(0, system.size): system.planets.append(system.id + j) generatePlanet(system.intensity[0], system.id, j) system_list.append(system)
def DefineQCLayer ( self, selection, qcModel, electronicState = None ): """Define a QC layer. A layer consists of two subsystems with the same atomic composition. One uses the new energy model and a weight of +1 whereas the second has the old energy model and a weight of -1. """ # . Get the latest defined system. if len ( self.subsystems ) > 0: number = len ( self.subsystems ) oldsystem = self.subsystems[-1].system else: number = 0 oldsystem = self.system # . Get the QC atom indices of the full system (excluding boundary atoms). try: oldqcset = set ( oldsystem.energyModel.qcAtoms.GetFullSelection ( ) ).difference ( set ( oldsystem.energyModel.qcAtoms.BoundaryAtomSelection ( ) ) ) except: raise ValueError ( "Unable to retrieve the previous system's QC atom indices." ) # . Map a subsystem's indices to those of the full system. if len ( self.subsystems ) > 0: mapping = self.subsystems[-1].selection unmapped = oldqcset oldqcset = set ( ) for i in unmapped: oldqcset.add ( mapping[i] ) # . Check that the selection is a subset of the previous one. newqcset = set ( selection ) if not newqcset.issubset ( oldqcset ): raise ValueError ( "The atoms in the new QC layer must be a subset of the QC atoms in the underlying system." ) # . Get the old QC model (which at this stage is known to exist). oldmodel = oldsystem.energyModel.qcModel # . Find the atomic numbers. atomicNumbers = self.system.atoms.GetItemAttributes ( "atomicNumber", selection = selection ) # . Find boundary atoms. boundaryAtoms = self.FindBoundaryAtoms ( selection, len ( atomicNumbers ) ) # . Extend atomicNumbers by the appropriate number of boundary atom hydrogens. atomicNumbers.extend ( len ( boundaryAtoms ) * [ 1 ] ) # . Define a basic QC system - it is cleaner to do this for a QC system from scratch without pruning, etc. system0 = System.FromAtoms ( atomicNumbers ) if electronicState is not None: system0.electronicState = electronicState system0.coordinates3 = Coordinates3.WithExtent ( len ( system0.atoms ) ) system0.coordinates3.Set ( 0.0 ) # . Define the subsystems of the layer. system1 = Clone ( system0 ) for ( i, ( system, model, weight ) ) in enumerate ( ( ( system0, oldmodel, -1.0 ), ( system1, qcModel, 1.0 ) ) ): system.label = "MultiLayer Objective Function Subsystem {:d} with Weight {:.1f}".format ( number+i, weight ) system.DefineQCModel ( model ) subsystem = MultiLayerSubsystem ( system, weight, selection, boundaryAtoms = boundaryAtoms ) subsystem.VariablesPut ( self.system.coordinates3 ) self.subsystems.append ( subsystem )
def download(self): fileName = self.path.rsplit("/", 1) filePath = "%s/%i-%s" % (self.tempStorage, hash(self), fileName[1]) if os.path.exists(filePath): self.path = filePath self.downloaded = True return self.downloaded Logging.debug("Trying download %s to %s." % (self.path, filePath)) try: httpRequest = urllib2.urlopen(self.path) except urllib2.HTTPError as e: return None if (not os.path.exists(self.tempStorage) or not os.access(self.tempStorage, os.W_OK) or System.getFreeSpace(self.tempStorage) < int(httpRequest.info().get("Content-Length"))): return None try: iso = file(filePath, "w") while 1: buf = httpRequest.read(16*1024) if not buf: break iso.write(buf) iso.close() except IOError as e: return None self.path = filePath self.downloaded = os.path.exists(filePath) return self.downloaded
def test_IsSystemRunningThroughWithAllFeatures(self): system = System(self.testdata) # Turn on features system.use_dependency_is_root() system.use_dependency_order() system.use_aspect() system.use_tense() system.use_same_tense() system.use_same_aspect() system.use_dependency_type() system.use_dct() system.use_type() system.use_same_polarity() system.use_polarity() system.use_class() system.use_entity_distance() system.use_textual_order() system.use_duration() system.use_duration_difference() system.use_same_pos() system.use_pos() system.use_temporal_signal() system.create_features() system.train() system.eval() self.assertTrue(True)
# Leave out i for testing train_X, test_X = leave_out(pieces_X, i) train_y, test_y = leave_out(pieces_y, i) # Transform back to sparse train_X = transform_to_sparse_matrix(train_X) test_X = transform_to_sparse_matrix(test_X) clf.fit(train_X, train_y) predicted = clf.predict(test_X) accs.append(accuracy_score(test_y, predicted)) return np.mean(accs) data = Data() data.training = TrainingSet(False, False, "data/training/TBAQ-cleaned/TimeBank/") system = System(data, ["lemma", "token"]) system.create_features() X_event_event, y_event_event = system.training_event_event X_event_timex, y_event_timex = system.training_event_timex X_event_event = transform_to_list(X_event_event) X_event_timex = transform_to_list(X_event_timex) print kfold(X_event_event, y_event_event, 5) print kfold(X_event_timex, y_event_timex, 5)
def process(cls, filename = None): if filename is None: filename = os.path.join(System.get_default_config_dir(), "slaveserver.conf") return cls.read_ini(filename)
#rs = bar.makeResultSet() plt.ylabel("result 0.0-1.0") plt.xlabel("#peers") k = 1 j = 1 while j < 8: x = [] y = [] i = 1 #num Nodes, min Edges, max Edges foo = Graph.Graph(10*j,2+k,4*k) foo.printGraph(str(j)) while i < 800: #numPeers, minNumWr, maxNumWr, numberOfTimeSteps tmp = System(foo, i, 2, 15, 4000) tmp.sim() rs = tmp.makeResultSet() x.append(i) y.append(rs[1]) i+=1 plt.plot(x,y, color=(random.random(), random.random(), random.random()), label="#Node = " +str(10*j) + ", minCon = " + str(2+k) + ", maxCon = " + str(3*k)) print str(j) + " done" j+=1 k+=1 plt.legend() plt.show()
from Data import Data from System import System data = Data() system = System(data) # Create features and apply feature selection system.use_all_features() system.use_feature_selection() system.create_features() # Train classifiers and save them to pickle file system.train() system.save_classifiers() # Run pairwise classification event_event, event_timex = system.eval() print "Event-Event:" print event_event print "Event-Timex:" print event_timex # Run global model system.create_confidence_scores() system.apply_global_model() event_event, event_timex = system.eval_global_model() print "Event-Event:" print event_event print "Event-Timex:" print event_timex
return n def get_triple_of_pairwise_classifier_mistakes_which_do_not_create_inconsistency(subgraphs_with_potentially_improvements): rels = [] for triple in subgraphs_with_potentially_improvements: gm_tripel = get_global_model_triple(triple) if triple[0].predicted_class == gm_tripel[0].relation_type and triple[1].predicted_class == gm_tripel[1].relation_type and triple[2].predicted_class == gm_tripel[2].relation_type: rels.append(triple) return rels data = Data() system = System(data) # Create features and apply feature selection system.use_all_features() system.use_feature_selection() system.create_features() system.train() # Needs to be called to set relation.predicted_class system.save_predictions_to_relations() system.eval(quiet=True) # Run global model system.create_confidence_scores() system.apply_global_model()