def create_data(self): space = Space(project_id=self.id) timer = Timer() timer.start() info = dict() info['number_of_particles'] = int(self.number_of_particles) info['dimension'] = int(self.dimension) info['project_id'] = self.id space.set_dimension(dimension=info['dimension']) space.add_particles(number=int(info['number_of_particles']), position=[0, 0, 0]) space.simulate( n=500, timer=timer, step_particles_insertion=self.particle_insertion.get('number')) space.simulate(n=200, timer=timer) info['simulation_number'] = space.simulation_number timer.stop() info['timer'] = timer.dictionary() json.dump(info, open(str(self.id) + '/' + 'info', 'w')) print(info)
def onEnter(self, entityMailbox): """ defined method. 进入场景 """ self.avatars[entityMailbox.id] = entityMailbox Space.onEnter(self, entityMailbox)
def onEnter(self, entityCall): """ defined method. 进入场景 """ self.avatars[entityCall.id] = entityCall Space.onEnter(self, entityCall)
def onEnter(self, entityCall): """ Defined method. Entering the scene """ self.avatars[entityCall.id] = entityCall Space.onEnter(self, entityCall)
def main(): player_box = PlayerBox() generator = Generator() menu = Menu() lib = TextureLib() graphics = Graphics(lib) space = Space(graphics, menu, generator, player_box) space.start()
def onLeave(self, entityID): """ defined method. 离开场景 """ if entityID in self.avatars: del self.avatars[entityID] Space.onLeave(self, entityID)
def onLeave(self, entityID): """ Defined method. Leave the scene """ if entityID in self.avatars: del self.avatars[entityID] Space.onLeave(self, entityID)
def onTimer(self, tid, userArg): """ KBEngine method. 引擎回调timer触发 """ #DEBUG_MSG("%s::onTimer: %i, tid:%i, arg:%i" % (self.getScriptName(), self.id, tid, userArg)) if SCDefine.TIMER_TYPE_HEARDBEAT == userArg: self.onCheckDestroyTimer() Space.onTimer(self, tid, userArg)
def onTimer(self, tid, userArg): """ Ouroboros method. Engine callback timer trigger """ #DEBUG_MSG("%s::onTimer: %i, tid:%i, arg:%i" % (self.getScriptName(), self.id, tid, userArg)) if ServerConstantsDefine.TIMER_TYPE_HEARTBEAT == userArg: self.onCheckDestroyTimer() Space.onTimer(self, tid, userArg)
def initialize(self): for x in range(9): for y in range(9): space = Space() space.x = x space.y = y self.set(x, y, space) self.graph = self.create_graph() self.space_distances_p1 = self.calculate_space_distances(self.graph, 8) self.space_distances_p2 = self.calculate_space_distances(self.graph, 0)
def button_clicked(self): # Generation of an initial solution try: loop_time = 1.0 / 60 self.space = Space(self.confParam, self.drawSpace, self.drawPher, self.drawProcess, self.drawEnd, loop_time) self.space.setDaemon(True) self.space.start() self.state.setText('Estado: Processing') self.state.setStyleSheet('color: #AC660A') except Exception as inst: print type(inst) # the exception instance print inst.args # arguments stored in .args print inst self.state.setText('Estado: Processing error') self.state.setStyleSheet('color: #D20101') self.process.setText('Process:') self.process.setStyleSheet('color: #1F1C1C') self.startProcess() # It start the space image self.canvasSpace = MyCanvasSpace(self.image, self.space, parent=None, width=self.confParam['rowsF'], height=self.confParam['colsF'], dpi=100, focus=self.confParam['focusF']) self.imagesLayout.addWidget(self.canvasSpace) self.image.setFocus() self.setCentralWidget(self.image) # It start the pheromone image self.canvasPheromone = MyCanvasPheromone( self.pheromones, self.space, parent=None, width=30, height=self.confParam['colsF'], dpi=100) self.pheromLayout.addWidget(self.canvasPheromone) self.pheromones.setFocus() self.setCentralWidget(self.pheromones) # Connect signals to draw self.drawSpace.connect(self.handle_drawSpace) self.drawPher.connect(self.handle_drawPher) self.drawProcess.connect(self.handle_drawProcess) self.drawEnd.connect(self.handle_drawEnd)
def simulate(self): space = Space(project_id=self.id) timer = Timer() timer.start() space.set_dimension(dimension=self.dimension) for source in self.sources: space.add_particles(number=int(source.initial_particles_N), position=[ source.position.x_axis, source.position.y_axis, source.position.z_axis ]) for i in range(int(self.number_of_iterations / 25)): space.simulate(n=25, info=True, timer=timer, save_particles=False, sources=self.sources) self.save_lattice(particles=space.particles, simulation_number=space.simulation_number) timer.stop() print(timer.dictionary())
def create_matplotlib_graphs(space_object: Space, generations: int, save: tuple = (False, None), show: bool = True, onebyone: bool = False): """ This function will create matplotlib figures for both saving and displaying at every generation. :param space_object: The Space object :param generations: An integer of generation number :param save: A tuple which is (will_save, file_name_prefix). Default is (False, None) :param show: True if want to show, False if don't want. :param onebyone: True if show one by one and False for showing together. :return: """ # Making imports here because of unnecessary usage # of matplotlib import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Creating the first values without .update() values = Space.clear_ndarray(space_object.export()) if not onebyone: fig = plt.figure() workspace_dims = workspace_divider(generations) for gen in range(generations): fig.add_subplot(110 * workspace_dims + gen + 1, projection="3d") ax = fig.gca() ax.set_aspect('auto') ax.voxels(values, edgecolor="k") if save[0]: plt.savefig(f"{save[1]}_gen_{gen}") space_object.update() values = Space.clear_ndarray(space_object.export()) if show: plt.show() else: for gen in range(generations): fig = plt.figure(gen) ax = fig.gca(projection='3d') ax.set_aspect('auto') ax.voxels(values, edgecolor="k") if save[0]: plt.savefig(f"{save[1]}_gen_{gen}") if show: print("You must close the figure in order to see next generation.") plt.show() space_object.update() values = Space.clear_ndarray(space_object.export())
def test_add_remove_subspaces(self): self.assertRaises(ValueError, self.solar_system.add_element, self.solar_system) self.assertRaises(ValueError, self.solar_system.add_element, 'Any object except Space') earth = self.solar_system.elements['Earth'] moon = Space('Moon') earth.add_element(moon) lunohod = Space('Lunohod') moon.add_element(lunohod) mars = self.solar_system.elements['Mars'] phobos = Space('Phobos') deimos = Space('Deimos') mars.add_element(phobos) mars.add_element(deimos) self.assertRaises(ValueError, self.solar_system.add_element, lunohod) self.assertRaises(ValueError, self.solar_system.remove_element, 'Any object, not Space')
def highdimsample(): space2 = Space.generateSpace(1000, 7, 10**(-17)) print space2 closestPair = closestPairDivide(space2) print "\n\n\n"
def graphicsample(): space = Space.generateSpace(10000, 3, 10**(-10)) print space fig = pylab.figure() ax = Axes3D(fig) for i in space.pointList: ax.scatter(i.vector[0], i.vector[1], i.vector[2], s=30) closestPair = closestPairBrutePlus(space) print "\n\n\n" closestPair = closestPairDivide(space) ax.scatter(closestPair.pointA.vector[0], closestPair.pointA.vector[1], closestPair.pointA.vector[2], c='r', s=30) ax.scatter(closestPair.pointB.vector[0], closestPair.pointB.vector[1], closestPair.pointB.vector[2], c='r', s=30) pyplot.show()
def as_BFarray(self): # ***TODO: The caching here is broken because of shape, strides and ctypes.data # How to fix? #*if self._BFarray is not None: #* return self._BFarray a = _bf.BFarray() a.data = self.ctypes.data a.space = Space(self.bf.space).as_BFspace() a.dtype = self.bf.dtype.as_BFdtype() a.immutable = not self.flags['WRITEABLE'] a.ndim = len(self.shape) # HACK WAR for backend not yet supporting ndim=0 (scalar arrays) if a.ndim == 0: a.ndim = 1 a.shape[0] = 1 a.strides[0] = self.bf.dtype.itemsize for d in xrange(len(self.shape)): a.shape[d] = self.shape[d] # HACK TESTING support for 'packed' arrays itemsize_bits = self.bf.dtype.itemsize_bits if itemsize_bits < 8: a.shape[a.ndim - 1] *= 8 // itemsize_bits for d in xrange(len(self.strides)): a.strides[d] = self.strides[d] a.big_endian = not self.bf.native a.conjugated = self.bf.conjugated return a
def __init__(self): self.naubs = [] self.naubjoints = set() self.playing = False self.cb = Naubino.Callbacks() self.__score = 0 self.__warn = False self.space = Space(self) self.pointers = set() self.size = Vec2d(0, 0) self.mode = None self.naub_colors = dict((name, ColorRGB255(*color)) for name , color in ( ("red" , (229, 53, 23)), ("pink" , (226, 0, 122)), ("green" , (151, 190, 13)), ("blue" , ( 0, 139, 208)), ("purple" , (100, 31, 128)), ("yellow" , (255, 204, 0)))) self.colors = dict((name, ColorRGB255(*color)) for name , color in ( ("black" , ( 0, 0, 0)), ("grey" , (160, 160, 160)), ("white" , (255, 255, 255)))) self.colors.update(self.naub_colors)
def highdimsample(): space2 = Space.generateSpace(1000,7,10**(-17)) print space2 closestPair = closestPairDivide(space2) print "\n\n\n"
def Draw(self): """ Draw the board :return: """ # Where we will start creating objects xy_location = list(self.START) # Keep track of lines made - we don't want more than 4 linesMade = 0 for x in range(3): for y in range(3): # Create a new space and put in list to keep track of # Need a new argument to know what position the space is on the board # This is the (x, y) tuple self.spaces.append(Space(self.screen, (x, y), self.spaceHeight, self.spaceWidth, tuple(xy_location))) # Update xy_location list to correct position xy_location[0] += self.spaceWidth # Create the line if we haven't reached limit of 4 if linesMade < 4 and y != 2: # Move half the line thickness so there's no overlap between the line # and the Space xy_location[0] += self.HALF_LINE_THICKNESS pygame.draw.line(self.screen, self.BLACK, xy_location, (xy_location[0], self.screen.get_height()), self.LINE_THICKNESS) linesMade += 1 xy_location[0] += self.HALF_LINE_THICKNESS else: # If we already have all lines, just move by the number of pixels the # existing line takes up xy_location[0] += self.LINE_THICKNESS # Reset x value to 0 xy_location[0] = 0 # incriment y value xy_location[1] += self.spaceHeight # Draw line if all lines haven't been drawn if linesMade < 5: xy_location[1] += self.HALF_LINE_THICKNESS pygame.draw.line(self.screen, self.BLACK, xy_location, (self.screen.get_width(), xy_location[1]), self.LINE_THICKNESS) linesMade += 1 xy_location[1] += self.HALF_LINE_THICKNESS
def setUp(self): self.solar_system = Space('Solar System') mercury = Space('Mercury') venus = Space('Venus') earth = Space('Earth') mars = Space('Mars') self.solar_system.add_element(mercury) self.solar_system.add_element(venus) self.solar_system.add_element(earth) self.solar_system.add_element(mars)
def getBoard(self, file): board_df = pd.read_csv(file) for _, attributes in board_df.iterrows(): if attributes['class'] == 'Street': self.board.append(Space.Street(attributes)) if attributes['class'] == 'Utility': self.board.append(Space.Utility(attributes)) if attributes['class'] == 'Railroad': self.board.append(Space.Railroad(attributes)) if attributes['class'] == 'Tax': self.board.append(Space.Tax(attributes)) if attributes['class'] == 'Chance': self.board.append(Space.Chance()) if attributes['class'] == 'Chest': self.board.append(Space.Chest()) if attributes['class'] in ['Jail', 'Idle']: self.board.append([])
def main(): space = Space(width=500, height=500) root = Tk() # Putting window to center of the screen screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() margin_x = int((screen_width - space.width) / 2) margin_y = int((screen_height - space.height) / 2) geometry = str(space.width) + "x" + str( space.height) + "+" + str(margin_x) + "+" + str(margin_y) root.geometry(geometry) app = DummySpaceGame(parent=root, space=space) app.mainloop()
def __init__(self, x, y, z, description): """ Der Konstruktor erzeugt die Planeteigenschaften, wie die Position, Rotations- und Translationsgeschwindigkeit :param x: X-Koordinate des Planeten :param y: Y-Koordinate des Planeten :param z: Z-Koordinate des Planeten :param description: der Name des Planeten """ self.position = array( 'd', [x, y, z]) #Position des Planeten wird in einem Array gespeichert self.description = description self.orbit = None #beschreibt sich selber self.rotation = None #steuert die Rotation self.translation = None #steuert die Translatio self.scale = 1 #Planetgroesse self.dayscale = None #Anzahl der Stunden fuer eine vollstaendige Umdrehnung um sich selbst self.yearscale = None #Anzahl der Tage fuer einen Umlauf um die Sonne self.texture = None #Texture self.rspeed = 0.1 #Geschwindigkeit der Rotation self.tspeed = 0.1 #Geschwindigkeit der Translation self.move = [ ] #Hier wird gespeichert ob der Planet rotieren oder eine Translation vollfuehren soll self.h = False self.tt = None self.t = True self.light = False self.plnp = [] base.setBackgroundColor(0, 0, 0) #schwarter Hintergrund base.useDrive() #Mouselistener #base.oobe() camera.setPos(0, 0, 45) #Kameraposition camera.setHpr(0, -90, 0) #Kameraausrichtung shadow = [[1.25, 1.25, 1.25]] for s in shadow: self.plnp.append(Space().pointlight(s[0], s[1], s[2])) self.showHelp() #Listener self.accept("h", self.showHelp) # help mit kommandos wird angezeigt (label) self.accept("escape", sys.exit) # programm wird beendet self.accept("t", self.texturAnAus) #textur an/aus self.accept("control-mouse1", self.changeLight) #punktlichtwuelle setzen self.accept("wheel_up", self.speedup) # animation wird schneller self.accept("wheel_down", self.speeddown) # animation wird langsamer self.accept("space", self.startstop) # animation stoppen und wieder startet
def save_lattice(self, project_id=str(), particles=None, simulation_number=int()): info = dict() info = json.load(open(project_id, 'r')) space = Space(project_id=project_id) space.lattice = Lattice() if particles: lattice = Lattice() lattice.update(particles=particles) lattice.save(project_id=project_id, simulation_number=simulation_number) else: i = 0 while True: if os.path.exists('Dataset/Particles/' + project_id + '/' + str(i)): print(str(i)) space.particles = Particles.load( project_id=info['project_id'], simulation_number=i) space.lattice.update(particles=space.particles) space.lattice.save(project_id=info['project_id'], simulation_number=i) i += 1 else: break
def __init__(self): #set columns and rows in board self.ROWS = 7 self.COLS = 8 #create 2D list for all spaces on board self.spaces = [[Space() for x in list(range(self.COLS))] for x in list(range(self.ROWS))] #highest row containing open move in each column. Set to start at bottom row self.array = np.zeros((self.ROWS, self.COLS)) self.open_row = [6] * 8 #contains the last move played self.last_move = [] #tracks number of moves played self.num_moves = 0 #Set Space.index to track the postion of each space on the board self.setup_space_index() #Set Space.open_x and Space.open_o to track open spaces withing 4 potions on the board self.setup_open()
def __array_finalize__(self, obj): if obj is None: # Already initialized self.bf in __new__ return # Initialize as view of existing array if isinstance(obj, ndarray): # Copy metadata from existing bf.ndarray self.bf = BFArrayInfo(obj.bf.space, obj.bf.dtype, obj.bf.native, obj.bf.conjugated) else: # Generate metadata from existing np.ndarray space = str(Space(raw_get_space(obj.ctypes.data))) #dtype = str(DataType(obj.dtype)) # **TODO: Decide on bf.dtype being DataType vs. string (and same for space) dtype = DataType(obj.dtype) native = obj.dtype.isnative conjugated = False self.bf = BFArrayInfo(space, dtype, native, conjugated) self._update_BFarray()
def create_mayavi_animation(space_object: Space, generations: int, wait: int, ui: bool = False): """ This function will create a 3D animation using mayavi.mlab module. You can't directly change camera positions while calculating the generations but after, you can. It should be fixed in new versions. :param space_object: The Space object which will simulated. :param generations: Generation count. :param wait: The delay rate for animation. :param ui: User inteface option for stop/start animation. (Mayavi) """ from mayavi import mlab x, y, z, val = space_object.export(seperate_dims=True) figure = mlab.figure(size=(800, 600)) plt = mlab.points3d(x, y, z, val, mode="cube", color=(1, 0, 0), figure=figure) print("Generation 0: Inital state") # TODO: Fix the non-changeable camera during the calculation of generations. @mlab.animate(delay=wait, ui=ui) def __animate(gen): fig = mlab.gcf() dist = mlab.view()[2] for index in range(gen): space_object.update() _x, _y, _z, _val = space_object.export(seperate_dims=True) plt.mlab_source.reset(x=_x, y=_y, z=_z, scalars=_val, reset_zoom=True) print(f"Generation: {index + 1}") mlab.view(distance=dist+index, focalpoint="auto", figure=fig) index += 1 if index == gen: print("Simulation has completed.") yield return True while True: is_ended = __animate(generations) if is_ended: break mlab.show()
def graphicsample(): space = Space.generateSpace(10000,3,10**(-10)) print space fig = pylab.figure() ax = Axes3D(fig) for i in space.pointList: ax.scatter(i.vector[0], i.vector[1], i.vector[2], s= 30) closestPair = closestPairBrutePlus(space) print "\n\n\n" closestPair = closestPairDivide(space) ax.scatter(closestPair.pointA.vector[0], closestPair.pointA.vector[1], closestPair.pointA.vector[2], c= 'r', s= 30) ax.scatter(closestPair.pointB.vector[0], closestPair.pointB.vector[1], closestPair.pointB.vector[2], c= 'r', s= 30) pyplot.show()
def __init__(self): ''' Constructor ''' self.__levelCount = int( raw_input("to define the parking lot's level count:")) cards = [] for i in range(self.__levelCount): levelId = i + 1 self.__spaceCountEachLevel = int( raw_input("to define the space count in level " + str(levelId) + " of the parking lot:")) spacesOfEachLevel = [] for j in range(self.__spaceCountEachLevel): spaceId = i * self.__spaceCountEachLevel + j + 1 spacesOfEachLevel.append(Space(spaceId)) cards.append(Card(spaceId, levelId, spaceId)) self.__levels.append(Level(spacesOfEachLevel, levelId)) self.__totalSpaceCount += self.__spaceCountEachLevel self.__cardReader = CardReader(cards)
class TestSpace(unittest.TestCase): def setUp(self): self.solar_system = Space('Solar System') mercury = Space('Mercury') venus = Space('Venus') earth = Space('Earth') mars = Space('Mars') self.solar_system.add_element(mercury) self.solar_system.add_element(venus) self.solar_system.add_element(earth) self.solar_system.add_element(mars) def space_constructor(self): self.assertRaises(ValueError, Space, 'xxx', '0') def test_add_remove_subspaces(self): self.assertRaises(ValueError, self.solar_system.add_element, self.solar_system) self.assertRaises(ValueError, self.solar_system.add_element, 'Any object except Space') earth = self.solar_system.elements['Earth'] moon = Space('Moon') earth.add_element(moon) lunohod = Space('Lunohod') moon.add_element(lunohod) mars = self.solar_system.elements['Mars'] phobos = Space('Phobos') deimos = Space('Deimos') mars.add_element(phobos) mars.add_element(deimos) self.assertRaises(ValueError, self.solar_system.add_element, lunohod) self.assertRaises(ValueError, self.solar_system.remove_element, 'Any object, not Space') def test_add_same_name_subspaces(self): mars = self.solar_system.elements['Mars'] count = 105 for i in range(count): phobos = Space('Phobos') mars.add_element(phobos) self.assertEqual(phobos.name, 'Phobos %d' % (count-1))
SHOW = options.temporary import random random.seed(SEED) usedLayers = [ layers.LayerPlanets(), layers.LayerPlanetsSelection(), layers.LayerPlanetsTerrain(), layers.LayerPlanetsTrees(), layers.LayerPlanetsLife(), ] im = Image.new("RGB", (WIDTH, HEIGHT), BACKGROUND) space = Space(SEED) def saveImage(image, steps, layers): if SHOW: image.show() else: name = "out" if steps != None: name += "-s" + str(steps) if layers != None: name += "-l" + str(layers) name += ".png" image.save(name, "PNG") print("Image saved as " + name)
def __init__(self): Space.__init__(self) self.avatars = {} self.addTimer(30, 10, SCDefine.TIMER_TYPE_HEARDBEAT)
def __init__(self): Space.__init__(self)
def __init__(self, s_id, color): Space.__init__(self, s_id) self.pawns = [] self.color = color
def __init__(self): Space.__init__(self) self.avatars = {}
class Naubino(object): class Callbacks(object): def score_changed (self, score ): pass def warn_changed (self, warn ): pass def add_naub (self, naub ): pass def remove_naub (self, naub ): pass def add_naub_joint (self, joint ): pass def remove_naub_joint (self, joint ): pass def pre_remove_naub (self, naub ): pass def pre_remove_naub_joint(self, joint ): pass def fail (self ): pass @property def score(self): return self.__score @score.setter def score(self, score): if self.__score == score: return self.__score = score self.cb.score_changed(score) @property def warn(self): return self.__warn @warn.setter def warn(self, warn): if self.__warn == warn: return self.__warn = warn self.cb.warn_changed(warn) def __init__(self): self.naubs = [] self.naubjoints = set() self.playing = False self.cb = Naubino.Callbacks() self.__score = 0 self.__warn = False self.space = Space(self) self.pointers = set() self.size = Vec2d(0, 0) self.mode = None self.naub_colors = dict((name, ColorRGB255(*color)) for name , color in ( ("red" , (229, 53, 23)), ("pink" , (226, 0, 122)), ("green" , (151, 190, 13)), ("blue" , ( 0, 139, 208)), ("purple" , (100, 31, 128)), ("yellow" , (255, 204, 0)))) self.colors = dict((name, ColorRGB255(*color)) for name , color in ( ("black" , ( 0, 0, 0)), ("grey" , (160, 160, 160)), ("white" , (255, 255, 255)))) self.colors.update(self.naub_colors) def create_pointer(self, pos): pointer = Pointer(pos) self.space.add(pointer.body) self.pointers.add(pointer) return pointer def remove_pointer(self, pointer): self.pointers.remove(pointer) self.space.remove(pointer.body) def add_naub(self, naub): naub.naubino = self if naub not in self.naubs: self.naubs.append(naub) if self.mode: self.mode.add_naub(naub) self.cb.add_naub(naub) def remove_naub(self, naub): self.cb.remove_naub(naub) if self.mode: self.mode.remove_naub(naub) if naub in self.naubs: self.naubs.remove(naub) def pre_remove_naub(self, naub): self.cb.pre_remove_naub(naub) def add_naubs(self, *naubs): for naub in naubs: self.add_naub(naub) def add_naub_joint(self, joint): self.naubjoints.add(joint) self.cb.add_naub_joint(joint) def remove_naub_joint(self, joint): self.naubjoints.discard(joint) self.cb.remove_naub_joint(joint) def pre_remove_naub_joint(self, joint): self.cb.pre_remove_naub_joint(joint) def create_naub_pair(self, pos = (0, 0), rot = 0): return self.create_naub_chain(2, pos, rot) def create_naub_chain(self, n, pos = (0, 0), rot = 0): pos = Vec2d(*pos) naubs = [Naub(self) for i in xrange(n)] restl = Config.naub_joint_rest_length restl = [restl(a, b) for a, b in zip(naubs, naubs[1:])] restl = tuple(sum(restl[:i]) for i in xrange(len(restl)+1)) v = Vec2d(1, 0).rotated(rot) for i, naub in enumerate(naubs): naub.pos = pos + v * (-(restl[-1] * 0.5) + restl[i]) for a, b in zip(naubs, naubs[1:]): a.join_naub(b) return naubs def random_naub_color(self): colors = self.naub_colors color = colors[sample(colors, 1)[0]] return color def score_cycle(self, cycle): # self.score += len(cycle) # property can't do += self.score = self.score + len(cycle) def step(self, dt): for pointer in self.pointers: pointer.step(dt) if self.mode: self.mode.step(dt) self.space.step(dt) for naub in self.naubs: naub.time = naub.time + dt danger = self.danger() self.warn = Config.warn(danger) if Config.fail(danger): self.stop() self.cb.fail() def danger(self): danger = 0 for j in self.naubjoints: if (j.a.pos.get_length() < 160 or j.b.pos.get_length() < 160): danger += 1 return danger def play(self): self.mode.play() def stop(self): self.mode.stop() def touch_down(self, pos): pos = Vec2d(*pos) for naub in self.naubs: if naub.shape.point_query(pos): pointer = self.create_pointer(pos) naub.select(pointer) return Touch(self, naub, pointer) return None def touch_up(self, naub, pointer): if naub.alive: naub.deselect(pointer) self.remove_pointer(pointer) def pop_cycle(self, cycle): self.score_cycle(cycle) for naub in cycle: naub.remove()
from __future__ import division, print_function from Space import Space from Space.Coordinates import Cartesian solar_system = Space('Solar System') mercury = Space('Mercury') venus = Space('Venus') earth = Space('Earth') mars = Space('Mars') solar_system.add_element(mercury) solar_system.add_element(venus) solar_system.add_element(earth) solar_system.add_element(mars) moon = Space('Moon') earth.add_element(moon) lunohod = Space('Lunohod') moon.add_element(lunohod) phobos = Space('Phobos') phobos2 = Space('Phobos') phobos3 = Space('Phobos') deimos = Space('Deimos') mars.add_element(phobos) mars.add_element(phobos2) mars.add_element(phobos3) mars.add_element(deimos) phobos.detach_from_parent() earth.add_element(phobos)
from __future__ import division, print_function import numpy as np from mayavi import mlab from Space import Space from Space.Figure.Sphere import * from Space.Curve.Parametric import Arc from Space.Coordinates import Cartesian import Space_visualization as Visual solar_system = Space('Solar System') sun = Sphere('Sun', r_outer=0.2) mercury = Space('Mercury', Cartesian(origin=[0.5, 0.5, 0.5])) venus = Space('Venus', Cartesian(origin=[1, 1, 1])) earth_orbit = Arc(name='Earth orbit', a=1, b=2, start=0, stop=2*np.pi, right=True) earth = Sphere(name='Earth', coordinate_system=Cartesian(origin=[1.5, 1.5, 1.5]), r_outer=0.02) mars = Space('Mars', Cartesian(origin=[2, 2, 2])) solar_system.add_element(sun) #solar_system.add_element(mercury) #solar_system.add_element(venus) solar_system.add_element(earth_orbit) solar_system.add_element(earth) #solar_system.add_element(mars) #moon = SphericalCone('Moon', Cartesian(origin=[0.2, 0.2, 0.2]), # r_inner=0.5, r_outer=1.0, theta=np.pi/6)
def create(self): self.cards = Card.create_deck() self.board = Space.create_board()
def simulate(self, project_id=str(), load=False, save=True, number_of_iterations=int(), number_of_particles=int(), dimension=int()): info = dict() load_and_continue = load space = Space(project_id=project_id) timer = Timer() timer.start() # Pokracuj od poslednej ulozenej polohy castic if load_and_continue: info = json.load(open(project_id, 'r')) space.particles = Particles.load( project_id=info['project_id'], simulation_number=info['simulation_number']) space.set_dimension(dimension=info['dimension']) space.simulation_number = info['simulation_number'] # Novy projekt if not load_and_continue: info = dict() info['number_of_particles'] = int(number_of_particles) info['dimension'] = dimension info['project_id'] = project_id # info['multisource'] = True # info['sources_distance'] = 10 # info['particle_insertion'] = {'start': 0, 'end': 499, 'number': 200, 'position':[5,0,0]} space.set_dimension(dimension=info['dimension']) space.add_particles(number=int(info['number_of_particles']), position=[-5, -2, 0]) space.walls = Walls() space.walls.add(x=-15, x_orientation=-1) space.walls.add(x=15, x_orientation=1) space.walls.add(y=15, y_orientation=1) space.walls.add(y=-15, y_orientation=-1) # space.wind = Wind() # space.wind.set(y_axis=1,x_axis=1, amplitude=0.05) # space.add_particles(number=int(info['number_of_particles']), position=[-3, -3, 0]) # space.add_particles(number=int(info['number_of_particles']), position=[3, 3, 0]) # space.add_particles(number=int(info['number_of_particles']), position=[-6, 6, 0]) # space.add_particles(number=int(info['number_of_particles'])*10, position=[6, -6, 0]) space.project_id = project_id # diffusion.space.wind.activate(wind_type='ConstantWind') # diffusion.space.wind.active_types['ConstantWind'].set(x_axis=5, amplitude=0.1) # # diffusion.space.walls.add() # diffusion.space.walls.pole[0].set(x_min=30, x_max=int(1e6)) # Core functionality - simulation with saving particles self.save_lattice(project_id=project_id, particles=space.particles, simulation_number=space.simulation_number) if save: space.simulate(n=number_of_iterations, timer=timer) if not save: for i in range(number_of_iterations): print(i) # if i < 500: # space.simulate(n=1, timer=timer, save_particles=False, step_particles_insertion=500) # else: # if i == 500: # space.wind = None space.simulate(n=10, timer=timer, save_particles=False, step_particles_insertion=0) self.save_lattice(project_id=project_id, particles=space.particles, simulation_number=space.simulation_number) info['simulation_number'] = space.simulation_number print(info) # Saving last state json.dump(info, open(project_id, 'w')) # Just final info timer.stop() print(timer)
def __init__(self): Space.__init__(self) self.avatars = {} self.lastGateCount = 0
from __future__ import division, print_function import numpy as np from Space.Coordinates import Cartesian from Space import Space from Space.Figure import Figure from Space.Curve import Curve from Space.Field import Field coordinate_system = Cartesian(origin=np.array([0, 0, 0]), euler_angles_convention='canova') print(coordinate_system) my_space = Space('My new space', coordinate_system=coordinate_system) print(my_space) my_figure = Figure('My figure') my_space.add_element(my_figure) print(my_figure) my_curve = Curve('My curve') my_space.add_element(my_curve) print(my_curve) my_field = Field('My Field', field_type='My Field type') my_figure.add_element(my_field) print(my_field)