def notifyCollided(self, other): if self.__direction == "Down": block = Block.Block( self.__blocks[len(self.__blocks) - 1].getX(), self.__blocks[len(self.__blocks) - 1].getY() - self.__blocks[len(self.__blocks) - 1].getSize(), self.__blocks[len(self.__blocks) - 1].getColor(), self.__blocks[len(self.__blocks) - 1].getSize()) elif self.__direction == "Up": block = Block.Block( self.__blocks[len(self.__blocks) - 1].getX(), self.__blocks[len(self.__blocks) - 1].getY() + self.__blocks[len(self.__blocks) - 1].getSize(), self.__blocks[len(self.__blocks) - 1].getColor(), self.__blocks[len(self.__blocks) - 1].getSize()) elif self.__direction == "Left": block = Block.Block( self.__blocks[len(self.__blocks) - 1].getX() + self.__blocks[len(self.__blocks) - 1].getSize(), self.__blocks[len(self.__blocks) - 1].getY(), self.__blocks[len(self.__blocks) - 1].getColor(), self.__blocks[0].getSize()) elif self.__direction == "Right": block = Block.Block( self.__blocks[len(self.__blocks) - 1].getX() - self.__blocks[len(self.__blocks) - 1].getSize(), self.__blocks[len(self.__blocks) - 1].getY(), self.__blocks[len(self.__blocks) - 1].getColor(), self.__blocks[0].getSize()) self.__blocks.insert(len(self.__blocks), block)
def doOneFrame(self): self.__blocks.pop(len(self.__blocks) - 1) if self.__direction == "Up": block = Block.Block( self.__blocks[0].getX(), self.__blocks[0].getY() - self.__blocks[0].getSize(), self.__blocks[0].getColor(), self.__blocks[0].getSize()) elif self.__direction == "Down": block = Block.Block( self.__blocks[0].getX(), self.__blocks[0].getY() + self.__blocks[0].getSize(), self.__blocks[0].getColor(), self.__blocks[0].getSize()) elif self.__direction == "Right": block = Block.Block( self.__blocks[0].getX() + self.__blocks[0].getSize(), self.__blocks[0].getY(), self.__blocks[0].getColor(), self.__blocks[0].getSize()) elif self.__direction == "Left": block = Block.Block( self.__blocks[0].getX() - self.__blocks[0].getSize(), self.__blocks[0].getY(), self.__blocks[0].getColor(), self.__blocks[0].getSize()) if block.getX() < 0 or block.getX() > self.__gridSize: block.setX(self.__gridSize - block.getX()) block.setY(block.getY()) if block.getY() < 0 or block.getY() > self.__gridSize: block.setY(self.__gridSize - block.getY()) block.setX(block.getX()) self.__blocks.insert(0, block)
def make_next_block(prev_block, data=None): index = prev_block.index + 1 timestamp = datetime.datetime.now() next_hash = prev_block.hash if not data: data = {'proof': prove_work(prev_block.data['proof'])} return Block(index, timestamp, data, next_hash)
def make_genesis_block(): genesis = Block(index=0, timestamp=datetime.datetime.now(), data={'proof': 1}, prev_hash='0') print(f'Genesis block has been added to blockchain [ length: 1 ]\n' f'Hash: {genesis.hash}\n') return genesis
def mine(self): """ Mine a new block featuring the latest incoming messages. This method waits for enough messages to be received from the server, then forms them into blocks, mines the block, adds the block to the blockchain, and prepares the block to be broadcast by the server. The mining of a block may be interrupted by a superceding add_block_str() call. In this case the miner should do its best to move on to mine another block and not lose any messages it was previously attempting to mine. This process repeats forever, and this function never runs. This function is called in blockchain_bbs.py as a new thread. """ self.log.debug("Miner %s : Mining on thread %d", self.miner_id[:6], threading.get_ident() % 10000) while True: # Make sure we have enough new messages in the queue if self.get_message_queue_size() < MSGS_PER_BLOCK: continue self.log.info("Thread: %d - "+ RED +"Starting to mine a block!" + NC, threading.get_ident() % 10000) with self.lock: if self.message_list is None: self.message_list = [self.message_queue.pop(0) for i in range(MSGS_PER_BLOCK)] while self.mining_flag != CONTINUE_MINING or self.latest_block is None: pass while self.mining_flag == CONTINUE_MINING: nonce = hexlify(str(random.getrandbits(NONCE_BIT_LENGTH)).encode()).decode() # Parent hash is 64 '0's if we are mining the genesis block parent_hash = self.latest_block.block.block_hash if self.latest_block is not None else '0' * 36 block = Block(nonce=nonce, parent=parent_hash, create_time=time.time(), miner=self.miner_id, posts=self.message_list) if block.verify_pow(): self.log.info("Thread: %d - " + GREEN + "Mined a block !!!" + NC + "\n", threading.get_ident() % 10000) self.mined_block = block self._add_block(block, write_to_ledger=True, mined_ourselves=True) self.message_list = None break if self.mining_flag == GIVEN_BLOCK: self.log.debug("Mining interrupted - given a block from a peer") self._add_all_to_message_queue(self.message_list) self.mining_flag = CONTINUE_MINING
def __init__(self, rows): pygame.init() pygame.font.init() height = 500 width = 500 self._rows = rows self.__grid = GameGrid.GameGrid(rows) self.__wn = pygame.display.set_mode((height, width)) blockSize = height / rows block1 = Block.Block(rows / 2 * blockSize, rows / 2 * blockSize, "white", blockSize) block2 = Block.Block(rows / 2 * blockSize + blockSize, rows / 2 * blockSize, "white", blockSize) snakeBlocks = [block1, block2] self.__snake = Snake.Snake(snakeBlocks, width) self.__apple = Apple.Apple( int(random.random() * width / blockSize) * blockSize, int(random.random() * width / blockSize) * blockSize, blockSize, width) self.__score = Score.Score(width - blockSize * 1.2, 0, "black", "") self.__highScore = Score.Score(0, 0, "black", "High: ")
def automine(): # determine a reference point to begin computing latest_block = blockchain[len(blockchain) - 1] latest_proof = latest_block.data['proof'] # once we find a proof, we can compute a block # (and transact that client an amount) proof = prove_work(latest_proof) node_transactions.append({ 'from': 'network', 'to': config.CLIENT_ADDRESS, 'amount': 1 }) # and collect the elements needed to generate and apply the next block! new_index = latest_block.index + 1 new_timestamp = datetime.datetime.now() new_data = {'proof': proof, 'transactions': node_transactions} latest_hash = latest_block.hash print(new_data) new_block = Block(new_index, new_timestamp, new_data, latest_hash) blockchain.append(new_block) # provide a descriptive response resp = json.dumps({ 'index': new_index, 'timestamp': str(new_timestamp), 'data': new_data, 'last_hash': latest_hash }) # before concluding the request, # flush out the local transaction cache node_transactions[:] = [] return resp + '\n'
def UniformSlab3D(material, substrate_material=1, numbands=8, k_interpolation=11, resolution=32, mesh_size=3, supercell_z=6, runmode='sim', num_processors=2, convert_field_patterns=True, job_name_suffix='', bands_title_appendix=''): """Create a 3D MPB simulation of a uniform slab with thickness 1 in air. *material* is the material of the slab, *substrate_material* is the material of the substrate below the slab. *material* and *substrate_material* can be strings (e.g. SiN, 4H-SiC-anisotropic_c_in_z; defined in data.py) or just the epsilon value (float); By default, *substrate_material* is 1, i.e. air. *numbands* is the number of bands to calculate. *k_interpolation* is the number of k-vectors between every two of the used high symmetry points Gamma, X, M and Gamma again, so the total number of simulated k-vectors will be 3*k_interpolation + 4. *resolution* and *mesh_size* are as described in MPB documentation. *supercell_z* is the height of the supercell in units of lattice constant; *runmode* can be one of the following: '' : just create and return the simulation object 'ctl' : create the sim object and save the ctl file 'sim' (default): run the simulation and do all postprocessing 'postpc' : do all postprocessing; simulation should have run before! 'display': display all pngs done during postprocessing. This is the only mode that is interactive. *convert_field_patterns* indicates whether field pattern h5 files should be converted to png (only when postprocessing). Optionally specify a *job_name_suffix* (appendix to the folder name etc.) which will be appended to the jobname created automatically from the most important parameters. Specify *bands_title_appendix*, which will be added to the title of the bands diagram. """ mat = Dielectric(material) smat = Dielectric(substrate_material) objects = [ Block( x=0, y=0, z=0, material=mat, #make it bigger than computational cell, just in case: size=(1, 2, 1)) ] if smat.epsilon != 1.0: objects.append( Block(x=0, y=0, z=-0.5 - (supercell_z - 1) / 4.0, material=smat, size=(1, 2, (supercell_z - 1) / 2.0))) geom = Geometry( # I want to hide that there is actually a periodicity in x. The # bands are always cut of at kvec_x=0.5 and folded back. If I # decrease the size in x (e.g. by 1/8), the kvec_x at 0.5 will # actually be greater (here, 0.5 * 8). This is true, as can also # be seen by looking at k_magnitude in the simulation output. To # make sure there is no mixing between bands, I will only look # at kvec_x up to 0.25. At kvec=(1/8, 0, 0), the band # frequencies are the same as it would be at k_x*d/pi=1 (d is # slab thickness), when we had no periodic boundaries (compare # Sakoda - Optical Properties of Photonic Crystals 2nd Edition # 2005, page 177, Fig. 8.2 - actually, the frequencies are not # _exactly_ the same, why? Wrong refractive index?): width=0.125, height=1, depth=supercell_z, triangular=False, objects=objects) # Just below kx=0.5, the bands still mix due to the periodicity. # To hide this, just cut at kx=0.25: max_kx = 0.25 # I actually want to see TM-like and TE-like modes, like described # in Joannopoulos et al., Photonic Crystals; Molding the Flow of Light, # Princeton University Press 2008: # Fig. 7 on page 130 & text on pages 128 and 136. # I try to look everywhere in kspace to find them, but it seems there # are only pure TE and TM modes. # (These ...-like modes are neither mentioned in # Sakoda - Optical Properties of Photonic Crystals 2nd Edition, # Springer 2005,pages 176ff.) kspace = KSpace( points_list=[ (0, 0, 0), (max_kx, 0, 0), # Gamma -> +x (max_kx, 0, 0.5), # +x -> shifted +x (no bands change) (0, 0, 0.5), (0, 0, 0), # -> +z -> Gamma (max_kx, 0, 0.5) # Gamma -> shifted +x (same as Gamma->+x) ], k_interpolation=k_interpolation) # points of interest: (output mode patterns at these points) poi = [(0, 0, 0), (0.125, 0, 0), (0.25, 0, 0), (0.25, 0, 0.25), (0.25, 0, 0.5), (0.125, 0, 0.5), (0, 0, 0.5), (0, 0, 0.25), (0.125, 0, 0.25)] band_funcs = ('\n display-zparities display-yparities' + ''.join([('\n (output-at-kpoint (vector3 %s) ' 'fix-efield-phase output-efield output-hfield)') % ' '.join(str(c) for c in vec) for vec in poi])) # material name for jobname and draw_bands_title: # note: quick & dirty. if smat.epsilon == 1.0: matname = mat.name else: matname = '{0}_on_{1:.3f}'.format(mat.name, smat.epsilon) jobname = 'Slab3D_{0}_res{1}_supcell{2}'.format(matname, resolution, supercell_z).replace( '.', 'p') sim = Simulation(jobname=jobname + job_name_suffix, geometry=geom, kspace=kspace, numbands=numbands, resolution=resolution, mesh_size=mesh_size, initcode=defaults.default_initcode, postcode='', runcode='(run %s)\n' % band_funcs, clear_subfolder=runmode.startswith('s') or runmode.startswith('c')) draw_bands_title = ('Uniform slab; ' '{0}, resolution={1}, supercell_z={2}'.format( matname, resolution, supercell_z) + bands_title_appendix) ### some monkey patching: >:O <-evil monkey # only make cross-section png: defaults.epsh5topng_call_3D = defaults.epsh5topng_call_3D_cross_sect # export field patterns along another slice (default: -0z0) # NOTE, for mpbdata_call: # -T because we use mpi-mpb, then -y is actually for -x defaults.mpbdata_call = ('mpb-data -T -rn%(resolution)s ' '-y8 ' '-o%(output_file)s ' '%(h5_file)s') # For the individual field components to be comparable, don't use # automatic scaling, but set range with -m and -M: rnge = 1 defaults.fieldh5topng_call_3D = ( 'h5topng -0y0 -S3 -Zcbluered -C%(eps_file)s -m-{0} -M{0} ' '-o%(output_file)s %(h5_file)s'.format(rnge)) defaults.fieldh5topng_call_3D_no_ovl = ( 'h5topng -0y0 -S3 -Zcbluered -m-{0} -M{0} ' '-o%(output_file_no_ovl)s %(h5_file)s'.format(rnge)) return do_runmode(sim, runmode, num_processors, draw_bands_title, plot_crop_y=1.0, convert_field_patterns=convert_field_patterns, field_pattern_plot_k_selection=None, x_axis_hint=11, field_pattern_plot_filetype='pdf')
def __init__(self): self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.freetype.init() #to check if current action is pouring #self.rotate = False #self.rotate_count = 200 # setting background color self.bg_color = pygame.Color('white') #pygame.Color('grey12') self.light_grey = (200, 200, 200) self.dark_grey = (120, 120, 120) self.groundline = (0, 0, 0) self.maize = pygame.Color(255, 203, 5) self.blue = pygame.Color(0, 39, 76) self.table_color = self.blue #pygame.Color(202, 164, 114) # loading background # self.background = pygame.image.load('maize_blue.jpg') self.gui_list = [] #to collect all the object in the gui self.name2obj = {} #a dict to help to convert object name to object self.drawers_list = [ ] # a list to collect all the drawer names for closing # define drawers constants and locations: self.drawer_height = 120 self.drawer_width = 80 self.drawer_front = SCREEN_HEIGHT - 50 - 10 self.drawer_bottom = self.drawer_front + self.drawer_height self.drawer_pos_coffee = 115 self.drawer_pos_cup = 215 self.drawer_pos_spoon = 15 # spoon height = 100 self.spoon = Spoon(self.blue, 5, height, self.drawer_pos_spoon + self.drawer_width / 2, self.drawer_bottom - height - 10) # cup cup_height = 60 cup_width = 40 self.cup = Cup( self.blue, cup_width, cup_height, self.drawer_pos_cup + self.drawer_width / 2 - cup_width / 2, self.drawer_bottom) self.contain_color = self.bg_color self.coffee_color = self.bg_color # coffee bag_height = 80 bag_width = 50 self.coffee_bag = Block(self.blue, bag_width, bag_height, self.drawer_pos_coffee+self.drawer_width/2-bag_width/2, \ self.drawer_bottom-bag_height, addText=True) self.coffee_bag.addText2Block('Coffee') # drawer1 self.drawer1 = Drawer(self.maize, self.drawer_width, self.drawer_height, self.drawer_pos_coffee, self.drawer_front, self.coffee_bag) self.gui_list.append((self.maize, self.drawer1.object, self.drawer1)) #self.gui_list.append(('black', self.drawer1.bottom, self.drawer1)) self.name2obj['drawer1'] = self.drawer1 self.drawers_list.append('drawer1') # drawer2 self.drawer2 = Drawer(self.maize, self.drawer_width, self.drawer_height, self.drawer_pos_cup, self.drawer_front, self.cup) self.gui_list.append((self.maize, self.drawer2.object, self.drawer2)) self.name2obj['drawer2'] = self.drawer2 self.drawers_list.append('drawer2') # drawer3 self.drawer3 = Drawer(self.maize, self.drawer_width, self.drawer_height, self.drawer_pos_spoon, self.drawer_front, self.spoon) self.gui_list.append((self.maize, self.drawer3.object, self.drawer3)) self.name2obj['drawer3'] = self.drawer3 self.drawers_list.append('drawer3') #appending object in the list after drawer #appending coffee self.gui_list.append( (self.blue, self.coffee_bag.object, self.coffee_bag)) self.name2obj['coffee'] = self.coffee_bag #appending cup self.gui_list.append(('dummy_color', self.cup.object, self.cup)) self.gui_list.append(('dummy_coffee', self.cup.coffee, self.cup)) self.gui_list.append((self.cup.color, self.cup.left, self.cup)) self.gui_list.append((self.cup.color, self.cup.right, self.cup)) self.gui_list.append((self.cup.color, self.cup.bottom, self.cup)) self.name2obj['cup'] = self.cup #spoon self.gui_list.append((self.spoon.color, self.spoon.shaft, self.spoon)) self.gui_list.append((self.spoon.color, self.spoon.head, self.spoon)) self.name2obj['spoon'] = self.spoon # table self.table = pygame.Rect(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50) self.gui_list.append((self.table_color, self.table, None)) #faucet faucet_ul_x, faucet_ur_x = SCREEN_WIDTH - 150, SCREEN_WIDTH - 50 faucet_bl_x, faucet_br_x = SCREEN_WIDTH - 150, SCREEN_WIDTH - 50 faucet_ul_y, faucet_ur_y = SCREEN_HEIGHT - 50 - 200, SCREEN_HEIGHT - 50 - 200 faucet_bl_y, faucet_br_y = SCREEN_HEIGHT - 50, SCREEN_HEIGHT - 50 self.faucet_coordinates = [(faucet_ul_x, faucet_ul_y), (faucet_ur_x, faucet_ur_y), (faucet_br_x, faucet_br_y), (faucet_br_x - 30, faucet_br_y), (faucet_br_x - 30, faucet_ur_y + 30), (faucet_ul_x + 30, faucet_ul_y + 30), (faucet_ul_x + 30, faucet_ul_y + 40), (faucet_ul_x, faucet_ul_y + 40)] self.color_table = { 'dummy_color': self.contain_color, 'dummy_coffee': self.coffee_color }
def TriHolesSlab3D_Waveguide(material, radius, thickness, mode='zeven', numbands=8, k_steps=17, supercell_size=5, supercell_z=6, resolution=32, mesh_size=7, ydirection=False, first_row_longitudinal_shift=0, first_row_transversal_shift=0, first_row_radius=None, second_row_longitudinal_shift=0, second_row_transversal_shift=0, second_row_radius=None, runmode='sim', num_processors=2, projected_bands_folder='../projected_bands_repo', plot_complete_band_gap=False, save_field_patterns_kvecs=list(), save_field_patterns_bandnums=list(), convert_field_patterns=False, job_name_suffix='', bands_title_appendix='', plot_crop_y=False, field_pattern_plot_k_selection=()): """Create a 3D MPB Simulation of a slab with a triangular lattice of holes, with a waveguide along the nearest neighbor direction, i.e. Gamma->K direction. The simulation is done with a cubic super cell. Before the waveguide simulation, additional simulations of the unperturbed structure will be run for projected bands data, if these simulations where not run before. :param material: can be a string (e.g. SiN, 4H-SiC-anisotropic_c_in_z; defined in data.py) or just the epsilon value (float) :param radius: the radius of holes in units of the lattice constant :param thickness: slab thickness in units of the lattice constant :param mode: the mode to run. Possible are 'zeven' and 'zodd'. :param numbands: number of bands to calculate :param k_steps: number of k steps along the waveguide direction between 0 and 0.5 to simulate. This can also be a list of the explicit k values (just scalar values for component along the waveguide axis) to be simulated. :param supercell_size: the length of the supercell perpendicular to the waveguide, in units of sqrt(3) times the lattice constant. If it is not a odd number, one will be added. :param supercell_z: the height of the supercell in units of the lattice constant :param resolution: described in MPB documentation :param mesh_size: described in MPB documentation :param ydirection: set this if the waveguide should point along y, otherwise (default) it will point along x. Use the default if you want to use yparity data. :param first_row_longitudinal_shift: shifts the holes next to the waveguide by this amount, parallel to the waveguide direction. :param first_row_transversal_shift: shifts the holes next to the waveguide by this amount, perpendicular to the waveguide direction. :param first_row_radius: The radius of the holes next to the waveguide. If None (default), use radius. :param second_row_longitudinal_shift: shifts the holes in the second row next to the waveguide by this amount, parallel to the waveguide direction :param second_row_transversal_shift: shifts the holes in the second row next to the waveguide by this amount, perpendicular to the waveguide direction :param second_row_radius: The radius of the holes in the second row next to the waveguide. If None (default), use radius. :param runmode: can be one of the following: '' : just create and return the simulation object 'ctl' : create the sim object and save the ctl file 'sim' (default): run the simulation and do all postprocessing 'postpc' : do all postprocessing; simulation should have run before! 'display': display all pngs done during postprocessing. This is the only mode that is interactive. :param num_processors: number of processors used during simulation :param projected_bands_folder: the path to the folder which will contain the simulations of the unperturbed PhC, which is needed for the projections perpendicular to the waveguide direction. If the folder contains simulations run before, their data will be reused. :param plot_complete_band_gap: If this is False, the band gap will be a function of the k component along the waveguide. For each k, a simulation with unperturbed photonic crystal will be run to get the data. If this is True, only one unperturbed simulation will be run to find the full direction independent bandgap. :param save_field_patterns_kvecs: a list of k-vectors (3-tuples), which indicates where field pattern h5 files are generated during the simulation (only at bands in save_field_patterns_bandnums) :param save_field_patterns_bandnums: a list of band numbers (int, starting at 1), which indicates where field pattern h5 files are generated during the simulation (only at k-vectors in save_field_patterns_kvecs) :param convert_field_patterns: indicates whether field pattern h5 files should be converted to png (only when postprocessing) :param job_name_suffix: Optionally specify a job_name_suffix (appendix to the folder name etc.) which will be appended to the jobname created automatically from the most important parameters. :param bands_title_appendix: will be added to the title of the bands diagram. :param plot_crop_y: the band diagrams are automatically cropped before the last band if plot_crop_y is True, alternatively use plot_crop_y to specify the max. y-value where the plot will be cropped. :return: the Simulation object """ mat = Dielectric(material) # first, make sure all data for projected bands exist, otherwise # start their simulations. unperturbed_jobname = 'TriHolesSlab_{0}_r{1:03.0f}_t{2:03.0f}'.format( mat.name, radius * 1000, thickness * 1000) # look here for old simulations, and place new ones there: repo = path.abspath( path.join(path.curdir, projected_bands_folder, unperturbed_jobname)) # create path if not there yet: if not path.exists(path.abspath(repo)): makedirs(path.abspath(repo)) # these k points will be simulated (along waveguide): if isinstance(k_steps, (int, float)): k_steps = int(k_steps) k_points = np.linspace(0, 0.5, num=k_steps, endpoint=True) else: k_points = np.array(k_steps) # This list will be forwarded later to this defect simulation's # post-process. It contains the folder paths of unperturbed # simulations for each k-vec of this simulation (or only one simulation, # if the plotted band gap does not change from k-vec to k-vec): project_bands_list = [] if plot_complete_band_gap: if mode == 'zeven': # We only need a simulation of the first two bands at the M # and the K point to get the band gap. # first, see if we need to simulate: jobname_suffix = '_for_gap' jobname = unperturbed_jobname + jobname_suffix project_bands_list.append(path.join(repo, jobname)) range_file_name = path.join(repo, jobname, jobname + '_' + mode + '_ranges.csv') if not path.isfile(range_file_name): # does not exist, so start simulation: log.info('unperturbed structure not yet simulated for ' 'band gap. Running now...') kspace = KSpace(points_list=[(0, 0.5, 0), ('(/ -3)', '(/ 3)', 0)], k_interpolation=0, point_labels=['M', 'K']) sim = TriHolesSlab3D( material=material, radius=radius, thickness=thickness, custom_k_space=kspace, numbands=3, # 3 so the band plot looks better ;) resolution=resolution, mesh_size=mesh_size, supercell_z=supercell_z, runmode='sim' if runmode.startswith('s') else '', num_processors=num_processors, containing_folder=repo, save_field_patterns=False, convert_field_patterns=False, job_name_suffix=jobname_suffix, bands_title_appendix=', for band gap', modes=[mode]) if not sim: log.error( 'an error occurred during simulation of unperturbed ' 'structure. See the .out file in {0}'.format( path.join(repo, jobname))) return # Now, the _ranges.csv file is wrong, because we did not # simulate the full K-Space, especially Gamma is # missing. Correct the ranges so the first band starts # at 0 and the second band is the last band and goes to # a very high value. This way, there is only the band # gap left between the first and second continuum bands. # Load the _ranges.csv file to get the band gap: ranges = np.loadtxt(range_file_name, delimiter=',', ndmin=2) # tinker: ranges[0, 1] = 0 ranges[1, 2] = ranges[1, 2] * 100 # save file again, drop higher bands: np.savetxt(range_file_name, ranges[:2, :], header='bandnum, min, max', fmt=['%.0f', '%.6f', '%.6f'], delimiter=', ') else: # For high refractive indices and big radius, there are some # small gaps for TM modes. But we need to simulate more # bands and more k-points than for the TE modes. This is # especially difficult (or even impossible?), since # quasi-guided PhC bands (which narrow the band gap) are # hidden by continuum modes above the light line in 3D. # I don't need it, so it is not implemented yet: log.warning('plot_complete_band_gap not implemented for {0}' ' modes yet.'.format(mode)) else: # Note: in the following, I use a triangular lattice, which is # orientated such that the Gamma->K direction points towards y # in cartesian coordinates. If ydirection is False, it does not # matter, because the projected bands stay the same. # In the triangular lattice, in the basis of its reciprocal # basis vectors, this is the K' point, i.e. die boundary of the # first brillouin zone in the rectangular lattice, onto which we # need to project (see also : Steven G. Johnson et al., "Linear # waveguides in photonic-crystal slabs", Phys. Rev. B, Vol. 62, # Nr.12, 8212-8222 (2000); page 8216 & Fig. 8): rectBZ_K = np.array((0.25, -0.25)) # the M point in the triangular lattice reciprocal basis, which # points along +X (perpendicular to a waveguide in k_y # direction): (note: if k_y is greater than 1/3, we leave the # 1st BZ in +x direction. But this is OK and we calculate it # anyway, because it does not change the projection. If we want # to optimize calculation time some time, we could limit this.) triBZ_M = np.array((0.5, 0.5)) # now, see if we need to simulate: for ky in k_points: jobname_suffix = '_projk{0:06.0f}'.format(ky * 1e6) jobname = unperturbed_jobname + jobname_suffix project_bands_list.append(path.join(repo, jobname)) range_file_name = path.join(repo, jobname, jobname + '_' + mode + '_ranges.csv') if not path.isfile(range_file_name): # does not exist, so start simulation: log.info('unperturbed structure not yet simulated at ' 'k_wg={0}. Running now...'.format(ky)) kspace = KSpace( points_list=[ rectBZ_K * ky * 2, rectBZ_K * ky * 2 + triBZ_M ], k_interpolation=15, ) sim = TriHolesSlab3D( material=material, radius=radius, thickness=thickness, custom_k_space=kspace, numbands=defaults.num_projected_bands, resolution=resolution, supercell_z=supercell_z, mesh_size=mesh_size, runmode='sim' if runmode.startswith('s') else '', num_processors=num_processors, containing_folder=repo, save_field_patterns=False, convert_field_patterns=False, job_name_suffix=jobname_suffix, bands_title_appendix=', at k_wg={0:0.3f}'.format(ky), modes=[mode]) if not sim: log.error( 'an error occurred during simulation of unperturbed ' 'structure. See the .out file in {0}'.format( path.join(repo, jobname))) return # If a shift is used, inversion symmetry is broken: if ((first_row_longitudinal_shift or second_row_longitudinal_shift) and 'mpbi' in defaults.mpb_call): log.info('default MPB to use includes inversion symmetry: ' '{0}. '.format(defaults.mpb_call) + 'Shift of holes specified, which breaks inv. symmetry. ' 'Will fall back to MPB without inv. symm.: {0}'.format( defaults.mpb_call.replace('mpbi', 'mpb'))) defaults.mpb_call = defaults.mpb_call.replace('mpbi', 'mpb') # make it odd: if supercell_size % 2 == 0: supercell_size += 1 # half of the supercell (floored): sch = int(supercell_size / 2) # Create geometry and add objects. objects = get_triangular_phc_waveguide_air_rods( radius=radius, supercell_size=supercell_size, ydirection=ydirection, first_row_longitudinal_shift=first_row_longitudinal_shift, first_row_transversal_shift=first_row_transversal_shift, first_row_radius=first_row_radius, second_row_longitudinal_shift=second_row_longitudinal_shift, second_row_transversal_shift=second_row_transversal_shift, second_row_radius=second_row_radius) if ydirection: geom = Geometry( width='(* (sqrt 3) %i)' % supercell_size, height=1, depth=supercell_z, triangular=False, objects=([ Block( x=0, y=0, z=0, material=mat, # make it bigger than computational cell, just in case: size=('(* (sqrt 3) %i)' % (supercell_size + 1), 2, thickness)) ] + objects)) kspaceW1 = KSpace( points_list=[(0, ky, 0) for ky in k_points], k_interpolation=0, ) else: geom = Geometry( width=1, height='(* (sqrt 3) %i)' % supercell_size, depth=supercell_z, triangular=False, objects=([ Block( x=0, y=0, z=0, material=mat, # make it bigger than computational cell, just in case: size=(2, '(* (sqrt 3) %i)' % (supercell_size + 1), thickness)) ] + objects)) kspaceW1 = KSpace( points_list=[(kx, 0, 0) for kx in k_points], k_interpolation=0, ) jobname = 'TriHolesSlab_W1_{0}_r{1:03.0f}_t{2:03.0f}'.format( mat.name, radius * 1000, thickness * 1000) if mode == 'zeven': outputfuncs = defaults.output_funcs_te else: outputfuncs = defaults.output_funcs_tm runcode = '' if defaults.newmpb: runcode = '(optimize-grid-size!)\n\n' if save_field_patterns_bandnums and save_field_patterns_kvecs: runcode += ( ';function to determine whether an item x is member of list:\n' '(define (member? x list)\n' ' (cond (\n' ' ;false if the list is empty:\n' ' (null? list) #f )\n' ' ;true if first item (car) equals x:\n' ' ( (eqv? x (car list)) #t )\n' ' ;else, drop first item (cdr) and make recursive call:\n' ' ( else (member? x (cdr list)) )\n' ' ))\n\n' + '(define output-bands-list (list {0}))\n\n'.format( ' '.join(map(str, save_field_patterns_bandnums))) + '(define (output-func bnum)\n' ' (if (member? bnum output-bands-list)\n' ' (begin\n' + ''.join(12 * ' ' + '({0} bnum)\n'.format(func) for func in outputfuncs) + ' )\n' ' ))\n\n' '(run-{0} {1})\n'.format( mode, defaults.default_band_func(save_field_patterns_kvecs, 'output-func')) + '(print-dos 0 1.2 121)\n\n') else: runcode += ('(run-{0} {1})\n'.format( mode, defaults.default_band_func([], None)) + '(print-dos 0 1.2 121)\n\n') sim = Simulation(jobname=jobname + job_name_suffix, geometry=geom, kspace=kspaceW1, numbands=numbands, resolution=resolution, mesh_size=mesh_size, initcode=defaults.default_initcode, postcode='', runcode=runcode, clear_subfolder=runmode.startswith('s') or runmode.startswith('c')) draw_bands_title = ( 'Hex. PhC slab W1; {0}, thickness={1:0.3f}, radius={2:0.3f}'.format( mat.name, geom.objects[0].size[2], radius) + bands_title_appendix) return do_runmode( sim, runmode, num_processors, draw_bands_title, plot_crop_y=plot_crop_y, convert_field_patterns=convert_field_patterns, field_pattern_plot_k_selection=field_pattern_plot_k_selection, field_pattern_plot_filetype=defaults.field_dist_filetype, x_axis_hint=[5, "{1}" if ydirection else "{0}"], project_bands_list=project_bands_list, color_by_parity='y')
def TriHolesSlab3D(material, radius, thickness, numbands=8, k_interpolation=11, resolution=32, mesh_size=7, supercell_z=6, runmode='sim', num_processors=2, save_field_patterns=True, convert_field_patterns=True, containing_folder='./', job_name_suffix='', bands_title_appendix='', custom_k_space=None, modes=('zeven', 'zodd'), substrate_material=None): """Create a 3D MPB Simulation of a slab with a triangular lattice of holes. :param material: can be a string (e.g. SiN, 4H-SiC-anisotropic_c_in_z; defined in data.py) or just the epsilon value (float) :param radius: the radius of holes in units of the lattice constant :param thickness: slab thickness in units of the lattice constant :param numbands: number of bands to calculate :param k_interpolation: number of the k-vectors between every two of the used high symmetry points Gamma, M, K and Gamma again, so the total number of simulated k-vectors will be 3*k_interpolation + 4 :param resolution: described in MPB documentation :param mesh_size: described in MPB documentation :param supercell_z: the height of the supercell in units of the lattice constant :param runmode: can be one of the following: '' : just create and return the simulation object 'ctl' : create the sim object and save the ctl file 'sim' (default): run the simulation and do all postprocessing 'postpc' : do all postprocessing; simulation should have run before! 'display': display all pngs done during postprocessing. This is the only mode that is interactive. :param num_processors: number of processors used during simulation :param save_field_patterns: indicates whether field pattern h5 files are generated during the simulation (at points of high symmetry) :param convert_field_patterns: indicates whether field pattern h5 files should be converted to png (only when postprocessing) :param containing_folder: the path to the folder which will contain the simulation subfolder. :param job_name_suffix: Optionally specify a job_name_suffix (appendix to the folder name etc.) which will be appended to the jobname created automatically from the most important parameters. :param bands_title_appendix: will be added to the title of the bands diagram. :param custom_k_space: By default, KSpaceTriangular with k_interpolation interpolation steps are used. Provide any KSpace object here to customize this. k_interpolation will then be ignored. :param modes: a list of modes to run. Possible are 'zeven', 'zodd' or '' (latter meaning no distinction). Default: ['zeven', 'zodd'] :param substrate_material: the material of an optional substrate, see param material. Holes will not be extended into the substrate. Default: None, i.e. the substrate is air. :return: the Simulation object """ mat = Dielectric(material) geom = Geometry( width=1, height=1, depth=supercell_z, triangular=True, objects=[ Block( x=0, y=0, z=0, material=mat, #make it bigger than computational cell, just in case: size=(2, 2, thickness)), Rod(x=0, y=0, material='air', radius=radius) ]) if substrate_material: geom.add_substrate(Dielectric(substrate_material), start_at=-0.5 * thickness) if isinstance(custom_k_space, KSpace): kspace = custom_k_space else: kspace = KSpaceTriangular(k_interpolation=k_interpolation, use_uniform_interpolation=defaults.newmpb) # points of interest: (output mode patterns at these points) if save_field_patterns: poi = kspace.points()[0:-1] else: poi = [] runcode = '' for mode in modes: if mode == '': runcode += ('(run %s)\n' % (defaults.default_band_func( poi, ' '.join(defaults.output_funcs_other))) + '(print-dos 0 1.2 121)\n\n') else: if mode == 'zeven': outputfunc = ' '.join(defaults.output_funcs_te) else: outputfunc = ' '.join(defaults.output_funcs_tm) runcode += ('(run-%s %s)\n' % (mode, defaults.default_band_func(poi, outputfunc)) + '(print-dos 0 1.2 121)\n\n') jobname = 'TriHolesSlab_{0}_r{1:03.0f}_t{2:03.0f}'.format( mat.name, radius * 1000, thickness * 1000) sim = Simulation(jobname=jobname + job_name_suffix, geometry=geom, kspace=kspace, numbands=numbands, resolution=resolution, mesh_size=mesh_size, initcode=defaults.default_initcode, postcode='', runcode=runcode, work_in_subfolder=path.join(containing_folder, jobname + job_name_suffix), clear_subfolder=runmode.startswith('s') or runmode.startswith('c')) draw_bands_title = ( 'Hex. PhC slab; ' '{0}, thickness={1:0.3f}, radius={2:0.3f}'.format( mat.name, geom.objects[0].size[2], geom.objects[1].radius) + bands_title_appendix) return do_runmode(sim, runmode, num_processors, draw_bands_title, plot_crop_y=0.8 / geom.substrate_index, convert_field_patterns=convert_field_patterns, field_pattern_plot_filetype=defaults.field_dist_filetype, field_pattern_plot_k_selection=None, x_axis_hint=[defaults.default_x_axis_hint, kspace][kspace.has_labels()])
particles = [] last_bar = pygame.time.get_ticks() - bar_frequency next_bar = 0 bar_speed = 4 bar_frequency = 1200 bird_dead = False score = 0 p_count = 0 score_list = [] for _ in range(15): x = random.randint(30, WIDTH - 30) y = random.randint(60, HEIGHT - 60) max = random.randint(8,16) b = Block(x,y,max, win) block_group.add(b) if event.type == pygame.MOUSEBUTTONDOWN and not home_page: if p.rect.collidepoint(event.pos): touched = True x, y = event.pos offset_x = p.rect.x - x if event.type == pygame.MOUSEBUTTONUP and not home_page: touched = False if event.type == pygame.MOUSEMOTION and not home_page: if touched: x, y = event.pos if move_right and prev_x > x: