def take_snapshot(self, now): """ This function creates a directory, exports the dielectric structure, then exports the electric and magnetic field vectors to separate HDF5 files. Finally it converts the fields to VTK format (to be readable e. g. by Mayavi2). Note that it is not only called by self.poll(), but I may be also called at will. """ meep.master_printf(" * Saving field snapshot at time=%.4e... \n" % now) ## Export the dielectric structure so that we can visually verify it structure_filename = os.path.join(self.outputdir, 'structure') ## name of the file to save eps (without extension) #if meep.my_rank() == 0 and not os.path.exists(self.outputdir): os.mkdir(self.outputdir) if not os.path.exists(self.outputdir): run_bash("mkdir -p %s" % self.outputdir, anyprocess=True) ## NO DATA #if not os.path.exists(structure_filename): #if meep.my_rank() ==0 : #if not "outputfile" in locals(): outputfile = meep.prepareHDF5File(structure_filename+'.h5') self.field.output_hdf5(meep.Dielectric, self.volume, outputfile) del(outputfile) ## Export the fields snapshot snapshotfiles = [] for (component, compname) in [(meep.Ex, "Ex"), (meep.Ey, "Ey"), (meep.Ez, "Ez"), (meep.Hx, "Hx"), (meep.Hy, "Hy"), (meep.Hz, "Hz")]: snapshotfiles.append("%s/snapshot_%s_t%e.h5" % (self.outputdir, compname, now)) snapshotfile = meep.prepareHDF5File(snapshotfiles[-1]) self.field.output_hdf5(component, self.volume, snapshotfile, 1) del(snapshotfile) ## Convert the files for Mayavi2; join E-fields and H-fields components into vector fields run_bash("h5tovtk %s.h5 -o %s.vtk" % (structure_filename, structure_filename)) run_bash("h5tovtk %s -t 0 -o %s/t%0.3e_Evec.vtk" % (" ".join(snapshotfiles[:3]), self.outputdir, now)) ## todo: use path.join run_bash("h5tovtk %s -t 0 -o %s/t%0.3e_Hvec.vtk" % (" ".join(snapshotfiles[3:]), self.outputdir, now))
def build_polarizabilities(self, structure): """ This is a helper to define the susceptibilities using the callback. It goes through all polarizabilities for all materials. Applicable for time-domain simulation only, because dispersive model is not implemented for frequency-domain simulation yet. """ avail_cbs = [meep.DBL5, meep.DBL4, meep.DBL3, meep.DBL2, meep.DBL1,] avail_cb_setters = [meep.set_DBL5_Callback, meep.set_DBL4_Callback, meep.set_DBL3_Callback, meep.set_DBL2_Callback, meep.set_DBL1_Callback,] for material in self.materials: meep.master_printf("\tAdding material: %s with epsilon: %s at frequency %.4g Hz\n" % (material.name, analytic_eps(material, self.srcFreq).__str__(), self.srcFreq)) for polariz in material.pol: if avail_cbs == []: meep.master_printf("Error: too many polarizabilities defined (5) Reduce their number.") next_cb, next_cb_setter = avail_cbs.pop(), avail_cb_setters.pop() self.return_value = polariz['sigma'] self.double_vec = material.where ## redirect the double_vec() function callback next_cb_setter(self.__disown__()) if "lorentzian_susceptibility" in dir(meep): ## for meep 1.2 or newer structure.add_susceptibility(next_cb, meep.E_stuff, meep.lorentzian_susceptibility(polariz['omega']/c, polariz['gamma']/c)) #else:todo: fix in python-meep #print dir(meep) #structure.add_susceptibility(next_cb, meep.E_stuff, #meep.drude_susceptibility(polariz['omega']/c, polariz['gamma']/c)) else: ## for meep 1.1.1 or older structure.add_polarizability(next_cb, polariz['omega']/c, polariz['gamma']/c)
def __init__(self, field=None, snapshot_times=[], outputdir=None, volume=None): """ Remember the time when to take a snapshot. A list of two or more numbers may be provided. """ self.field = field self.snapshot_times = snapshot_times self.outputdir = outputdir self.volume = volume if not os.path.exists(self.outputdir): run_bash("mkdir -p %s" % self.outputdir) meep.master_printf("Registered %d time points(s) to take snapshot\n" % len(self.snapshot_times))
def finalize(self): #run_bash("cd %s; rm *png" % outputdir) meep.master_printf("\n\nImages to gif\n") del(self.openfile) run_bash("cd %s; h5topng -t 0:%d -R -Zc dkbluered -a yarg %s.h5 -S 1" % (self.outputdir, self.images_number-1, self.name)) if self.outputPNGs or self.outputGIF: run_bash("cd %s; convert -compress None -delay 10 *png %s.gif" % (self.outputdir, self.name)) if not self.outputPNGs: run_bash("cd %s; rm %s*.png" % (self.outputdir, self.name)) if self.outputVTK: run_bash("cd %s; h5tovtk %s.h5 -o %s.vtk" % (self.outputdir, self.name)) if not self.outputHDF: run_bash("cd %s; rm %s.h5" % (self.outputdir, self.name))
def __init__(self, field=None, component=meep.Ex, timebounds=(0, np.inf), timestep=0, volume=None, normal=None, position=None, model=None, pad=0, outputdir="", name=None, outputPNGs=False, outputGIF=True, outputHDF=False, outputVTK=False): """ """ self.field = field self.outputdir = outputdir self.component = component self.timebounds = timebounds self.timestep = timestep self.outputPNGs = outputPNGs self.outputGIF = outputGIF self.outputHDF = outputHDF self.outputVTK = outputVTK if volume: self.volume = volume meep.master_printf("Will record slices at times %.3g, %.3g ... %.3g s \n" % (timebounds[0], timebounds[0]+timestep, timebounds[1])) else: #if not position: #raise RuntimeError("Specify the position of the cut plane (on the axis perpendicular to it)") if normal=="x": self.volume = meep.volume( meep.vec(position, -model.size_y/2+pad, -model.size_z/2+pad), meep.vec(position, model.size_y/2-pad, model.size_z/2-pad)) elif normal=="y": self.volume = meep.volume( meep.vec(-model.size_x/2+pad, position, -model.size_z/2+pad), meep.vec(model.size_x/2-pad, position, model.size_z/2-pad)) elif normal=="z": self.volume = meep.volume( meep.vec(-model.size_x/2+pad, -model.size_y/2+pad, position), meep.vec(model.size_x/2-pad, model.size_y/2-pad, position)) #else: #print normal #raise RuntimeError("Specify the normal parameter as 'x', 'y' or 'z'") meep.master_printf("Will record slices at %s=%.3g m, at times %g, %g ... %g s \n" \ % (normal, position, timebounds[0], timebounds[0]+timestep, timebounds[1])) self.outputdir = outputdir if not name: if not position or not normal: self.name = "SliceByVolume" else: self.name = "Slice_%s%.3e" % (normal, position) else: self.name = name self.images_number = 0 self.last_slice_time = 0. #slices=[] #slices.append({"name":"Ex_xz_slice", "component":meep.Ex, "geom": if not os.path.exists(outputdir): run_bash("mkdir -p %s" % outputdir, anyprocess=True) self.openfile = meep.prepareHDF5File("%s.h5" % (os.path.join(self.outputdir, self.name)))
def lorentzian_unstable_check_new(model, dt, quit_on_warning=True): #{{{ for mat in model.materials: eps_ts = analytic_eps(mat, 1/dt/np.pi) if np.real(eps_ts)<0: meep.master_printf("Warning: for material '%s', the permittivity is negative at timestepping frequency eps(1/pi/dt)=eps(%g)=%s.\n" % \ (mat.name, 1/dt/np.pi, eps_ts.__str__())); if quit_on_warning: quit() for pol in mat.pol: omega_0, gamma = pol['omega'], pol['gamma'] if (omega_0 > gamma/2): z2 = np.sqrt(gamma*gamma + 4*omega_0*omega_0)/2 else: z2 = gamma/2 + np.sqrt(gamma*gamma - 4*omega_0*omega_0)/2 if z2 > 1/dt/np.pi: meep.master_printf("Warning: for material '%s', the oscillator pole having magnitude |z|=%g will be probably unstable when 1/pi/dt=%g.\n" % \ (mat.name, z2, 1/dt/np.pi)); if quit_on_warning: quit()
def __init__(self): meep.CallbackMatrix2D.__init__(self) meep.master_printf("Creating the material matrix....\n") self.meep_resolution = int(res) eps_matrix = numpy.zeros([gridSizeX * res, gridSizeY * res], dtype=complex) # _eps_matrix = numpy.zeros([gridSizeX * res, gridSizeY * res], dtype=float) len_x = eps_matrix.shape[0] len_y = eps_matrix.shape[1] print("len_x = %i, len_y = %i" % (len_x, len_y)) for nn in range(0, len(rx)): for x in range(0, len_x): for y in range(0, len_y): eps_matrix[x, y] = eps_matrix[x, y] + amp[nn] * numpy.exp( -1j * numpy.sqrt((rx[nn] + x / res)**2 + (rz + y / res)**2) * numpy.sqrt( (kx[nn] + x / kx[nn] / res)**2 + (kz[nn] + y / kz[nn] / res)**2) + 1j * phase[nn]) eps_matrix = numpy.absolute( eps_matrix / numpy.amax(eps_matrix))**2 * modulation print(eps_matrix[10, 10]) # grating = numpy.abs(eps_matrix) ** 2 # plt.figure(1) # plt.imshow(_eps_matrix, cmap='hot', extent=[0, gridSizeX, 0, gridSizeY]) # plt.colorbar() # plt.show() meep.master_printf("Setting the material matrix...\n") self.set_matrix_2D(eps_matrix, vol) # self.setMatrix(grating) self.stored_eps_matrix = eps_matrix # to prevent the garbage collector from cleaning up the matrix... meep.master_printf("MeepMaterial object initialized.\n")
def print_progress(self, now): if now > 0 and (now-self.last_reported_time > self.simtime*.1): meep.master_printf("Progress %.2f of expected total %d s\n" % (now / self.simtime, (self.simtime / now * self.get_time()))) self.last_reported_time = now
def __init__(self, simtime): self.starttime = time.time() self.simtime = simtime meep.master_printf("\tSimulation time: %e [s] = %e time units\n" % (simtime, simtime*c)) self.last_reported_time = 0
* realistic dispersive material models, * calculation of complex amplitude parameters s11 (reflection), s21 (transmission) * all units in metric system (native time unit is then (1 m)/c = 3.33 ns), * meep remains in its own namespace ("import meep" instead of "from meep import *") """ import numpy as np import time, sys, os from scipy.constants import pi, c import meep_utils import meep_mpi as meep #import meep meep.master_printf("=== Initialisation ===\n") sim_param, model_param = meep_utils.process_param(sys.argv[1:]) print model_param ## Model selection #from model_SphereWireNew import *; model = SphereWire_model(**model_param) ## OK #from model_SphereWireNew import *; model = SphereFishnet_model(**model_param) ## OK #from model_SphereWireNew import *; model = SphereElliptic_model(**model_param) #from model_SphereWireNew import *; model = SimpleEllipsoid_model(**model_param) #from model_CKEBars import * #model = CKEBars_model_test(**model_param) #from model_PKCutSheet import * #model = PKCutSheet_model(**model_param) from model_simple_structures import *
def print_progress(self, now): if now/self.simtime > self.reporttimes[0]: meep.master_printf("Progress %.2f of expected total %d s\n" % \ (now / self.simtime, (self.simtime / now * self.get_time()))) self.reporttimes[0:1] = []
def __init__(self, simtime): self.starttime = time.time() self.simtime = simtime meep.master_printf("\tSimulation time: %e [s] = %e time units\n" % (simtime, simtime*c)) self.reporttimes = [.001, .01, 0.03] + [t/10. for t in range(1,9)] + [2.]