From 70d03f75aa34f4fb07e7fb3e84a09474858dc1d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Ne=C4=8Dada?= Date: Thu, 2 Apr 2020 18:27:43 +0300 Subject: [PATCH] Argproc: waves with polarisation; update finiterectlat-scatter.py Former-commit-id: a24428bd19d90ad6d13ab3cfe4d1c0fc406dc451 --- misc/finiterectlat-scatter.py | 67 +++++++++++++++--------------- qpms/argproc.py | 76 +++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 32 deletions(-) diff --git a/misc/finiterectlat-scatter.py b/misc/finiterectlat-scatter.py index 5ee8c57..485ef22 100755 --- a/misc/finiterectlat-scatter.py +++ b/misc/finiterectlat-scatter.py @@ -4,11 +4,8 @@ import math from qpms.argproc import ArgParser -ap = ArgParser(['rectlattice2d_finite', 'single_particle', 'single_lMax', 'single_omega']) -ap.add_argument("-k", '--kx-lim', nargs=2, type=float, required=True, help='k vector', metavar=('KX_MIN', 'KX_MAX')) -# ap.add_argument("--kpi", action='store_true', help="Indicates that the k vector is given in natural units instead of SI, i.e. the arguments given by -k shall be automatically multiplied by pi / period (given by -p argument)") +ap = ArgParser(['rectlattice2d_finite', 'single_particle', 'single_lMax', 'single_omega', 'planewave']) ap.add_argument("-o", "--output", type=str, required=False, help='output path (if not provided, will be generated automatically)') -ap.add_argument("-N", type=int, default="151", help="Number of angles") ap.add_argument("-O", "--plot-out", type=str, required=False, help="path to plot output (optional)") ap.add_argument("-P", "--plot", action='store_true', help="if -p not given, plot to a default path") ap.add_argument("-g", "--save-gradually", action='store_true', help="saves the partial result after computing each irrep") @@ -22,15 +19,11 @@ logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO) Nx, Ny = a.size px, py = a.period -particlestr = ("sph" if a.height is None else "cyl") + ("_r%gnm" % (a.radius*1e9)) -if a.height is not None: particlestr += "_h%gnm" % (a.height * 1e9) -defaultprefix = "%s_p%gnmx%gnm_%dx%d_m%s_n%g_angles(%g_%g)_Ey_f%geV_L%d_cn%d" % ( - particlestr, px*1e9, py*1e9, Nx, Ny, str(a.material), a.refractive_index, a.kx_lim[0], a.kx_lim[1], a.eV, a.lMax, a.N) -logging.info("Default file prefix: %s" % defaultprefix) - import numpy as np import qpms +import math +from qpms.qpms_p import cart2sph, sph2cart, sph_loccart2cart, sph_loccart_basis from qpms.cybspec import BaseSpec from qpms.cytmatrices import CTMatrix, TMatrixGenerator from qpms.qpms_c import Particle @@ -39,6 +32,13 @@ from qpms.cycommon import DebugFlags, dbgmsg_enable from qpms import FinitePointGroup, ScatteringSystem, BesselType, eV, hbar from qpms.symmetries import point_group_info eh = eV/hbar +pi = math.pi + +particlestr = ("sph" if a.height is None else "cyl") + ("_r%gnm" % (a.radius*1e9)) +if a.height is not None: particlestr += "_h%gnm" % (a.height * 1e9) +defaultprefix = "%s_p%gnmx%gnm_%dx%d_m%s_n%g_φ%gπ_θ(%g_%g)π_ψ%gπ_χ%gπ_f%geV_L%d" % ( + particlestr, px*1e9, py*1e9, Nx, Ny, str(a.material), a.refractive_index, a.phi/pi, np.amin(a.theta)/pi, np.amax(a.theta)/pi, a.psi/pi, a.chi/pi, a.eV, a.lMax, ) +logging.info("Default file prefix: %s" % defaultprefix) dbgmsg_enable(DebugFlags.INTEGRATION) @@ -56,23 +56,24 @@ Tmatrix = ap.tmgen(bspec, ap.omega) particles= [Particle(orig_xy[i], Tmatrix) for i in np.ndindex(orig_xy.shape[:-1])] sym = FinitePointGroup(point_group_info['D2h']) -ss = ScatteringSystem(particles, sym) +ss, ssw = ScatteringSystem.create(particles, ap.background_emg, omega, sym=sym) wavenumber = ap.background_epsmu.k(omega).real # Currently, ScatteringSystem does not "remember" frequency nor wavenumber -sinalpha_list = np.linspace(a.kx_lim[0],a.kx_lim[1],a.N) +## Plane wave data +a.theta = np.array(a.theta) +k_sph_list = np.stack((np.broadcast_to(wavenumber, a.theta.shape), a.theta, np.broadcast_to(a.phi, a.theta.shape)), axis=-1) +sψ, cψ = math.sin(a.psi), math.cos(a.psi) +sχ, cχ = math.sin(a.chi), math.cos(a.chi) +E_sph = (0., cψ*cχ + 1j*sψ*sχ, sψ*cχ + 1j*cψ*sχ) -# Plane wave data -E_cart_list = np.empty((a.N,3), dtype=complex) -E_cart_list[:,:] = np.array((0,1,0))[None,:] -k_cart_list = np.empty((a.N,3), dtype=float) -k_cart_list[:,0] = sinalpha_list -k_cart_list[:,1] = 0 -k_cart_list[:,2] = np.sqrt(1-sinalpha_list**2) -k_cart_list *= wavenumber +k_cart_list = sph2cart(k_sph_list) +E_cart_list = sph_loccart2cart(E_sph, k_sph_list) -σ_ext_list_ir = np.empty((a.N, ss.nirreps), dtype=float) -σ_scat_list_ir = np.empty((a.N, ss.nirreps), dtype=float) +npoints = a.theta.shape[0] + +σ_ext_list_ir = np.empty((npoints, ss.nirreps), dtype=float) +σ_scat_list_ir = np.empty((npoints, ss.nirreps), dtype=float) outfile_tmp = defaultprefix + ".tmp" if a.output is None else a.output + ".tmp" @@ -80,15 +81,15 @@ for iri in range(ss.nirreps): logging.info("processing irrep %d/%d" % (iri, ss.nirreps)) LU = None # to trigger garbage collection before the next call translation_matrix = None - LU = ss.scatter_solver(wavenumber,iri) + LU = ssw.scatter_solver(iri) logging.info("LU solver created") translation_matrix = ss.translation_matrix_packed(wavenumber, iri, BesselType.REGULAR) + np.eye(ss.saecv_sizes[iri]) logging.info("auxillary translation matrix created") - for j in range(a.N): + for j in range(npoints): # the following two could be calculated only once, but probably not a big deal ã = ss.planewave_full(k_cart=k_cart_list[j], E_cart=E_cart_list[j]) - Tã = ss.apply_Tmatrices_full(ã) + Tã = ssw.apply_Tmatrices_full(ã) Tãi = ss.pack_vector(Tã, iri) ãi = ss.pack_vector(ã, iri) @@ -97,7 +98,7 @@ for iri in range(ss.nirreps): σ_scat_list_ir[j, iri] = np.vdot(fi,np.dot(translation_matrix, fi)).real/wavenumber**2 if a.save_gradually: iriout = outfile_tmp + ".%d" % iri - np.savez(iriout, iri=iri, meta=vars(a), sinalpha=sinalpha_list, k_cart = k_cart_list, E_cart=E_cart_list, + np.savez(iriout, iri=iri, meta=vars(a), k_sph=k_sph_list, k_cart = k_cart_list, E_cart=E_cart_list, E_sph=np.array(E_sph), omega=omega, wavenumber=wavenumber, σ_ext_list_ir=σ_ext_list_ir[:,iri], σ_scat_list_ir=σ_scat_list_ir[:,iri]) logging.info("partial results saved to %s"%iriout) @@ -108,8 +109,9 @@ for iri in range(ss.nirreps): outfile = defaultprefix + ".npz" if a.output is None else a.output -np.savez(outfile, meta=vars(a), sinalpha=sinalpha_list, k_cart = k_cart_list, E_cart=E_cart_list, σ_ext=σ_ext,σ_abs=σ_abs,σ_scat=σ_scat, - σ_ext_ir=σ_ext_list_ir,σ_abs_ir=σ_abs_list_ir,σ_scat_ir=σ_scat_list_ir, omega=omega, wavenumber=wavenumber +np.savez(outfile, meta=vars(a), k_sph=k_sph_list, k_cart = k_cart_list, E_cart=E_cart_list, E_sph=np.array(E_sph), + σ_ext=σ_ext,σ_abs=σ_abs,σ_scat=σ_scat, + σ_ext_ir=σ_ext_list_ir,σ_abs_ir=σ_abs_list_ir,σ_scat_ir=σ_scat_list_ir, omega=omega, wavenumber=wavenumber ) logging.info("Saved to %s" % outfile) @@ -121,11 +123,12 @@ if a.plot or (a.plot_out is not None): fig = plt.figure() ax = fig.add_subplot(111) - ax.plot(sinalpha_list, σ_ext*1e12,label='$\sigma_\mathrm{ext}$') - ax.plot(sinalpha_list, σ_scat*1e12, label='$\sigma_\mathrm{scat}$') - ax.plot(sinalpha_list, σ_abs*1e12, label='$\sigma_\mathrm{abs}$') + sintheta = np.sin(a.theta) + ax.plot(sintheta, σ_ext*1e12,label='$\sigma_\mathrm{ext}$') + ax.plot(sintheta, σ_scat*1e12, label='$\sigma_\mathrm{scat}$') + ax.plot(sintheta, σ_abs*1e12, label='$\sigma_\mathrm{abs}$') ax.legend() - ax.set_xlabel('$\sin\\alpha$') + ax.set_xlabel('$\sin\\theta$') ax.set_ylabel('$\sigma/\mathrm{\mu m^2}$') plotfile = defaultprefix + ".pdf" if a.plot_out is None else a.plot_out diff --git a/qpms/argproc.py b/qpms/argproc.py index ce5b12d..1502cda 100644 --- a/qpms/argproc.py +++ b/qpms/argproc.py @@ -20,8 +20,73 @@ class AppendTupleAction(argparse.Action): setattr(args, self.dest, list()) getattr(args, self.dest).append(tuple(values)) +def float_range(string): + """Tries to parse a string either as one individual float value + or one of the following patterns: + + first:last:increment + first:last|steps + first:last + + (The last one is equivalent to first:last|50.) + Returns either float or numpy array. + """ + try: + res = float(string) + return res + except ValueError: + import re + steps = None + match = re.match(r's?([^:]+):([^|]+)\|(.+)', string) + if match: + #print("first:last|steps", match.group(1,2,3)) + steps = int(match.group(3)) + else: + match = re.match(r's?([^:]+):([^:]+):(.+)', string) + if match: + #print("first:last:increment", match.group(1,2,3)) + increment = float(match.group(3)) + else: + match = re.match(r's?([^:]+):(.+)', string) + if match: + #print("first:last", match.group(1,2)) + steps = 50 + else: + argparse.ArgumentTypeError('Invalid float/sequence format: "%s"' % string) + first = float(match.group(1)) + last = float(match.group(2)) + import numpy as np + if steps is not None: + return np.linspace(first, last, num=steps) + else: + return np.arange(first, last, increment) + class ArgParser: ''' Common argument parsing engine for QPMS python CLI scripts. ''' + + def __add_planewave_argparse_group(ap): + pwgrp = ap.add_argument_group('Incident wave specification', """ + Incident wave direction is given in terms of ISO polar and azimuthal angles θ, φ, + which translate into cartesian coordinates as r̂ = (x, y, z) = (sin(θ) cos(φ), sin(θ) sin(φ), cos(θ)). + + Wave polarisation is given in terms of parameters ψ, χ, where ψ is the angle between a polarisation + ellipse axis and meridian tangent θ̂, and tg χ determines axes ratio; + the electric field in the origin is then + + E⃗ = cos(χ) (cos(ψ) θ̂ + sin(ψ) φ̂) + i sin(χ) (sin(ψ) θ̂ + cos(ψ) φ̂). + + All the angles are given as multiples of π/2. + """ # TODO EXAMPLES + ) + pwgrp.add_argument("-φ", "--phi", type=float, default=0, + help='Incident wave asimuth in multiples of π/2.') + pwgrp.add_argument("-θ", "--theta", type=float_range, default=0, + help='Incident wave polar angle in multiples of π/2. This might be a sequence in format FIRST:LAST:INCREMENT.') + pwgrp.add_argument("-ψ", "--psi", type=float, default=0, + help='Angle between polarisation ellipse axis and meridian tangent θ̂ in multiples of π/2.') + pwgrp.add_argument("-χ", "--chi", type=float, default=0, + help='Polarisation parameter χ in multiples of π/2. 0 for linear, 0.5 for circular pol.') + atomic_arguments = { 'rectlattice2d_periods': lambda ap: ap.add_argument("-p", "--period", type=float, nargs='+', required=True, help='square/rectangular lattice periods', metavar=('px','[py]')), 'rectlattice2d_counts': lambda ap: ap.add_argument("--size", type=int, nargs=2, required=True, help='rectangular array size (particle column, row count)', metavar=('NCOLS', 'NROWS')), @@ -40,6 +105,7 @@ class ArgParser: 'plot_out': lambda ap: ap.add_argument("-O", "--plot-out", type=str, required=False, help="path to plot output (optional)"), 'plot_do': lambda ap: ap.add_argument("-P", "--plot", action='store_true', help="if -p not given, plot to a default path"), 'lattice2d_basis': lambda ap: ap.add_argument("-b", "--basis-vector", action=AppendTupleAction, help="basis vector in xy-cartesian coordinates (two required)", dest='basis_vectors', metavar=('X', 'Y')), + 'planewave_pol_angles': __add_planewave_argparse_group, } feature_sets_available = { # name : (description, dependencies, atoms not in other dependencies, methods called after parsing) @@ -51,6 +117,7 @@ class ArgParser: 'lattice2d': ("Specification of a generic 2d lattice (spanned by the x,y axes)", (), ('lattice2d_basis',), ('_eval_lattice2d',)), 'rectlattice2d': ("Specification of a rectangular 2d lattice; conflicts with lattice2d", (), ('rectlattice2d_periods',), ('_eval_rectlattice2d',)), 'rectlattice2d_finite': ("Specification of a rectangular 2d lattice; conflicts with lattice2d", ('rectlattice2d',), ('rectlattice2d_counts',), ()), + 'planewave': ("Specification of a normalised plane wave (typically used for scattering) with a full polarisation state", (), ('planewave_pol_angles',), ("_process_planewave_angles",)), } @@ -157,3 +224,12 @@ class ArgParser: self.reciprocal_basis1 = np.linalg.inv(self.direct_basis) self.reciprocal_basis2pi = 2 * np.pi * self.reciprocal_basis1 + def _process_planewave_angles(self): #feature: planewave + import math + pi2 = math.pi/2 + a = self.args + a.chi = a.chi * pi2 + a.psi = a.psi * pi2 + a.theta = a.theta * pi2 + a.phi = a.phi * pi2 +