Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tensor components csv #13

Merged
merged 4 commits into from
Nov 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ check_chemistry_file = 'qcip_tools.scripts.check_chemistry_file:main'
ct_analysis = 'qcip_tools.scripts.ct_analysis:main'
cube_radial_distribution = 'qcip_tools.scripts.cube_radial_distribution:main'
electrical_derivatives = 'qcip_tools.scripts.electrical_derivatives:main'
electrical_derivatives_from_csvtensors = 'qcip_tools.scripts.electrical_derivatives_from_csvtensors:main'
excitations = 'qcip_tools.scripts.excitations:main'
geometrical_derivatives = 'qcip_tools.scripts.geometrical_derivatives:main'
gen_character_table = 'qcip_tools.scripts.gen_character_table:main'
Expand Down
40 changes: 35 additions & 5 deletions qcip_tools/scripts/electrical_derivatives.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import qcip_tools.scripts
from qcip_tools import derivatives_e, quantities
from qcip_tools.chemistry_files import helpers, PropertyNotPresent
import platform

__version__ = '0.3'
__author__ = 'Pierre Beaujean'
Expand Down Expand Up @@ -70,6 +71,7 @@ def get_arguments_parser():
arguments_parser = argparse.ArgumentParser(description=__doc__)
arguments_parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
arguments_parser.add_argument('-csv', default=False, action='store_true')
arguments_parser.add_argument('--save-components', default=False, action='store_true')
arguments_parser.add_argument('-q', '--quiet', default=False, action='store_true')

