Skip to content

Commit 68c3b3c

Browse files
author
Herbert D Ludowieg
authored
Merge pull request #275 from herbertludowieg/master
Some changes for codacy
2 parents c09b083 + 1e5c47d commit 68c3b3c

12 files changed

Lines changed: 104 additions & 70 deletions

File tree

.github/workflows/branch.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name: Branch
33
on:
44
push:
55
branches-ignore:
6-
- master
6+
- [master, main]
77

88
concurrency:
99
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
@@ -54,7 +54,7 @@ jobs:
5454
- name: Run Tests
5555
uses: ./.github/workflows/run-tests
5656
with:
57-
coverage-artifact-name: ${{ needs.coverage-artifact-name.outputs.ref }}
57+
coverage-artifact-name: code-coverage
5858

5959
codacy-coverage-reporter:
6060
runs-on: ubuntu-latest
@@ -65,7 +65,7 @@ jobs:
6565
- name: Download Coverage Report
6666
uses: actions/download-artifact@v2
6767
with:
68-
name: code-coverage-report-${{ needs.coverage-artifact-name.outputs.ref }}
68+
name: code-coverage-report-code-coverage
6969
- name: Run codacy-coverage-reporter
7070
uses: codacy/codacy-coverage-reporter-action@v1
7171
with:

.github/workflows/master.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ name: Master
33
on:
44
push:
55
branches:
6-
master
6+
[master, main]
77

88
concurrency:
99
group: ${{ github.workflow }}

.github/workflows/pull-request.yml

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
name: Branch
2+
3+
on:
4+
pull_request:
5+
6+
concurrency:
7+
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
8+
cancel-in-progress: true
9+
10+
jobs:
11+
12+
support-matrix:
13+
runs-on: ubuntu-latest
14+
outputs:
15+
matrix: ${{ steps.set-matrix.outputs.matrix }}
16+
steps:
17+
- uses: actions/checkout@v2
18+
- id: set-matrix
19+
run: echo "::set-output name=matrix::$(python cicd-matrix.py)"
20+
21+
coverage-artifact-name:
22+
runs-on: ubuntu-latest
23+
outputs:
24+
ref: ${{ steps.get-ref.outputs.ref }}
25+
steps:
26+
- id: get-ref
27+
run: |
28+
ref=${{ github.ref }}
29+
echo "::set-output name=ref::${ref////-}"
30+
31+
run-tests:
32+
needs: [ support-matrix, coverage-artifact-name ]
33+
name: Test Python ${{ matrix.python-version }} on ${{ matrix.os }}
34+
runs-on: ${{ matrix.os }}
35+
strategy:
36+
fail-fast: false
37+
matrix:
38+
os: ${{ fromJson(needs.support-matrix.outputs.matrix).os }}
39+
python-version: ${{ fromJson(needs.support-matrix.outputs.matrix).python-version }}
40+
steps:
41+
- uses: actions/checkout@v2
42+
- uses: actions/setup-python@v2
43+
with:
44+
python-version: ${{ matrix.python-version }}
45+
- uses: actions/cache@v2
46+
with:
47+
path: ${{ env.pythonLocation }}
48+
key: ${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('requirements.txt') }}-${{ hashFiles('requirements.dev.txt') }}
49+
- name: Install Dependencies
50+
run: |
51+
pip install --upgrade --upgrade-strategy eager -r requirements.txt -r requirements.dev.txt -e .
52+
- name: Run Tests
53+
uses: ./.github/workflows/run-tests
54+
with:
55+
coverage-artifact-name: code-coverage
56+

.github/workflows/run-tests/action.yml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@ runs:
2020
run: pytest --doctest-modules -v
2121

2222
- name: Upload Coverage
23-
if: (runner.os == 'Linux') && (matrix.python-version == '3.8')
23+
# needs always() to make sure that even if the linux/3.8 fails it will
24+
# still upload the artifact to export coverage to codacy
25+
if: (runner.os == 'Linux') && (matrix.python-version == '3.8') && (always())
2426
uses: actions/upload-artifact@v2
2527
with:
2628
name: code-coverage-report-${{ inputs.coverage-artifact-name }}
2729
path: coverage.xml
2830
retention-days: 1
29-
31+

