def write_to_file(self, filename='material_index.dat', plot=True): ''' Write the refractive index profile to file. Args: filename (str): The nominal filename the refractive index data should be saved to. plot (bool): `True` if plots should be generates, otherwise `False`. Default is `True`. ''' path = os.path.dirname(sys.modules[__name__].__file__) + '/' with open(filename, 'w') as fs: for n_row in np.abs(self.n[::-1]): n_str = ','.join([str(v) for v in n_row]) fs.write(n_str + '\n') if plot: filename_image_prefix, _ = os.path.splitext(filename) filename_image = filename_image_prefix + '.png' args = { 'title': 'Refractive Index Profile', 'x_pts': self.x_pts, 'y_pts': self.y_pts, 'x_min': self.x_min, 'x_max': self.x_max, 'y_min': self.y_min, 'y_max': self.y_max, 'filename_data': filename, 'filename_image': filename_image } gp.gnuplot(path + 'structure.gpi', args)
def _plot_n_effs(self, filename_n_effs, filename_te_fractions, xlabel, ylabel, title): args = { "titl": title, "xlab": xlabel, "ylab": ylabel, "filename_data": filename_n_effs, "filename_frac_te": filename_te_fractions, "filename_image": None, "num_modes": len(self.modes), } filename_image_prefix, _ = os.path.splitext(filename_n_effs) filename_image = filename_image_prefix + ".png" args["filename_image"] = filename_image if MPL: data = np.loadtxt(args["filename_data"], delimiter=",").T plt.clf() plt.title(title) plt.xlabel(args["xlab"]) plt.ylabel(args["ylab"]) for i in range(args["num_modes"]): plt.plot(data[0], data[i + 1], "-o") plt.savefig(args["filename_image"]) else: gp.gnuplot(self._path + "n_effs.gpi", args, silent=False) gp.trim_pad_image(filename_image) return args
def _plot_fraction( self, filename_fraction, xlabel, ylabel, title, mode_list=[] ): if not mode_list: mode_list = range(len(self.modes)) gp_mode_list = " ".join(str(idx) for idx in mode_list) args = { "titl": title, "xlab": xlabel, "ylab": ylabel, "filename_data": filename_fraction, "filename_image": None, "mode_list": gp_mode_list, } filename_image_prefix, _ = os.path.splitext(filename_fraction) filename_image = filename_image_prefix + ".png" args["filename_image"] = filename_image if MPL: data = np.loadtxt(args["filename_data"], delimiter=",").T plt.clf() plt.title(title) plt.xlabel(args["xlab"]) plt.ylabel("$" + args["ylab"] + "$") for i in modes: plt.plot(data[0], data[i + 1], "-o") plt.savefig(args["filename_image"]) else: gp.gnuplot(self._path + "fractions.gpi", args, silent=False) gp.trim_pad_image(filename_image) return args
def write_to_file(self, filename='material_index.dat', plot=True): ''' Write the refractive index profile to file. Args: filename (str): The nominal filename the refractive index data should be saved to. plot (bool): `True` if plots should be generates, otherwise `False`. Default is `True`. ''' path = os.path.dirname(sys.modules[__name__].__file__) + '/' dir_plot = 'material_index/' if not os.path.exists(dir_plot): os.makedirs(dir_plot) for axis, name in zip(self.axes, self.axes_str): root, ext = os.path.splitext(filename) fn = dir_plot + root + '_' + name + ext with open(fn, 'w') as fs: for n_row in np.abs(axis.n[::-1]): n_str = ','.join([str(v) for v in n_row]) fs.write(n_str + '\n') if plot: filename_image_prefix, _ = os.path.splitext(fn) filename_image = filename_image_prefix + '.png' args = { 'title': 'Refractive Index Profile: %s' % name, 'x_pts': self.xx.x_pts, 'y_pts': self.xx.y_pts, 'x_min': self.xx.x_min, 'x_max': self.xx.x_max, 'y_min': self.xx.y_min, 'y_max': self.xx.y_max, 'filename_data': fn, 'filename_image': filename_image } if MPL: heatmap = np.loadtxt(args['filename_data'], delimiter=',') plt.clf() plt.title(args['title']) plt.xlabel('$x$') plt.ylabel('$y$') plt.imshow(np.flipud(heatmap), extent=(args['x_min'], args['x_max'], args['y_min'], args['y_max']), aspect="auto") plt.colorbar() plt.savefig(filename_image) else: gp.gnuplot(path + 'structure.gpi', args, silent=False)
def _plot_mode(self, field_name, mode_number, filename_mode, n_eff=None, subtitle='', e2_x=0., e2_y=0., ctr_x=0., ctr_y=0., area=None, wavelength=None): fn = field_name[0] + '_{' + field_name[1:] + '}' title = 'Mode %i |%s| Profile' % (mode_number, fn) if n_eff: title += ', n_{eff}: ' + '{:.3f}'.format(n_eff.real) if wavelength: title += ', λ = %s ' % '{:.3f} µm'.format(wavelength) if area: title += ', A_%s: ' % field_name[1] + '{:.1f}\%'.format(area) if subtitle: title += '\n{/*0.7 %s}' % subtitle args = { 'title': title, 'x_pts': self._structure.xc_pts, 'y_pts': self._structure.yc_pts, 'x_min': self._structure.xc_min, 'x_max': self._structure.xc_max, 'y_min': self._structure.yc_min, 'y_max': self._structure.yc_max, 'x_step': self._structure.x_step, 'y_step': self._structure.y_step, 'filename_data': filename_mode, 'filename_image': None, 'e2_x': e2_x, 'e2_y': e2_y, 'ctr_x': ctr_x, 'ctr_y': ctr_y } filename_image_prefix, _ = os.path.splitext(filename_mode) filename_image = filename_image_prefix + '.png' args['filename_image'] = filename_image gp.gnuplot(self._path + 'mode.gpi', args) gp.trim_pad_image(filename_image) return args
def write_to_file(self, filename='material_index.dat', plot=True): """ Write the refractive index profile to file. Args: filename (str): The nominal filename the refractive index data should be saved to. plot (bool): `True` if plots should be generates, otherwise `False`. Default is `True`. """ path = os.path.dirname(sys.modules[__name__].__file__) + '/' with open(filename, 'w') as fs: for n_row in np.abs(self.n[::-1]): n_str = ','.join([str(v) for v in n_row]) fs.write(n_str + '\n') if plot: filename_image_prefix, _ = os.path.splitext(filename) filename_image = filename_image_prefix + '.png' args = { 'title': 'Refractive Index Profile', 'x_pts': self.x_pts, 'y_pts': self.y_pts, 'x_min': self.x_min, 'x_max': self.x_max, 'y_min': self.y_min, 'y_max': self.y_max, 'filename_data': filename, 'filename_image': filename_image } if MPL: heatmap = np.loadtxt(args['filename_data'], delimiter=',') plt.clf() plt.title(args['title']) plt.xlabel('$x$') plt.ylabel('$y$') im = plt.imshow(np.flipud(heatmap), extent=(args['x_min'], args['x_max'], args['y_min'], args['y_max']), aspect="equal", cmap='Blues') im_ratio = heatmap.shape[0] / heatmap.shape[1] plt.colorbar(im, fraction=0.046 * im_ratio, pad=0.04) plt.savefig(filename_image, bbox_inches='tight', dpi=300) else: gp.gnuplot(path + 'structure.gpi', args)
def _plot_n_effs(self, filename_n_effs, filename_te_fractions, xlabel, ylabel, title): args = { "titl": title, "xlab": xlabel, "ylab": ylabel, "filename_data": filename_n_effs, "filename_frac_te": filename_te_fractions, "filename_image": None, "num_modes": len(self.modes), } filename_image_prefix, _ = os.path.splitext(filename_n_effs) filename_image = filename_image_prefix + ".png" args["filename_image"] = filename_image if MPL: data = np.loadtxt(args["filename_data"], delimiter=",").T data2 = np.loadtxt(args["filename_frac_te"], delimiter=",")[:, 1:].T * 100 plt.clf() plt.title(args["titl"]) plt.xlabel(args["xlab"]) plt.ylabel(args["ylab"]) import matplotlib.colors as mcolors import matplotlib.cm as cm colormap = cm.plasma normalize = mcolors.Normalize(vmin=0, vmax=100) for i in range(args["num_modes"]): sc = plt.scatter(data[0], data[i + 1], c=data2[i], cmap=colormap, norm=normalize, zorder=2) plt.plot(data[0], data[i + 1], 'k-', zorder=1) cbar = plt.colorbar(sc) cbar.set_label('TE fraction [%]') plt.savefig(args["filename_image"], dpi=300) else: gp.gnuplot(self._path + "n_effs.gpi", args, silent=False) gp.trim_pad_image(filename_image) return args
def _plot_n_effs(self, filename_n_effs, xlabel, title): args = { 'titl': title, 'xlab': xlabel, 'ylab': 'n_{eff}', 'filename_data': filename_n_effs, 'filename_image': None, 'num_modes': len(self.modes) } filename_image_prefix, _ = os.path.splitext(filename_n_effs) filename_image = filename_image_prefix + '.png' args['filename_image'] = filename_image gp.gnuplot(self._path + 'n_effs.gpi', args, silent=False) gp.trim_pad_image(filename_image) return args
def write_to_file(self, filename='material_index.dat', plot=True): ''' Write the refractive index profile to file. Args: filename (str): The nominal filename the refractive index data should be saved to. plot (bool): `True` if plots should be generates, otherwise `False`. Default is `True`. ''' path = os.path.dirname(sys.modules[__name__].__file__) + '/' dir_plot = 'material_index/' if not os.path.exists(dir_plot): os.makedirs(dir_plot) for axis, name in zip(self.axes, self.axes_str): root, ext = os.path.splitext(filename) fn = dir_plot + root + '_' + name + ext with open(fn, 'w') as fs: for n_row in np.abs(axis.n[::-1]): n_str = ','.join([str(v) for v in n_row]) fs.write(n_str + '\n') if plot: filename_image_prefix, _ = os.path.splitext(fn) filename_image = filename_image_prefix + '.png' args = { 'title': 'Refractive Index Profile: %s' % name, 'x_pts': self.xx.x_pts, 'y_pts': self.xx.y_pts, 'x_min': self.xx.x_min, 'x_max': self.xx.x_max, 'y_min': self.xx.y_min, 'y_max': self.xx.y_max, 'filename_data': fn, 'filename_image': filename_image } gp.gnuplot(path + 'structure.gpi', args, silent=False)
def _plot_mode( self, field_name, mode_number, filename_mode, n_eff=None, subtitle="", e2_x=0.0, e2_y=0.0, ctr_x=0.0, ctr_y=0.0, area=None, wavelength=None, ): fn = field_name[0] + "_{" + field_name[1:] + "}" if MPL: title = r"Mode %i $|%s|$ Profile" % (mode_number, fn) else: title = r"Mode %i |%s| Profile" % (mode_number, fn) if n_eff: if MPL: title += r", $n_{eff}$: " + "{:.3f}".format(n_eff.real) else: title += ", n_{eff}: " + "{:.3f}".format(n_eff.real) if wavelength: if MPL: title += r", $\lambda = %s " % "{:.3f} \mu$m".format( wavelength) else: title += r", $\lambda = %s " % "{:.3f} \mu$m".format( wavelength) if area: if MPL: title += ", $A_%s$: " % field_name[1] + "{:.1f}%".format(area) else: title += ", A_%s: " % field_name[1] + "{:.1f}\%".format(area) if subtitle: if MPL: title2 = "\n$%s$" % subtitle else: title += "\n{/*0.7 %s}" % subtitle args = { "title": title, "x_pts": self._structure.xc_pts, "y_pts": self._structure.yc_pts, "x_min": self._structure.xc_min, "x_max": self._structure.xc_max, "y_min": self._structure.yc_min, "y_max": self._structure.yc_max, "x_step": self._structure.x_step, "y_step": self._structure.y_step, "filename_data": filename_mode, "filename_image": None, "e2_x": e2_x, "e2_y": e2_y, "ctr_x": ctr_x, "ctr_y": ctr_y, } filename_image_prefix, _ = os.path.splitext(filename_mode) filename_image = filename_image_prefix + ".png" args["filename_image"] = filename_image if MPL: heatmap = np.loadtxt(filename_mode, delimiter=",") plt.clf() plt.suptitle(title, y=0.88) if subtitle: plt.rcParams.update({"axes.titlesize": "small"}) plt.title(title2) plt.xlabel("x") plt.ylabel("y") basic_cols = [ '#adff2f', '#0000ff', '#000000', '#FF0000', '#ffff00' ] from matplotlib.colors import LinearSegmentedColormap cm = LinearSegmentedColormap.from_list('modecmap', basic_cols) if abs(np.max(heatmap)) > abs(np.min(heatmap)): inv = 1 smm = abs(np.max(heatmap)) else: inv = -1 smm = abs(np.min(heatmap)) im = plt.imshow( np.flipud(heatmap) * inv, extent=( args["x_min"], args["x_max"], args["y_min"], args["y_max"], ), aspect="equal", cmap=cm, vmin=-smm, vmax=smm, ) im_ratio = heatmap.shape[0] / heatmap.shape[1] plt.colorbar(im, fraction=0.046 * im_ratio, pad=0.04) nbounds = np.invert(compare_neighbors(np.real(self._structure.n))) im2 = np.zeros(nbounds.shape + (4, )) # Add RGBA column im2[:, :, 3] = nbounds # Set A value (only boundaries are opaque) im2[:, :, 0:3] = [ 1, 1, 1 ] # Set RGB value to white (1 is 255 as the array dtype=float) plt.imshow(im2[1:, :-1], extent=( args["x_min"], args["x_max"], args["y_min"], args["y_max"], ), aspect="equal", interpolation='none') plt.savefig(filename_image, bbox_inches='tight', dpi=300) else: gp.gnuplot(self._path + "mode.gpi", args) gp.trim_pad_image(filename_image) return args
import numpy as np import gnuplotpy as gp amplitude = 3. x = np.linspace(0., 2 * 3.14, 100) y = amplitude * np.sin(x) args = { 'the_title': 'Example 1', 'amp': amplitude, 'x_max': x[-1], 'filename': 'example1.png' } data = [x, y] gp.gnuplot('example1.gpi', args, data)
def _plot_mode( self, field_name, mode_number, filename_mode, n_eff=None, subtitle="", e2_x=0.0, e2_y=0.0, ctr_x=0.0, ctr_y=0.0, area=None, wavelength=None, ): fn = field_name[0] + "_{" + field_name[1:] + "}" if MPL: title = r"Mode %i $|%s|$ Profile" % (mode_number, fn) else: title = r"Mode %i |%s| Profile" % (mode_number, fn) if n_eff: if MPL: title += r", $n_{eff}$: " + "{:.3f}".format(n_eff.real) else: title += ", n_{eff}: " + "{:.3f}".format(n_eff.real) if wavelength: if MPL: title += r", $\lambda = %s " % "{:.3f} \mu$m".format( wavelength) else: title += r", $\lambda = %s " % "{:.3f} \mu$m".format( wavelength) if area: if MPL: title += ", $A_%s$: " % field_name[1] + "{:.1f}%".format(area) else: title += ", A_%s: " % field_name[1] + "{:.1f}\%".format(area) if subtitle: if MPL: title2 = "\n$%s$" % subtitle else: title += "\n{/*0.7 %s}" % subtitle args = { "title": title, "x_pts": self._structure.xc_pts, "y_pts": self._structure.yc_pts, "x_min": self._structure.xc_min, "x_max": self._structure.xc_max, "y_min": self._structure.yc_min, "y_max": self._structure.yc_max, "x_step": self._structure.x_step, "y_step": self._structure.y_step, "filename_data": filename_mode, "filename_image": None, "e2_x": e2_x, "e2_y": e2_y, "ctr_x": ctr_x, "ctr_y": ctr_y, } filename_image_prefix, _ = os.path.splitext(filename_mode) filename_image = filename_image_prefix + ".png" args["filename_image"] = filename_image if MPL: heatmap = np.loadtxt(filename_mode, delimiter=",") plt.clf() plt.suptitle(title) if subtitle: plt.rcParams.update({"axes.titlesize": "small"}) plt.title(title2) plt.xlabel("x") plt.ylabel("y") plt.imshow( np.flipud(heatmap), extent=( args["x_min"], args["x_max"], args["y_min"], args["y_max"], ), aspect="auto", ) plt.colorbar() plt.savefig(filename_image) else: gp.gnuplot(self._path + "mode.gpi", args) gp.trim_pad_image(filename_image) return args
import numpy as np import gnuplotpy as gp amplitude = 3. x = np.linspace(0., 2*3.14, 100) y = amplitude*np.sin(x) args = { 'the_title': 'Example 1', 'amp': amplitude, 'x_max': x[-1], 'filename': 'example1.png' } data = [x, y] gp.gnuplot('test.gpi', args, data)