arguments_parser.add_argument(
Expand All @@ -81,7 +83,7 @@ def get_arguments_parser():
return arguments_parser


def append_data(electrical_derivatives, to_data_frames, file_id):
def append_data(electrical_derivatives, to_data_frames, file_id, save_components=False):
representations = [
'F',
'FF',
Expand All @@ -97,13 +99,25 @@ def append_data(electrical_derivatives, to_data_frames, file_id):
'dDDd',
'xDDD',
]
components = {
'mu': [f'mu_{i}' for i in 'x y z'.split()],
'alpha': [f'alpha_{i}{j}' for i in 'x y z'.split()
for j in 'x y z'.split()],
'beta': [f'beta_{i}{j}{k}' for i in 'x y z'.split()
for j in 'x y z'.split()
for k in 'x y z'.split()],
'gamma': [f'gamma_{i}{j}{k}{m}' for i in 'x y z'.split()
for j in 'x y z'.split()
for k in 'x y z'.split()
for m in 'x y z'.split()],
}

for representation in representations:
if representation in electrical_derivatives:
freqs = [x for x in electrical_derivatives[representation].keys()]
freqs.sort(key=lambda x: derivatives_e.convert_frequency_from_string(x))

name = derivatives_e.NAMES[representation]
name = derivatives_e.NAMES[representation].replace('(', '_').replace(')', '')

# include dipole if found
kw = {}
Expand All @@ -117,19 +131,35 @@ def append_data(electrical_derivatives, to_data_frames, file_id):
if to_data_frames.get(df_name) is None:
to_data_frames[df_name] = {}
to_data_frames[df_name][file_id] = electrical_derivatives[representation][freq].properties
if save_components:
prop = name.split('_')[0]
components_dict = {}
for c, v in zip(components[prop],
electrical_derivatives[representation][freq].components.flatten()):
components_dict[c] = v
to_data_frames[df_name][file_id].update(components_dict)


def save_data(to_data_frames):
for df_name, data in to_data_frames.items():
df = pd.DataFrame(data).transpose()
df.to_csv(df_name + '.csv', sep=';')
df.index.names = ['names']
df.to_csv(df_name + '.csv')


def main():
args = get_arguments_parser().parse_args()
to_data_frames = {}

for file_name in args.infile:
if 'Windows' in platform.system():
from glob import glob
files = []
for f in args.infile:
files.extend(glob(f))
else:
files = args.infile

for file_name in files:
f = open(file_name)
infile = helpers.open_chemistry_file(f)
f.close()
Expand Down Expand Up @@ -169,7 +199,7 @@ def main():
print_tensors(electrical_derivatives, 'XDDD')

if args.csv:
append_data(electrical_derivatives, to_data_frames, infile.file_name)
append_data(electrical_derivatives, to_data_frames, infile.file_name, args.save_components)

if args.csv:
save_data(to_data_frames)
Expand Down
142 changes: 142 additions & 0 deletions qcip_tools/scripts/electrical_derivatives_from_csvtensors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
import argparse
import numpy as np
import pandas as pd
from qcip_tools import derivatives_e

__version__ = '0.1'
__author__ = 'Tarcius N. Ramos'
__maintainer__ = 'Pierre Beaujean & Tarcius N. Ramos'
__email__ = '[email protected] & [email protected]'
__status__ = 'Development'

__longdoc__ = """
Try to fetch the dipole moment and the frequency dependant (hyper)polarizabilities from a csv file,
then save the tensors and related quantities into another csv file. Rely on the availability of
``electrical_derivatives``.

"""


def get_arguments_parser(string=None):
parser = argparse.ArgumentParser(description='Extract the LoProp of a selection of domains.')
parser.add_argument('file', help='Files to be analysed.')
parser.add_argument('-o', '--output-file', help='Output base name file. Default: electrical_derivatives.csv',
default='electrical_derivatives.csv', type=str)

return parser.parse_args(string)


def _columns_to_tensor(data):
len_data = len(data)
tensor = None

if len_data == 3:
tensor = np.empty((3), dtype=float)
elif len_data == 9:
tensor = np.empty((3, 3), dtype=float)
elif len_data == 27:
tensor = np.empty((3, 3, 3), dtype=float)
elif len_data == 81:
tensor = np.empty((3, 3, 3, 3), dtype=float)

translate_coord = {'x': 0, 'y': 1, 'z': 2}

for col in data.index:
c = col.split('_')[1]
tmp = [translate_coord[x] for x in c]
tensor[tuple(tmp)] = data[col]

return tensor


def append_data(data, properties):
for k, v in properties.items():
if k not in data.keys():
data[k] = []
data[k].append(v)

return data


def main():
args = get_arguments_parser()
df = pd.read_csv(args.file)

components = {
'mu': [f'mu_{i}' for i in 'x y z'.split()],
'alpha': [f'alpha_{i}{j}' for i in 'x y z'.split()
for j in 'x y z'.split()],
'beta': [f'beta_{i}{j}{k}' for i in 'x y z'.split()
for j in 'x y z'.split()
for k in 'x y z'.split()],
'gamma': [f'gamma_{i}{j}{k}{m}' for i in 'x y z'.split()
for j in 'x y z'.split()
for k in 'x y z'.split()
for m in 'x y z'.split()],
}

col_mu = [c for c in df.columns if c in components['mu']]
col_alpha = [c for c in df.columns if c in components['alpha']]
col_beta = [c for c in df.columns if c in components['beta']]
col_gamma = [c for c in df.columns if c in components['gamma']]

new_data = {}
new_data['names'] = df['names']

if len(col_mu) != 0:
for _, row in df.iterrows():
mu = derivatives_e.ElectricDipole()
mu.components = _columns_to_tensor(row[col_mu])
mu.compute_properties()
new_data = append_data(new_data, mu.properties)
components_dict = {}
for c, v in zip(components['mu'], mu.flatten_components()):
components_dict[c] = v
new_data = append_data(new_data, components_dict)

if len(col_alpha) != 0:
for _, row in df.iterrows():
alpha = derivatives_e.PolarisabilityTensor()
alpha.components = _columns_to_tensor(row[col_alpha])
alpha.compute_properties()
new_data = append_data(new_data, alpha.properties)
components_dict = {}
for c, v in zip(components['alpha'], alpha.flatten_components()):
components_dict[c] = v
new_data = append_data(new_data, components_dict)

if len(col_beta) != 0:
for _, row in df.iterrows():
beta = derivatives_e.FirstHyperpolarisabilityTensor()
beta.components = _columns_to_tensor(row[col_beta])
kw = {}
if len(col_mu) != 0:
kw = {'dipole': row[col_mu].to_numpy()}
beta.compute_properties(**kw)
new_data = append_data(new_data, beta.properties)
components_dict = {}
for c, v in zip(components['beta'], beta.flatten_components()):
components_dict[c] = v
new_data = append_data(new_data, components_dict)

if len(col_gamma) != 0:
for _, row in df.iterrows():
gamma = derivatives_e.SecondHyperpolarizabilityTensor()
gamma.components = _columns_to_tensor(row[col_gamma])
kw = {}
if len(col_mu) != 0:
kw = {'dipole': row[col_mu].to_numpy()}
gamma.compute_properties(**kw)
new_data = append_data(new_data, gamma.properties)
components_dict = {}
for c, v in zip(components['gamma'], gamma.flatten_components()):
components_dict[c] = v
new_data = append_data(new_data, components_dict)

new_data = pd.DataFrame(new_data)
new_data.to_csv(args.output_file, index=False)


if __name__ == '__main__':
main()
Loading