exatomic/adf/output.py

Lines changed: 11 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ def parse_excitation(self):
391391
while self[stop].strip(): stop += 1
392392
df = self.pandas_dataframe(start, stop, ncol=6)
393393
df.columns = ['excitation', 'energy', 'energy_ev', 'osc', 'tau', 'symmetry']
394-
nan = np.where(list(map(lambda x: any(x), df.isna().values)))[0]
394+
nan = np.where(df.isna().values)[0]
395395
df.loc[nan, 'symmetry'] = df.loc[nan, 'tau'].copy()
396396
df.loc[nan, 'tau'] = 0.0
397397
df['tau'] = df['tau'].astype(float)
@@ -536,7 +536,7 @@ def parse_frequency(self):
536536
else:
537537
start = stop + 4
538538
stop = start + natoms
539-
freqs = list(map(lambda x: float(x), self[start-2].split()))
539+
freqs = list(map(float, self[start-2].split()))
540540
ncol = len(freqs)
541541
df = self.pandas_dataframe(start, stop, ncol=1+3*ncol)
542542
tmp = list(map(lambda x: x.split('.'), df[0]))
@@ -660,26 +660,9 @@ def parse_gradient(self):
660660
self.gradient = grad
661661

662662
def parse_excitation(self):
663-
_reexc = "no. E/a.u. E/eV f"
664-
found = self.find(_reexc, keys_only=True)
665-
if not found:
666-
return
667-
# there should only be one in the entire output
668-
start = found[0] + 2
669-
stop = start
670-
while self[stop].strip(): stop += 1
671-
df = self.pandas_dataframe(start, stop, ncol=6)
672-
df.columns = ['excitation', 'energy', 'energy_ev', 'osc', 'tau', 'symmetry']
673-
nan = np.where(list(map(lambda x: any(x), df.isna().values)))[0]
674-
df.loc[nan, 'symmetry'] = df.loc[nan, 'tau'].copy()
675-
df.loc[nan, 'tau'] = 0.0
676-
df['tau'] = df['tau'].astype(float)
677-
df['excitation'] = [int(x[:-1]) for x in df['excitation'].values]
678-
df.index = df['excitation'] - 1
679-
df.drop('excitation', axis=1, inplace=True)
680-
df['frame'] = 0
681-
df['group'] = 0
682-
self.excitation = df
663+
# the output has not changed from the last few iterations
664+
# of ADF
665+
ADF.parse_excitation(self)
683666

684667
def parse_electric_dipole(self):
685668
_reexc = "Excitation energies E in a.u. and eV, dE wrt prev. cycle"
@@ -707,21 +690,20 @@ def parse_electric_dipole(self):
707690
tdm = self.pandas_dataframe(start, stop, ncol=10)
708691
tdm.dropna(axis=1, how='all', inplace=True)
709692
if tdm.shape[1] == 9:
710-
spinorbit=True
693+
# TODO: should we get the magnitude here instead?
711694
tdm.columns = ['excitation', 'energy_ev', 'osc', 'remu_x' ,'remu_y', 'remu_z',
712695
'immu_x', 'immu_y', 'immu_z']
713696
else:
714697
tdm.columns = ['excitation', 'energy_ev', 'osc', 'mu_x' ,'mu_y', 'mu_z']
715-
spinorbit=False
716698
tdm['excitation'] -= 1
717699
diff = np.setdiff1d(df['excitation'].values.flatten(),
718700
tdm['excitation'].values.flatten())
719701
if len(diff) > 0:
720-
for idx in range(len(diff)):
721-
df1 = tdm.loc[range(diff[idx])]
722-
df2 = tdm.loc[range(diff[idx], tdm.shape[0])]
723-
new_line = [diff[idx], df.loc[diff[idx], 'energy_ev'],
724-
df.loc[diff[idx], 'osc']]+[0.0]*int(len(tdm.columns)-3)
702+
for d in diff:
703+
df1 = tdm.loc[range(d)]
704+
df2 = tdm.loc[range(d, tdm.shape[0])]
705+
new_line = [d, df.loc[d, 'energy_ev'],
706+
df.loc[d, 'osc']]+[0.0]*int(len(tdm.columns)-3)
725707
new_line = pd.DataFrame([new_line], columns=tdm.columns)
726708
new_df = pd.concat([df1, new_line, df2], ignore_index=True)
727709
tdm = new_df.copy()

