• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

adc-connect / adcc / 16384966787

03 Jul 2025 11:29AM UTC coverage: 73.883% (+0.3%) from 73.602%
16384966787

push

github

web-flow
Restructure ExcitedStates etc for IP/EA Integration (#195)

* allow timer customization in cached_member_function

* add option to exclude the args in the timer task

* timer description if nothing was recorded

* basic restructuring of ElectronicTransition, ExcitedStates and State2States

* basic restructuring of Excitation

* add _module member variable to dispatch to the corresponding working equations

* basic restructuring for excited state properties

* enable excitation for s2s

* port dataframe export

* add state_dm

* port the remaining properties - tests passing

* * cache the MO integrals instead of the AO integrals
* remove unnecessary property decorated returns of callbacks
* implement available integrals directly in the backends

* raise Exception directly in the backends for PE and PCM

* add to_qcvars back in

* split plot_spectrum in common function on base class and adc type dependent function on child classes

* invert order of unit conversion and broadening for plot_spectrum

* add input options for lower and upper bounds of the broadened spectrum

* remove broadening min/max and allow variable width_units

* refactor the ExcitedStates.describe method

* determine the column width automatically

* move describe_amplitudes to ElectronicStates and adapt for IP/EA

* store operators in tuple on IsrMatrix

* make flake happy and remove the cache for now since it is not used anyway

* reintroduce the cache for available backends and cache them lazily

* explicitly install setupstools

* enable libtensorlight download for macos arm64

* naively update CI to macos-latest

* install llvm and use arm64 compilers

* explicitly only build for the current platform

* only set architecture for macos

* generic block_orders for secular and isr matrix

* move init complete back to secular and isr matrix

* raise more explicit exception for not implemented methods

* patch coverage not required for status check

* add token for github api request... (continued)

1176 of 1884 branches covered (62.42%)

Branch coverage included in aggregate %.

700 of 965 new or added lines in 21 files covered. (72.54%)

6 existing lines in 6 files now uncovered.

7376 of 9691 relevant lines covered (76.11%)

175662.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

10.98
/adcc/visualisation/Spectrum.py
1
#!/usr/bin/env python3
2
## vi: tabstop=4 shiftwidth=4 softtabstop=4 expandtab
3
## ---------------------------------------------------------------------
4
##
5
## Copyright (C) 2019 by the adcc authors
6
##
7
## This file is part of adcc.
8
##
9
## adcc is free software: you can redistribute it and/or modify
10
## it under the terms of the GNU General Public License as published
11
## by the Free Software Foundation, either version 3 of the License, or
12
## (at your option) any later version.
13
##
14
## adcc is distributed in the hope that it will be useful,
15
## but WITHOUT ANY WARRANTY; without even the implied warranty of
16
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
## GNU General Public License for more details.
18
##
19
## You should have received a copy of the GNU General Public License
20
## along with adcc. If not, see <http://www.gnu.org/licenses/>.
21
##
22
## ---------------------------------------------------------------------
23
import numpy as np
2✔
24

25
from . import shapefctns
2✔
26
from ..misc import requires_module
2✔
27

28

29
class Spectrum:
2✔
30
    """
31
    Class for representing arbitrary spectra. This design is strongly
32
    inspired by the approach used by pymatgen.
33
    """
34

35
    # TODO Ideas:
36
    #   - normalise()   normalise spectrum by scaling it
37
    #   - shift()       shift spectrum such that max peak is at a
38
    #                   particular posn
39
    #   - interpolate_value(self, x, order=1):
40
    #                   interpolate value by linear / polynomial interpolation
41
    #                   between existing points
42
    #  support element-wise multiplication, division, addition /
43
    #                   subtraction of spectra ?
44

45
    def __init__(self, x, y, *args, xlabel: str = None, ylabel: str = None,
2✔
46
                 **kwargs):
47
        """Pass spectrum data to initialise the class.
48

49
        To allow the copy and other functions to work properly, all arguments
50
        and keywords arguments from implementing classes should be passed here.
51

52
        Parameters
53
        ----------
54
        x : ndarray
55
            Data on the first axis
56
        y : ndarray
57
            Data on the second axis
58
        args
59
            Arguments passed to subclass upon construction
60
        kwargs
61
            Keyword arguments passed to subclass upon construction.
62
        """
63
        self.x = np.array(x).flatten()
×
64
        self.y = np.array(y).flatten()
×
NEW
65
        self.xlabel = "x" if xlabel is None else xlabel
×
NEW
66
        self.ylabel = "y" if ylabel is None else ylabel
×
67
        if self.x.size != self.y.size:
×
68
            raise ValueError("Sizes of x and y mismatch: {} versus {}."
×
69
                             "".format(self.x.size, self.y.size))
70
        self._args = args
×
71
        self._kwargs = kwargs
×
72

73
    def broaden_lines(self, width=None, shape="lorentzian", xmin=None, xmax=None):
2✔
74
        """Apply broadening to the current spectral data and
75
        return the broadened spectrum.
76

77
        Parameters
78
        ----------
79
        shape : str or callable, optional
80
            The shape of the broadening to use (lorentzian or gaussian),
81
            by default lorentzian broadening is used. This can be a callable
82
            to directly specify the function with which each line of the
83
            spectrum is convoluted.
84
        width : float, optional
85
            The width to use for the broadening (stddev for the gaussian,
86
            gamma parameter for the lorentzian).
87
            Optional if shape is a callable.
88
        xmin : float, optional
89
            Explicitly set the minimum value of the x-axis for broadening
90
        xmax : float, optional
91
            Explicitly set the maximum value of the x-axis for broadening
92
        """
93
        if not callable(shape) and width is None:
×
94
            raise ValueError("If shape is not a callable, the width parameter "
×
95
                             "is required")
96

97
        if not callable(shape):
×
98
            if not hasattr(shapefctns, shape):
×
99
                raise ValueError("Unknown broadening function: " + shape)
×
100
            shapefctn = getattr(shapefctns, shape)
×
101

102
            def shape(x, x0):
×
103
                # Empirical scaling factor to make the envelope look nice
104
                scale = width / 0.272
×
105
                return scale * shapefctn(x, x0, width)
×
106

107
        # the min and max of the underlying spectrum
NEW
108
        xmin_disc = np.min(self.x)
×
NEW
109
        xmax_disc = np.max(self.x)
×
110
        # determine a padding that is added to the left and right of the lowest
111
        # and highest point of the discrete spectrum, respectively.
112
        # But only if the user did not provide any data for min/max!
113
        if xmin is None:
×
NEW
114
            xmin = xmin_disc
×
NEW
115
            xmin_padding = max((xmax_disc - xmin_disc) / 10, 5 * width)
×
116
        else:
NEW
117
            xmin_padding = 0
×
118
        if xmax is None:
×
NEW
119
            xmax = xmax_disc
×
NEW
120
            xmax_padding = max((xmax_disc - xmin_disc) / 10, 5 * width)
×
121
        else:
NEW
122
            xmax_padding = 0
×
123

124
        n_points = min(5000, max(500, int(1000 * (xmax - xmin))))
×
NEW
125
        x = np.linspace(xmin - xmin_padding, xmax + xmax_padding, n_points)
×
126

127
        y = 0
×
128
        for center, value in zip(self.x, self.y):
×
129
            y += value * shape(x, center)
×
130

131
        cpy = self.copy()
×
132
        cpy.x = x
×
133
        cpy.y = y
×
134
        return cpy
×
135

136
    def copy(self):
2✔
137
        """Return a consistent copy of the object."""
NEW
138
        return self.__class__(
×
139
            self.x, self.y, *self._args, xlabel=self.xlabel, ylabel=self.ylabel,
140
            **self._kwargs
141
        )
142

143
    @requires_module("matplotlib")
2✔
144
    def plot(self, *args, style=None, **kwargs):
2✔
145
        """Plot the Spectrum represented by this class.
146

147
        Parameters not listed below are passed to the matplotlib plot function.
148

149
        Parameters
150
        ----------
151
        style : str, optional
152
            Use some default setup of matplotlib parameters for certain
153
            types of spectra commonly plotted. Valid are "discrete" and
154
            "continuous". By default no special style is chosen.
155
        """
156
        from matplotlib import pyplot as plt
×
157
        if style == "discrete":
×
158
            p = plt.plot(self.x, self.y, "x", *args, **kwargs)
×
159
            plt.vlines(self.x, 0, self.y, linestyle="dashed",
×
160
                       color=p[0].get_color(), linewidth=1)
161
        elif style == "continuous":
×
162
            p = plt.plot(self.x, self.y, "-", *args, **kwargs)
×
163
        elif style is None:
×
164
            p = plt.plot(self.x, self.y, *args, **kwargs)
×
165
        else:
166
            raise ValueError("Unknown style: " + str(style))
×
167
        plt.xlabel(self.xlabel)
×
168
        plt.ylabel(self.ylabel)
×
169
        # if we have negative y-values (e.g., rotatory strengths),
170
        # draw y = 0 as an extra line for clarity
171
        if np.any(self.y < 0.0):
×
172
            plt.axhline(0.0, color='gray', lw=0.5)
×
173
        return p
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc