diff --git a/EMpy/RCWA.py b/EMpy/RCWA.py index 749e15c..aa27263 100644 --- a/EMpy/RCWA.py +++ b/EMpy/RCWA.py @@ -162,13 +162,13 @@ def get_pitch(self): if idx.size == 0: # warning('no BinaryGratings: better use a simple transfer matrix.') return 1.0 # return LAMBDA: any value will do + # check that all the pitches are the same! + l = S.asarray([self.multilayer[i].pitch for i in idx]) + if S.all(l == l[0]): + return l[0] + else: - # check that all the pitches are the same! - l = S.asarray([self.multilayer[i].pitch for i in idx]) - if not S.all(l == l[0]): - raise ValueError("All the BinaryGratings must have the same pitch.") - else: - return l[0] + raise ValueError("All the BinaryGratings must have the same pitch.") class IsotropicRCWA(RCWA): diff --git a/EMpy/devices.py b/EMpy/devices.py index 697fab1..a041b9e 100644 --- a/EMpy/devices.py +++ b/EMpy/devices.py @@ -985,17 +985,16 @@ def CM(self, wl=None): if wl is None: wl = self.wl - Hs = [] - for K, neff, l1, l2 in zip(self.Ks, self.neffs, self.l1s, self.l2s): - Hs.append( - composeTMlist( - [ - Line(self.wl, neff, 0.0, neff, l1).TM(wl), - K.TM(wl), - Line(self.wl, neff, 0.0, neff, l2).TM(wl), - ] - ) + Hs = [ + composeTMlist( + [ + Line(self.wl, neff, 0.0, neff, l1).TM(wl), + K.TM(wl), + Line(self.wl, neff, 0.0, neff, l2).TM(wl), + ] ) + for K, neff, l1, l2 in zip(self.Ks, self.neffs, self.l1s, self.l2s) + ] return composeCM(composeTMlist(Hs), self.Ks[-1].CM(wl)) @@ -1330,8 +1329,6 @@ def solve(self, wls): pf = SWG.pf400_25 elif (self.w, self.T) == (400, 125): pf = SWG.pf400_125 - elif (self.w, self.T) == (400, 225): - pf = SWG.pf400_225 elif self.w < 400 or self.w > 488 or self.T < 25 or self.T > 225: raise ValueError("input out of bounds") else: diff --git a/EMpy/materials.py b/EMpy/materials.py index fd08e32..8abd6c6 100644 --- a/EMpy/materials.py +++ b/EMpy/materials.py @@ -157,10 +157,7 @@ def __init__(self, data=None, T0=300): self.T0 = T0 def TOC(self, T): - if self.__data is not None: - return numpy.polyval(self.__data, T) - else: - return 0.0 + return numpy.polyval(self.__data, T) if self.__data is not None else 0.0 def __call__(self, T): return self.TOC(T) @@ -213,7 +210,7 @@ def isIsotropic(): def __str__(self): """Return material name.""" - return self.name + ", isotropic" + return f"{self.name}, isotropic" class EpsilonTensor(object): @@ -255,7 +252,7 @@ def isIsotropic(): def __str__(self): """Return material name.""" - return self.name + ", anisotropic" + return f"{self.name}, anisotropic" # Vacuum @@ -361,7 +358,7 @@ def get_10400_000_100(conc000): nE_ = numpy.interp(conc000, conc, epsE) ** 0.5 return LiquidCrystal( - "10400_000_100_" + str(conc000) + "_" + str(100 - conc000), + f"10400_000_100_{str(conc000)}_{str(100 - conc000)}", nO_, nE_, nO_electrical_, diff --git a/EMpy/modesolvers/FD.py b/EMpy/modesolvers/FD.py index eb473bf..c75fb5c 100644 --- a/EMpy/modesolvers/FD.py +++ b/EMpy/modesolvers/FD.py @@ -89,8 +89,7 @@ def __init__(self, wl, x, y, epsfunc, boundary, method="Ex"): def _get_eps(self, xc, yc): eps = self.epsfunc(xc, yc) eps = numpy.c_[eps[:, 0:1], eps, eps[:, -1:]] - eps = numpy.r_[eps[0:1, :], eps, eps[-1:, :]] - return eps + return numpy.r_[eps[0:1, :], eps, eps[-1:, :]] def build_matrix(self): @@ -260,9 +259,7 @@ def build_matrix(self): J = numpy.r_[iall, i_e, i_w, i_n, i_s] V = numpy.r_[Ap[iall], Ae[i_w], Aw[i_e], An[i_s], As[i_n]] - A = coo_matrix((V, (I, J))).tocsr() - - return A + return coo_matrix((V, (I, J))).tocsr() def solve(self, neigs, tol): @@ -286,24 +283,21 @@ def solve(self, neigs, tol): # sort and save the modes idx = numpy.flipud(numpy.argsort(neff)) self.neff = neff[idx] - tmp = [] - for i in idx: - tmp.append(phi[i]) - - if self.method == "scalar": - self.phi = tmp - elif self.method == "Ex": + tmp = [phi[i] for i in idx] + if self.method == "Ex": self.Ex = tmp - if self.method == "Ey": + elif self.method == "Ey": self.Ey = tmp + elif self.method == "scalar": + self.phi = tmp return self def __str__(self): - descr = ( - "Semi-Vectorial Finite Difference Modesolver\n\tmethod: %s\n" % self.method + return ( + "Semi-Vectorial Finite Difference Modesolver\n\tmethod: %s\n" + % self.method ) - return descr class VFDModeSolver(ModeSolver): diff --git a/EMpy/modesolvers/FMM.py b/EMpy/modesolvers/FMM.py index ca9c2ba..016fbe5 100644 --- a/EMpy/modesolvers/FMM.py +++ b/EMpy/modesolvers/FMM.py @@ -136,12 +136,7 @@ def translate(self): raise ValueError("Unknown boundary.") def __str__(self): - return "xleft = %s, xright = %s, yleft = %s, yright = %s" % ( - self.xleft, - self.xright, - self.yleft, - self.yright, - ) + return f"xleft = {self.xleft}, xright = {self.xright}, yleft = {self.yleft}, yright = {self.yright}" class Slice(object): @@ -289,15 +284,8 @@ def get_y(self, n=100): def eval(self, x_=None, y_=None): """Evaluate the mode at x,y.""" - if x_ is None: - x = self.get_x() - else: - x = numpy.atleast_1d(x_) - if y_ is None: - y = self.get_y() - else: - y = numpy.atleast_1d(y_) - + x = self.get_x() if x_ is None else numpy.atleast_1d(x_) + y = self.get_y() if y_ is None else numpy.atleast_1d(y_) nmodi = len(self.modie) lenx = len(x) leny = len(y) @@ -501,20 +489,12 @@ def fields(self, x=None, y=None): def intensity(self, x=None, y=None): Ex, Ey, Ez, cBx, cBy, cBz = self.fields(x, y) - cSz = 0.5 * (Ex * numpy.conj(cBy) - Ey * numpy.conj(cBx)) - return cSz + return 0.5 * (Ex * numpy.conj(cBy) - Ey * numpy.conj(cBx)) def TEfrac_old(self, x_=None, y_=None): - if x_ is None: - x = self.get_x() - else: - x = numpy.atleast_1d(x_) - if y_ is None: - y = self.get_y() - else: - y = numpy.atleast_1d(y_) - + x = self.get_x() if x_ is None else numpy.atleast_1d(x_) + y = self.get_y() if y_ is None else numpy.atleast_1d(y_) Ex, Ey, Ez, cBx, cBy, cBz, cSz = self.fields(x, y) cSTE = 0.5 * EMpy.utils.trapz2(Ex * numpy.conj(cBy), y, x) cSTM = 0.5 * EMpy.utils.trapz2(-Ey * numpy.conj(cBx), y, x) @@ -527,15 +507,8 @@ def TEfrac(self): def overlap_old(self, m, x_=None, y_=None): - if x_ is None: - x = self.get_x() - else: - x = numpy.atleast_1d(x_) - if y_ is None: - y = self.get_y() - else: - y = numpy.atleast_1d(y_) - + x = self.get_x() if x_ is None else numpy.atleast_1d(x_) + y = self.get_y() if y_ is None else numpy.atleast_1d(y_) Ex, Ey, Ez, cBx, cBy, cBz = self.fields(x, y) cSz = self.intensity(x, y) norm = scipy.sqrt(EMpy.utils.trapz2(cSz, y, x)) diff --git a/EMpy/modesolvers/interface.py b/EMpy/modesolvers/interface.py index b6ded39..2a3453a 100644 --- a/EMpy/modesolvers/interface.py +++ b/EMpy/modesolvers/interface.py @@ -32,18 +32,18 @@ def save_for_FDTD(self, mode_id="", x=None, y=None): Ex_FDTD, Ey_FDTD, Ez_FDTD, Hx_FDTD, Hy_FDTD, Hz_FDTD = self.get_fields_for_FDTD( x, y ) - Ex_FDTD.real.T.tofile("ex" + mode_id + ".dat", sep=" ") - Ex_FDTD.imag.T.tofile("iex" + mode_id + ".dat", sep=" ") - Ey_FDTD.real.T.tofile("ey" + mode_id + ".dat", sep=" ") - Ey_FDTD.imag.T.tofile("iey" + mode_id + ".dat", sep=" ") - Ez_FDTD.real.T.tofile("ez" + mode_id + ".dat", sep=" ") - Ez_FDTD.imag.T.tofile("iez" + mode_id + ".dat", sep=" ") - Hx_FDTD.real.T.tofile("hx" + mode_id + ".dat", sep=" ") - Hx_FDTD.imag.T.tofile("ihx" + mode_id + ".dat", sep=" ") - Hy_FDTD.real.T.tofile("hy" + mode_id + ".dat", sep=" ") - Hy_FDTD.imag.T.tofile("ihy" + mode_id + ".dat", sep=" ") - Hz_FDTD.real.T.tofile("hz" + mode_id + ".dat", sep=" ") - Hz_FDTD.imag.T.tofile("ihz" + mode_id + ".dat", sep=" ") + Ex_FDTD.real.T.tofile(f"ex{mode_id}.dat", sep=" ") + Ex_FDTD.imag.T.tofile(f"iex{mode_id}.dat", sep=" ") + Ey_FDTD.real.T.tofile(f"ey{mode_id}.dat", sep=" ") + Ey_FDTD.imag.T.tofile(f"iey{mode_id}.dat", sep=" ") + Ez_FDTD.real.T.tofile(f"ez{mode_id}.dat", sep=" ") + Ez_FDTD.imag.T.tofile(f"iez{mode_id}.dat", sep=" ") + Hx_FDTD.real.T.tofile(f"hx{mode_id}.dat", sep=" ") + Hx_FDTD.imag.T.tofile(f"ihx{mode_id}.dat", sep=" ") + Hy_FDTD.real.T.tofile(f"hy{mode_id}.dat", sep=" ") + Hy_FDTD.imag.T.tofile(f"ihy{mode_id}.dat", sep=" ") + Hz_FDTD.real.T.tofile(f"hz{mode_id}.dat", sep=" ") + Hz_FDTD.imag.T.tofile(f"ihz{mode_id}.dat", sep=" ") def plot(self, x=None, y=None): raise NotImplementedError() diff --git a/EMpy/utils.py b/EMpy/utils.py index 7a3dd3f..f74a18a 100644 --- a/EMpy/utils.py +++ b/EMpy/utils.py @@ -47,7 +47,6 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): rix = self.mat.n(wl) EPS[hmax] = rix ** 2 EPS1[hmax] = rix ** -2 - return EPS, EPS1 else: # anisotropic EPS = numpy.zeros((3, 3, 2 * hmax + 1), dtype=complex) @@ -56,7 +55,8 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): numpy.squeeze(self.mat.epsilonTensor(wl)) / EMpy.constants.eps0 ) EPS1[:, :, hmax] = scipy.linalg.inv(EPS[:, :, hmax]) - return EPS, EPS1 + + return EPS, EPS1 def capacitance(self, area=1.0, wl=0): """Capacitance = eps0 * eps_r * area / thickness.""" @@ -105,7 +105,6 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): EPS1 = (rix1 ** -2 - rix2 ** -2) * f * numpy.sinc(h * f) + rix2 ** -2 * ( h == 0 ) - return EPS, EPS1 else: # anisotropic EPS = numpy.zeros((3, 3, 2 * hmax + 1), dtype=complex) @@ -121,7 +120,8 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): EPS1[:, :, ih] = ( scipy.linalg.inv(eps1) - scipy.linalg.inv(eps2) ) * f * numpy.sinc(hh * f) + scipy.linalg.inv(eps2) * (hh == 0) - return EPS, EPS1 + + return EPS, EPS1 def capacitance(self, area=1.0, wl=0): """Capacitance = eps0 * eps_r * area / thickness.""" @@ -211,7 +211,6 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): * numpy.sinc(h * f2) * numpy.exp(2j * numpy.pi * h / N * B) ) - return EPS, EPS1 else: # anisotropic EPS = numpy.zeros((3, 3, 2 * hmax + 1), dtype=complex) @@ -248,7 +247,8 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): * numpy.exp(2j * numpy.pi * hh / N * B) + scipy.linalg.inv(eps3) * (hh == 0) ) - return EPS, EPS1 + + return EPS, EPS1 def capacitance(self, area=1.0, wl=0): """Capacitance = eps0 * eps_r * area / thickness.""" @@ -335,7 +335,6 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): * numpy.sinc(h * f2) * numpy.exp(2j * numpy.pi * h / N * B) ) - return EPS, EPS1 else: # anisotropic EPS = numpy.zeros((3, 3, 2 * hmax + 1), dtype=complex) @@ -373,7 +372,8 @@ def getEPSFourierCoeffs(self, wl, n, anisotropic=True): * numpy.exp(2j * numpy.pi * hh / N * B) + scipy.linalg.inv(eps3) * (hh == 0) ) - return EPS, EPS1 + + return EPS, EPS1 def capacitance(self, area=1.0, wl=0): """Capacitance = eps0 * eps_r * area / thickness.""" @@ -819,10 +819,7 @@ def height(self): def find_layer(self, y): l = numpy.where(self.ys() <= y)[0] - if len(l) > 0: - return self[min(l[-1], len(self) - 1)] - else: - return self[0] + return self[min(l[-1], len(self) - 1)] if len(l) > 0 else self[0] def plot(self, x0, x1, nmin, nmax, wl=1.55e-6): try: @@ -848,7 +845,7 @@ def __str__(self): class CrossSection(list): def __str__(self): - return "\n".join("%s" % s for s in self) + return "\n".join(f"{s}" for s in self) def widths(self): return numpy.array([s.width for s in self]) @@ -907,10 +904,7 @@ def grid(self, nx_per_region, ny_per_region): def find_slice(self, x): s = numpy.where(self.xs() <= x)[0] - if len(s) > 0: - return self[min(s[-1], len(self) - 1)] - else: - return self[0] + return self[min(s[-1], len(self) - 1)] if len(s) > 0 else self[0] def _epsfunc(self, x, y, wl): if numpy.isscalar(x) and numpy.isscalar(y): @@ -1084,7 +1078,14 @@ def group_delay_and_dispersion(wls, y): tau = -0.5 / numpy.pi * numpy.diff(phi) / df * 1e12 # dispersion in ps/nm - Dpsnm = -0.5 / numpy.pi / cnmps * f[1:-1] ** 2 * numpy.diff(phi, 2) / df[0:-1] ** 2 + Dpsnm = ( + -0.5 + / numpy.pi + / cnmps + * f[1:-1] ** 2 + * numpy.diff(phi, 2) + / df[:-1] ** 2 + ) return phi, tau, Dpsnm @@ -1179,15 +1180,8 @@ def absdy(x_): roots = scipy.interpolate.sproot(tckFWHM) idxFWHM = numpy.searchsorted(roots, xopt) - if idxFWHM <= 0: - xFWHM_1 = x[0] - else: - xFWHM_1 = roots[idxFWHM - 1] - if idxFWHM >= len(roots): - xFWHM_2 = x[-1] - else: - xFWHM_2 = roots[idxFWHM] - + xFWHM_1 = x[0] if idxFWHM <= 0 else roots[idxFWHM - 1] + xFWHM_2 = x[-1] if idxFWHM >= len(roots) else roots[idxFWHM] p = Peak(xopt, yopt, idx, x[idx], y[idx], xFWHM_1, xFWHM_2) peaks.append(p) @@ -1195,9 +1189,7 @@ def cmp_y(x_, y_): # to sort in descending order if x_.y == y_.y: return 0 - if x_.y > y_.y: - return -1 - return 1 + return -1 if x_.y > y_.y else 1 peaks.sort(cmp=cmp_y) @@ -1259,7 +1251,7 @@ def warning(s): :type s: str :rtype : str """ - print("WARNING --- {}".format(s)) + print(f"WARNING --- {s}") class ProgressBar(object): @@ -1289,10 +1281,8 @@ def updateAmount(self, newAmount=0): """Update the progress bar with the new amount (with min and max values set at initialization; if it is over or under, it takes the min or max value as a default.""" - if newAmount < self.min: - newAmount = self.min - if newAmount > self.max: - newAmount = self.max + newAmount = max(newAmount, self.min) + newAmount = min(newAmount, self.max) self.amount = newAmount # Figure out the new percent done, round to an integer @@ -1308,25 +1298,22 @@ def updateAmount(self, newAmount=0): # Build a progress bar with an arrow of equal signs; special cases for # empty and full if numHashes == 0: - self.progBar = "[>%s]" % (" " * (allFull - 1)) + self.progBar = f'[>{" " * (allFull - 1)}]' elif numHashes == allFull: - self.progBar = "[%s]" % ("=" * allFull) + self.progBar = f'[{"=" * allFull}]' else: - self.progBar = "[%s>%s]" % ( - "=" * (numHashes - 1), - " " * (allFull - numHashes), - ) + self.progBar = f'[{"=" * (numHashes - 1)}>{" " * (allFull - numHashes)}]' # figure out where to put the percentage, roughly centered percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) - percentString = " " + str(percentDone) + "% " + percentString = f" {percentDone}% " elapsed_time = time.time() - self.start_time # slice the percentage into the bar self.progBar = "".join( [ - self.progBar[0:percentPlace], + self.progBar[:percentPlace], percentString, self.progBar[percentPlace + len(percentString) :], ] diff --git a/examples/ex_laser_etch_monitor.py b/examples/ex_laser_etch_monitor.py index 20af614..65b5aa8 100644 --- a/examples/ex_laser_etch_monitor.py +++ b/examples/ex_laser_etch_monitor.py @@ -57,8 +57,7 @@ def find_nearest(a, a0): def arg_find_nearest(a, a0): """Return index to element in ndArray `a` that has value closest to the scalar value `a0`.""" - idx = numpy.abs(a - a0).argmin() - return idx + return numpy.abs(a - a0).argmin() def count_noninf(multilayer): @@ -72,11 +71,7 @@ def count_noninf(multilayer): def arg_inf(multilayer): """Return index to layers with infinite-thickness in an EMpy Multilayer object.""" - out = [] - for ix, x in enumerate(multilayer): - if numpy.isinf(x.thickness): - out.append(ix) - return out + return [ix for ix, x in enumerate(multilayer) if numpy.isinf(x.thickness)] # Define some materials @@ -172,7 +167,7 @@ def n_AlGaAs95(w): idxtemp = 0 print("Etching...") -while go is True: +while go: # keep reducing thickness/removing layers until last layer is too thin i = i + 1 @@ -186,27 +181,24 @@ def n_AlGaAs95(w): if i <= 0: # first iteration: analyze unetched structure EtchStep_current = 0.0 - indexno = idxtemp else: # point to non-infinite layers for etching: while numpy.isinf(layers[idxtemp].thickness): - idxtemp = idxtemp + 1 # assumes etching from 1st layer in list - indexno = idxtemp - + idxtemp += 1 + indexno = idxtemp if layers[indexno].thickness <= EtchStep_current: # next layer is thinner than etch step # Reduce etch step + remove this layer: EtchStep_current = EtchStep_current - layers[indexno].thickness layers.pop(indexno) - elif layers[indexno].thickness > EtchStep_current: + else: # etch increment ends within next layer # reduce layer thickness & solve & save data points: layers[indexno].thickness = layers[indexno].thickness - EtchStep_current # add this layer stack to the list etchedlayers.append(deepcopy(layers)) - # get RefrIndex in this layer - RefrIdx.append(etchedlayers[-1][idxtemp].mat.n(wl_lasermon).real) + RefrIdx.append(etchedlayers[-1][indexno].mat.n(wl_lasermon).real) if i <= 0: # for 1st iteration: unetched layer EtchSteps.append(0.0) diff --git a/examples/ex_transfer_matrix_2.py b/examples/ex_transfer_matrix_2.py index bf77d4d..1b991aa 100644 --- a/examples/ex_transfer_matrix_2.py +++ b/examples/ex_transfer_matrix_2.py @@ -39,5 +39,5 @@ pylab.ylabel("Power /dB") pylab.grid() pylab.xlim(wls.min(), wls.max()) -pylab.savefig(__file__ + ".png") +pylab.savefig(f"{__file__}.png") pylab.show() diff --git a/examples/nk.py b/examples/nk.py index 8eafdbe..e02c4ff 100644 --- a/examples/nk.py +++ b/examples/nk.py @@ -592,10 +592,7 @@ def AlAs_interp(wl, k=False): ns = np.interp(wl, wls, ns) ks = np.interp(wl, wls, ks) - if k: - return ns - 1j * ks - else: - return ns + return ns - 1j * ks if k else ns # end def(AlAs_interp) @@ -861,10 +858,7 @@ def GaAs_interp(wl, k=False): ns = np.interp(wl, wls, ns) ks = np.interp(wl, wls, ks) - if k: - return ns - 1j * ks - else: - return ns + return ns - 1j * ks if k else ns # end def(GaAs_interp) @@ -1052,10 +1046,7 @@ def GaSb_interp(wl, k=False): ns = np.interp(wl, wls, ns) ks = np.interp(wl, wls, ks) - if k: - return ns - 1j * ks - else: - return ns + return ns - 1j * ks if k else ns # end def(GaSb_interp) @@ -1207,12 +1198,11 @@ def AlGaAs_interp(x, wl, k=False): Exception ValueError for wavelength out of model range """ check_wl(wl, 0.206, 2.066, "AlGaAs_interp", fail=True) - if k: - GaAs = GaAs_interp(wl, k=True) - AlAs = AlAs_interp(wl, k=True) - return GaAs - (GaAs - AlAs) * x - else: + if not k: return GaAs_interp(wl) - (GaAs_interp(wl) - AlAs_interp(wl)) * x + GaAs = GaAs_interp(wl, k=True) + AlAs = AlAs_interp(wl, k=True) + return GaAs - (GaAs - AlAs) * x # end def(AlGaAs) diff --git a/scripts/FDTD.py b/scripts/FDTD.py index 910a228..18cefc4 100644 --- a/scripts/FDTD.py +++ b/scripts/FDTD.py @@ -125,9 +125,8 @@ def tofile(self, filename=None): """Save the input data to the input file.""" if filename is None: filename = self.filename - f = open(filename, "w") - f.write(self.__str__()) - f.close() + with open(filename, "w") as f: + f.write(self.__str__()) class Param(object): @@ -236,12 +235,8 @@ def plot_Hz(self, logplot=False): self.__plot_field(self.Hz, logplot) def __plot_field(self, field, logplot=False): - if logplot: - data = 20 * numpy.log10(1e-20 + numpy.abs(field)) - pylab.plot(self.t, data) - else: - data = field - pylab.plot(self.t, data) + data = 20 * numpy.log10(1e-20 + numpy.abs(field)) if logplot else field + pylab.plot(self.t, data) pylab.show() @@ -266,27 +261,21 @@ def fetch_data( remote_dir = fixdir(remote_dir_) directory = fixdir(directory_) # input file - os.system( - "scp -C bollalo001@pico:" + remote_dir + "/" + input_file + " " + directory - ) + os.system(f"scp -C bollalo001@pico:{remote_dir}/{input_file} {directory}") # param file - os.system( - "scp -C bollalo001@pico:" + remote_dir + "/" + param_file + " " + directory - ) + os.system(f"scp -C bollalo001@pico:{remote_dir}/{param_file} {directory}") # fieldslices, flux and time sensors - os.system( - "scp -C bollalo001@pico:" + remote_dir + "/[EHeh]*_*" + " " + directory - ) + os.system(f"scp -C bollalo001@pico:{remote_dir}/[EHeh]*_* {directory}") # dielslices - os.system("scp -C bollalo001@pico:" + remote_dir + "/diel*" + " " + directory) + os.system(f"scp -C bollalo001@pico:{remote_dir}/diel* {directory}") def put_data(self, remote_dir_="./", input_file="inp.txt", directory_="./"): remote_dir = fixdir(remote_dir_) directory = fixdir(directory_) # input file - os.system("scp -C" + directory + input_file + " bollalo001@pico:" + remote_dir) + os.system(f"scp -C{directory}{input_file} bollalo001@pico:{remote_dir}") # .dat modesolver's files - os.system("scp -C" + directory + "*.dat bollalo001@pico:" + remote_dir) + os.system(f"scp -C{directory}*.dat bollalo001@pico:{remote_dir}") def load( self, directory_="./", input_file="inp.txt", param_file="param", remote_dir_="" @@ -336,69 +325,64 @@ def load_input_file(self, directory_="./", filename="inp.txt"): # dielslices ndielslices = numpy.fromstring(strip_comment(f.readline()), sep=" ") inp.dielslices = [] - for i in range(ndielslices): - inp.dielslices.append( - numpy.fromstring(strip_comment(f.readline()), sep=" ") - ) - + inp.dielslices.extend( + numpy.fromstring(strip_comment(f.readline()), sep=" ") + for _ in range(ndielslices) + ) # fieldslices nfieldslices = numpy.fromstring(strip_comment(f.readline()), sep=" ") inp.fieldslices = [] - for i in range(nfieldslices): - inp.fieldslices.append( - numpy.fromstring(strip_comment(f.readline()), sep=" ") - ) - + inp.fieldslices.extend( + numpy.fromstring(strip_comment(f.readline()), sep=" ") + for _ in range(nfieldslices) + ) # dielobjs (ndielobjs, inp.bgrix, inp.bgsigma) = numpy.fromstring( strip_comment(f.readline()), sep=" " ) inp.dielobjs = [] - for i in range(int(ndielobjs)): - inp.dielobjs.append( - (strip_comment(f.readline()), strip_comment(f.readline())) - ) + inp.dielobjs.extend( + (strip_comment(f.readline()), strip_comment(f.readline())) + for _ in range(int(ndielobjs)) + ) inp.smoothing_method = numpy.fromstring(strip_comment(f.readline()), sep=" ") # sources nsources = numpy.fromstring(strip_comment(f.readline()), dtype=int, sep=" ") inp.sources = [] # (inp.time_dependence, inp.wls, inp.pwidth, inp.shift) = numpy.fromstring(strip_comment(f.readline()), sep = ' ') - for i in range(nsources): - inp.sources.append( - ( - strip_comment(f.readline()), - strip_comment(f.readline()), - strip_comment(f.readline()), - strip_comment(f.readline()), - ) + inp.sources.extend( + ( + strip_comment(f.readline()), + strip_comment(f.readline()), + strip_comment(f.readline()), + strip_comment(f.readline()), ) - + for _ in range(nsources) + ) # dft monitors (inp.lambdamin, inp.lambdamax, inp.dlambda) = numpy.fromstring( strip_comment(f.readline()), sep=" " ) ndftmonitors = numpy.fromstring(strip_comment(f.readline()), dtype=int, sep=" ") inp.dftmonitors = [] - for i in range(ndftmonitors): - inp.dftmonitors.append( - ( - numpy.fromstring(strip_comment(f.readline()), sep=" "), - numpy.fromstring(strip_comment(f.readline()), sep=" "), - ) + inp.dftmonitors.extend( + ( + numpy.fromstring(strip_comment(f.readline()), sep=" "), + numpy.fromstring(strip_comment(f.readline()), sep=" "), ) - + for _ in range(ndftmonitors) + ) # time monitors ntimemonitors = numpy.fromstring(strip_comment(f.readline()), sep=" ") inp.timemonitors_time_interval = numpy.fromstring( strip_comment(f.readline()), sep=" " ) inp.timemonitors = [] - for i in range(ntimemonitors): - inp.timemonitors.append( - numpy.fromstring(strip_comment(f.readline()), sep=" ") - ) - + inp.timemonitors.extend( + numpy.fromstring(strip_comment(f.readline()), sep=" ") + for _ in range(ntimemonitors) + ) f.close() self.input = inp @@ -411,7 +395,7 @@ def load_param(self, directory_="./", filename="param"): except Exception: print("ERROR: param file") return - param.dx, param.dy, param.dz, param.dt = data[0:4] + param.dx, param.dy, param.dz, param.dt = data[:4] ( param.mx, param.my, @@ -467,10 +451,10 @@ def load_sensors(self, directory_="./"): tmp.H2 = load_fortran_unformatted(directory + "H2_%02d" % (iflux + 1)) # [tmp.E1, tmp.H1, tmp.E2, tmp.H2] = map(lambda x: x[0::2] + 1j * x[1::2], [tmp.E1, tmp.H1, tmp.E2, tmp.H2]) # more memory efficient! - tmp.E1 = tmp.E1[0::2] + 1j * tmp.E1[1::2] - tmp.H1 = tmp.H1[0::2] + 1j * tmp.H1[1::2] - tmp.E2 = tmp.E2[0::2] + 1j * tmp.E2[1::2] - tmp.H2 = tmp.H2[0::2] + 1j * tmp.H2[1::2] + tmp.E1 = tmp.E1[::2] + 1j * tmp.E1[1::2] + tmp.H1 = tmp.H1[::2] + 1j * tmp.H1[1::2] + tmp.E2 = tmp.E2[::2] + 1j * tmp.E2[1::2] + tmp.H2 = tmp.H2[::2] + 1j * tmp.H2[1::2] n1 = dm["flxlim"][1] - dm["flxlim"][0] + 1 n2 = dm["flxlim"][3] - dm["flxlim"][2] + 1 @@ -549,8 +533,8 @@ def viz2D(self, filename, directory_="./", const_dir="z", logplot=False): pylab.contour(x1, x2, data, 64) pylab.colorbar() pylab.axis("image") - pylab.xlabel(x1label + " /um") - pylab.ylabel(x2label + " /um") + pylab.xlabel(f"{x1label} /um") + pylab.ylabel(f"{x2label} /um") pylab.show() def memory(self): @@ -646,7 +630,7 @@ def run( if bg: cmd += "&" if remote: - cmd = 'ssh pico "' + cmd + '"' + cmd = f'ssh pico "{cmd}"' os.system(cmd) def __str__(self): @@ -675,9 +659,7 @@ def load_fortran_unformatted(filename): def strip_comment(line): """Get rid of fortran comments.""" idx = line.find("!") - if idx != -1: - return line[:idx].strip() - return line + return line[:idx].strip() if idx != -1 else line def fixdir(str, sep="/"):