exatomic/adf/tape21.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,13 @@
1010

1111
from exatomic.exa.core.container import TypedMeta
1212
from exatomic.exa.core.editor import Editor
13-
from exatomic.exa.util.units import Length, Mass, Energy
1413
from exatomic.core.atom import Atom, Frequency
1514
from exatomic.core.gradient import Gradient
1615
from exatomic.core.tensor import JCoupling, NMRShielding
1716
from exatomic.base import z2sym, sym2isomass
1817
import numpy as np
1918
import pandas as pd
2019
import six
21-
import warnings
2220

2321
class MissingSection(Exception):
2422
pass
@@ -167,7 +165,6 @@ def parse_frequency(self, cart=True):
167165
# these should be the ones that ADF determines to be translations and rotations
168166
# TODO: need a test case with one imaginary frequency
169167
low = freq != 0
170-
nlow = low.shape[0]
171168
# get only the ones that are non-zero
172169
freq = freq[low]
173170
nmodes = freq.shape[0]
@@ -202,14 +199,10 @@ def parse_frequency(self, cart=True):
202199
dz = np.array(dz).flatten()
203200
freqdx = np.repeat(range(nmodes), nat)
204201
label = np.tile(self.atom['label'], nmodes)
205-
symbol = self.atom['symbol']
206-
# get the isotopic masses
207-
mass = _get_isomass(symbol)
208202
symbol = np.tile(self.atom['symbol'], nmodes)
209203
# put the data together
210204
df = pd.DataFrame({'dx': dx, 'dy': dy, 'dz': dz, 'frequency': freq,
211205
'freqdx': freqdx})
212-
cols = ['dx', 'dy', 'dz']
213206
# calculate the reduced masses
214207
if not cart:
215208
r_mass = df.groupby(['freqdx']).apply(self.rmass_mwc,
@@ -220,6 +213,7 @@ def parse_frequency(self, cart=True):
220213
df['r_mass'] = np.repeat(r_mass, nat)
221214
df['symbol'] = symbol
222215
df['label'] = label
216+
# TODO: find out if this is stored in the file anywhere
223217
df['ir_int'] = 0
224218
df['frame'] = 0
225219
self.frequency = df
@@ -311,7 +305,6 @@ def parse_gradient(self, input_order=False):
311305
self.parse_atom(input_order=input_order)
312306
symbol = self.atom.last_frame['symbol'].values
313307
Z = self.atom.last_frame['Z'].values.astype(int)
314-
nat = self.atom.last_frame.shape[0]
315308
# get the gradients
316309
ngrad = self._intme(np.array(found[_regrad]))
317310
grad = self._dfme(np.array(found[_regrad]), ngrad)
@@ -323,7 +316,6 @@ def parse_gradient(self, input_order=False):
323316
'fy': y, 'fz': z, 'symbol': symbol,
324317
'frame': 0})
325318
df = df[['atom', 'Z', 'fx', 'fy', 'fz', 'symbol', 'frame']]
326-
#for u in ['fx', 'fy', 'fz']: df[u] *= 1./Length['Angstrom', 'au']
327319
self.gradient = df
328320

329321
def parse_nmr_shielding(self):

exatomic/core/basis.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,14 +119,16 @@ def spherical_by_shell(self, program, spherical=True):
119119
def functions_by_shell(self):
120120
"""Return a series of n functions per (set, L).
121121
This does not include degenerate functions."""
122-
obj = self.groupby(self._indexes)['shell'].nunique()
122+
obj = self._revert_categories(inplace=False)
123+
obj = obj.groupby(self._indexes)['shell'].nunique()
123124
obj.index.set_names(self._indexes, inplace=True)
124125
return obj
125126

