Fix saving lists of arrays with recent versions of numpy
[qpms.git] / misc / infiniterectlat-k0realfreqsvd.py
blobee9e2daac68b48a5d334124865b10cfa383ea3ee
1 #!/usr/bin/env python3
3 import math
4 from qpms.argproc import ArgParser, annotate_pdf_metadata
6 ap = ArgParser(['rectlattice2d', 'single_particle', 'single_lMax', 'omega_seq'])
7 ap.add_argument("-o", "--output", type=str, required=False, help='output path (if not provided, will be generated automatically)')
8 ap.add_argument("-O", "--plot-out", type=str, required=False, help="path to plot output (optional)")
9 ap.add_argument("-P", "--plot", action='store_true', help="if -p not given, plot to a default path")
10 ap.add_argument("-s", "--singular_values", type=int, default=10, help="Number of singular values to plot")
11 ap.add_argument("--D2", action='store_true', help="Use D2h symmetry even if the x and y periods are equal")
13 a=ap.parse_args()
15 import logging
16 logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
18 px, py = a.period
20 #Important! The particles are supposed to be of D2h/D4h symmetry
21 thegroup = 'D4h' if px == py and not a.D2 else 'D2h'
23 particlestr = ("sph" if a.height is None else "cyl") + ("_r%gnm" % (a.radius*1e9))
24 if a.height is not None: particlestr += "_h%gnm" % (a.height * 1e9)
25 defaultprefix = "%s_p%gnmx%gnm_m%s_bg%s_f(%g..%g..%g)eV_L%d_SVGamma" % (
26 particlestr, px*1e9, py*1e9, str(a.material), str(a.background), *(a.eV_seq), a.lMax)
27 logging.info("Default file prefix: %s" % defaultprefix)
30 import numpy as np
31 import qpms
32 import warnings
33 from qpms.cybspec import BaseSpec
34 from qpms.cytmatrices import CTMatrix, TMatrixGenerator
35 from qpms.qpms_c import Particle, pgsl_ignore_error
36 from qpms.cymaterials import EpsMu, EpsMuGenerator, LorentzDrudeModel, lorentz_drude
37 from qpms.cycommon import DebugFlags, dbgmsg_enable
38 from qpms import FinitePointGroup, ScatteringSystem, BesselType, eV, hbar
39 from qpms.symmetries import point_group_info
40 eh = eV/hbar
42 # not used; TODO:
43 irrep_labels = {"B2''":"$B_2''$",
44 "B2'":"$B_2'$",
45 "A1''":"$A_1''$",
46 "A1'":"$A_1'$",
47 "A2''":"$A_2''$",
48 "B1''":"$B_1''$",
49 "A2'":"$A_2'$",
50 "B1'":"$B_1'$",
51 "E'":"$E'$",
52 "E''":"$E''$",}
54 dbgmsg_enable(DebugFlags.INTEGRATION)
56 a1 = ap.direct_basis[0]
57 a2 = ap.direct_basis[1]
59 #Particle positions
60 orig_x = [0]
61 orig_y = [0]
62 orig_xy = np.stack(np.meshgrid(orig_x,orig_y),axis=-1)
64 omegas = ap.omegas
66 logging.info("%d frequencies from %g to %g eV" % (len(omegas), omegas[0]/eh, omegas[-1]/eh))
68 bspec = BaseSpec(lMax = a.lMax)
69 nelem = len(bspec)
70 # The parameters here should probably be changed (needs a better qpms_c.Particle implementation)
71 pp = Particle(orig_xy[0][0], ap.tmgen, bspec=bspec)
73 ss, ssw = ScatteringSystem.create([pp], ap.background_emg, omegas[0], latticebasis=ap.direct_basis)
74 k = np.array([0.,0.,0])
75 # Auxillary finite scattering system for irrep decomposition, quite a hack
76 ss1, ssw1 = ScatteringSystem.create([pp], ap.background_emg, omegas[0],sym=FinitePointGroup(point_group_info[thegroup]))
78 wavenumbers = np.empty(omegas.shape)
79 SVs = [None] * ss1.nirreps
80 for iri in range(ss1.nirreps):
81 SVs[iri] = np.empty(omegas.shape+(ss1.saecv_sizes[iri],))
82 for i, omega in enumerate(omegas):
83 ssw = ss(omega)
84 wavenumbers[i] = ssw.wavenumber.real
85 if ssw.wavenumber.imag:
86 warnings.warn("Non-zero imaginary wavenumber encountered")
87 with pgsl_ignore_error(15): # avoid gsl crashing on underflow; maybe not needed
88 ImTW = ssw.modeproblem_matrix_full(k)
89 for iri in range(ss1.nirreps):
90 if ss1.saecv_sizes[iri] == 0:
91 continue
92 ImTW_packed = ss1.pack_matrix(ImTW, iri)
93 SVs[iri][i] = np.linalg.svd(ImTW_packed, compute_uv = False)
95 outfile = defaultprefix + ".npz" if a.output is None else a.output
96 np.savez(outfile, meta={**vars(a), 'qpms_version' : qpms.__version__()}, omegas=omegas, wavenumbers=wavenumbers, SVs=np.concatenate(SVs, axis=-1), irrep_names=ss1.irrep_names, irrep_sizes=ss1.saecv_sizes, unitcell_area=ss.unitcell_volume
98 logging.info("Saved to %s" % outfile)
101 if a.plot or (a.plot_out is not None):
102 import matplotlib
103 matplotlib.use('pdf')
104 from matplotlib import pyplot as plt
105 from matplotlib.backends.backend_pdf import PdfPages
107 fig = plt.figure()
108 ax = fig.add_subplot(111)
109 cc = plt.rcParams['axes.prop_cycle']()
110 for iri in range(ss1.nirreps):
111 cargs = next(cc)
112 nlines = min(a.singular_values, ss1.saecv_sizes[iri])
113 for i in range(nlines):
114 ax.plot(omegas/eh, SVs[iri][:,-1-i],
115 label= None if i else irrep_labels[ss1.irrep_names[iri]],
116 **cargs)
117 ax.set_ylim([0,1.1])
118 ax.set_xlabel('$\hbar \omega / \mathrm{eV}$')
119 ax.set_ylabel('Singular values')
120 ax.legend()
122 plotfile = defaultprefix + ".pdf" if a.plot_out is None else a.plot_out
123 with PdfPages(plotfile) as pdf:
124 pdf.savefig(fig)
125 annotate_pdf_metadata(pdf, scriptname='infiniterectlat-k0realfreqsvd.py')
127 exit(0)