126127
def primitives_by_shell(self):
127128
"""Return a series of n primitives per (set, L).
128129
This does not include degenerate primitives."""
129-
obj = self.groupby(self._indexes)['alpha'].nunique()
130+
obj = self._revert_categories(inplace=False)
131+
obj = obj.groupby(self._indexes)['alpha'].nunique()
130132
obj.index.set_names(self._indexes, inplace=True)
131133
return obj
132134

exatomic/core/gradient.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,10 @@ def stats(self):
2323
norms = np.linalg.norm(data[cols].values, axis=1)
2424
rms = np.sqrt(np.mean(np.square(norms)))
2525
avg = np.mean(norms)
26-
max = norms.max()
27-
min = norms.min()
28-
sr = pd.Series([rms, avg, max, min], index=['rms', 'mean',
29-
'max', 'min'])
26+
max_grad = norms.max()
27+
min_grad = norms.min()
28+
sr = pd.Series([rms, avg, max_grad, min_grad],
29+
index=['rms', 'mean', 'max', 'min'])
3030
srs.append(sr)
3131
df = pd.concat(srs, axis=1, ignore_index=True).T
3232
return df
@@ -46,7 +46,7 @@ def avg_grad(self):
4646
cols = ['fx', 'fy', 'fz']
4747
arr = []
4848
for _, data in self.groupby('frame'):
49-
val = np.mean(data[cols].values)
49+
val = np.mean(data[cols].abs().values)
5050
arr.append(val)
5151
avg = pd.Series(arr)
5252
return avg

exatomic/exa/core/numerical.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,6 @@ def slice_naive(self, key):
4646
key = check_key(self, key)
4747
return cls(self.loc[key])
4848

49-
def __repr__(self):
50-
name = '.'.join([self.__module__, self.__class__.__name__])
51-
return '{0}{1}'.format(name, self.shape)
52-
5349
def __str__(self):
5450
return self.__repr__()
5551

@@ -60,7 +56,7 @@ class BaseSeries(Numerical):
6056
6157
Attributes:
6258
_sname (str): May have a required name (default None)
63-
_iname (str: May have a required index name
59+
_iname (str): May have a required index name
6460
_stype (type): May have a required value type
6561
_itype (type): May have a required index type
6662
"""
@@ -193,13 +189,20 @@ def copy(self, *args, **kwargs):
193189
cls = self.__class__ # Note that type conversion does not perform copy
194190
return cls(pd.DataFrame(self).copy(*args, **kwargs))
195191

196-
def _revert_categories(self):
192+
def _revert_categories(self, inplace=True):
197193
"""
198194
Inplace conversion to categories.
199195
"""
200-
for column, dtype in self._categories.items():
201-
if column in self.columns:
202-
self[column] = self[column].astype(dtype)
196+
if inplace:
197+
for column, dtype in self._categories.items():
198+
if column in self.columns:
199+
self[column] = self[column].astype(dtype)
200+
else:
201+
copy = self.copy()
202+
for column, dtype in copy._categories.items():
203+
if column in copy.columns:
204+
copy[column] = copy[column].astype(dtype)
205+
return copy
203206

204207
def _set_categories(self):
205208
"""

exatomic/gaussian/output.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -706,14 +706,17 @@ def parse_hessian(self):
706706
+"using this molecular orientation.")
707707
ldx = found[0] + 1
708708
dfs = []
709+
srs = []
710+
srs_old = []
709711
try:
710712
while float(self[ldx].split()[0]):
711713
d = self[ldx].split()
712714
if 'D' not in d[1]:
713715
ncols = len(d)
714716
cols = list(map(lambda x: int(x)-1, d))
715717
if cols[0] != 0:
716-
dfs.append(pd.concat(srs, axis=1).T)
718+
srs_old = srs
719+
dfs.append(pd.concat(srs_old, axis=1).T)
717720
srs = []
718721
else:
719722
arr = np.zeros(ncols)

0 commit comments

Comments
 (0)