Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
abelcarreras committed Dec 22, 2020
2 parents bb286b7 + 3141380 commit cf6157e
Show file tree
Hide file tree
Showing 11 changed files with 296 additions and 125 deletions.
83 changes: 56 additions & 27 deletions cosymlib/file_io/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,35 @@
from cosymlib.molecule import Molecule, Geometry, ElectronicStructure
from cosymlib.file_io.tools import extract_geometries
from cosymlib.tools import atomic_number_to_element
from cosymlib.file_io import custom_errors

import numpy as np
import os, sys, re
import os, re
import warnings


comment_line = ('#', '!', '$')


def _non_blank_lines(f):
for l in f:
line = l.rstrip()
if line:
yield line


def check_geometries_vertices(geometries, file_name):
n_atoms = geometries[0].get_n_atoms()
idl = 0
for idg, geometry in enumerate(geometries):
if geometry.get_n_atoms() != n_atoms:
warnings.warn('Error in structure {}: Line {} of file {}\n '
'Number of vertices does not match with other structures\n'.format(idg + 1, idl + 1,
file_name),
custom_errors.DifferentVerteciesWarning)
idl += geometry.get_n_atoms() + 2


# Read INPUT files
def read_generic_structure_file(input_name, read_multiple=False):
# print('Reading file {}...'.format(os.path.basename(input_name)))
Expand Down Expand Up @@ -43,42 +59,49 @@ def get_geometry_from_file_xyz(file_name, read_multiple=False):
"""
input_molecule = [[], []]
geometries = []
n_atoms = None
with open(file_name, mode='r') as lines:
n_atoms = int(lines.readline())
name = lines.readline()
if name.strip():
name = name.split()[0]
for line in lines:
if '$' in line or '#' in line or line.strip() == '':
for idl, line in enumerate(lines):
# if '$' in line or '#' in line or '!' in line:
if line.lstrip().startswith(comment_line):
pass
elif line.strip() == '':
warnings.warn('Line {} is empty'.format(idl + 1), custom_errors.EmptyLineWarning)
else:
try:
float(line.split()[1])
input_molecule[0].append(line.split()[0])
input_molecule[1].append(line.split()[1:])
except (ValueError, IndexError):
except IndexError:
if input_molecule[0]:
if len(input_molecule[0]) != n_atoms:
warnings.warn('Number of atoms in first line and number of atoms provided are not equal')
warnings.warn('Number of atoms around line {} and number '
'of atoms provided are not equal'.format(idl - len(input_molecule[0]) - 1),
custom_errors.MissingLineWarning)
geometries.append(Geometry(symbols=input_molecule[0],
positions=input_molecule[1],
name=name))
n_atoms = None

input_molecule = [[], []]
try:
if n_atoms is None:
n_atoms = int(line.split()[0])
except (ValueError):
else:
name = line.split()[0]

if len(input_molecule[0]) != n_atoms:
warnings.warn('Number of atoms in first line and number of atoms provided are not equal')
molecule = Geometry(symbols=input_molecule[0],
positions=input_molecule[1],
name=name)
if read_multiple:
geometries.append(molecule)
else:
return molecule
warnings.warn('Number of atoms in line {} and number '
'of atoms provided are not equal'.format(idl - len(input_molecule[0]) - 1),
custom_errors.MissingLineWarning)

geometries.append(Geometry(symbols=input_molecule[0],
positions=input_molecule[1],
name=name))
if not read_multiple:
return geometries[0]

# Check if all geometries are of the same vertices
check_geometries_vertices(geometries, file_name)

return geometries

Expand All @@ -93,12 +116,12 @@ def get_geometry_from_file_cor(file_name, read_multiple=False):
input_molecule = [[], []]
geometries = []
with open(file_name, mode='r') as lines:
line = lines.readline()
name = line.replace('**FRAG**', '')[:-1]
name = name.replace(' ', '')
for line in lines:
if '$' in line or '#' in line or line.strip() == '':

for idl, line in enumerate(lines):
if line.lstrip().startswith(comment_line):
pass
elif line.strip() == '':
warnings.warn('Line {} is empty'.format(idl + 1), custom_errors.EmptyLineWarning)
else:
try:
float(line.split()[1])
Expand All @@ -111,7 +134,7 @@ def get_geometry_from_file_cor(file_name, read_multiple=False):
else:
float(line.split()[2])
except (ValueError, IndexError):
if input_molecule:
if input_molecule[0]:
geometries.append(Geometry(symbols=input_molecule[0],
positions=input_molecule[1],
name=name))
Expand All @@ -123,6 +146,10 @@ def get_geometry_from_file_cor(file_name, read_multiple=False):
name=name))
if not read_multiple:
return geometries[0]

# Check if all geometries are of the same vertices
check_geometries_vertices(geometries, file_name)

return geometries


Expand Down Expand Up @@ -362,8 +389,10 @@ def get_geometry_from_file_ref(file_name, read_multiple=False):
lines.readline()
name = lines.readline().split()[0]
for line in lines:
if '$' in line or '#' in line:
if line.lstrip().startswith(comment_line):
pass
# elif line.strip() == '':
# warnings.warn('Line {} is empty'.format(idl + 1), custom_errors.EmptyLineWarning)
else:
try:
if len(line.split()) > 3:
Expand All @@ -375,7 +404,7 @@ def get_geometry_from_file_ref(file_name, read_multiple=False):
except (ValueError, IndexError):
if input_molecule:
structures.append(Geometry(positions=input_molecule,
name=name))
name=name))
input_molecule = []
name = line.split()[0]
structures.append(Geometry(positions=input_molecule,
Expand Down
54 changes: 25 additions & 29 deletions cosymlib/file_io/classic_inputs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import sys
from cosymlib.molecule import Geometry
from cosymlib.file_io import read_generic_structure_file
import os.path
from cosymlib.file_io import get_geometry_from_file_cor
from cosymlib.file_io import custom_errors

import os
import tempfile
import warnings


def read_old_input(file_name):
Expand All @@ -10,11 +12,11 @@ def read_old_input(file_name):
:param file_name: file name
:return: list of Geometry objects and options
"""
input_molecule = [[], []]
structures = []

options = {'%out': None, '%conquest': None, '%external': False, '%fullout': False, '%test': False,
'%n_atoms': 0, '%central_atom': 0, '%labels': 0, '%path': False}

idl = 0
with open(file_name, mode='r') as lines:
while True:
line = lines.readline().split()
Expand All @@ -36,36 +38,30 @@ def read_old_input(file_name):
options['%labels'] = line
except (ValueError, IndexError):
break
idl += 1

n_atoms = options['%n_atoms']
if options['%central_atom'] != 0:
n_atoms += 1
if options['%conquest'] is not None:
dir = os.path.dirname(os.path.abspath(file_name))
structures = read_generic_structure_file(os.path.join(dir, options['%conquest'] + '.cor'), read_multiple=True)
structures = get_geometry_from_file_cor(os.path.join(dir, options['%conquest'] + '.cor'), read_multiple=True)
else:
while True:
if not line:
break
name = line[0]
for i in range(n_atoms):
line = lines.readline().split()
if '!' in line:
pass
tmp = tempfile.NamedTemporaryFile(mode='w+t', dir=os.getcwd())
tmp_lines = lines.readlines()
try:
# Write data to the temporary file
tmp.write(line[0]+'\n')
idl += 1
for line in tmp_lines:
if line.strip() == '':
warnings.warn('Line {} is empty'.format(idl + 1), custom_errors.EmptyLineWarning)
else:
if len(line) == 4:
input_molecule[0].append(line[0])
input_molecule[1].append(line[1:])
elif len(line) == 5:
input_molecule[0].append(line[0])
input_molecule[1].append(line[1:-1])
else:
sys.exit('Wrong input format')
if input_molecule[0]:
structures.append(Geometry(symbols=input_molecule[0],
positions=input_molecule[1],
name=name))
input_molecule = [[], []]
line = lines.readline().split()
tmp.write(line)
idl += 1
tmp.seek(0)
structures = get_geometry_from_file_cor(tmp.name, read_multiple=True)
finally:
tmp.close()

return [structures, options]
20 changes: 20 additions & 0 deletions cosymlib/file_io/custom_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import warnings


def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
return ' %s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)


warnings.formatwarning = warning_on_one_line


class MissingLineWarning(Warning):
pass


class DifferentVerteciesWarning(Warning):
pass


class EmptyLineWarning(Warning):
pass
14 changes: 13 additions & 1 deletion docs/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,17 @@ for python3 ::
the code will be installed as a python module. To check that it is properly installed you can
run the :program:`python` interpret and execute ::

import symeess
import cosymlib

Install via pip
_______________

If pip is already installed in your computer, you can download and install the cosymlib module as any other
module in python ::

pip install cosymlib --user

for python3 ::

pip3 install cosymlib --user

108 changes: 108 additions & 0 deletions scripts/chirality
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#!/usr/bin/env python
from cosymlib import Cosymlib, __version__
from cosymlib.file_io.tools import print_header, print_footer, print_input_info
from cosymlib.file_io import read_generic_structure_file
import argparse
import sys
import yaml


# positional arguments
parser = argparse.ArgumentParser(description='gsym')

# positional arguments
parser.add_argument(type=str,
dest='input_file',
nargs='?', default=None,
help='input file with structures')
parser.add_argument(type=str,
dest="yaml_input",
nargs='?', default=None,
help='input file with keywords')
# Main options
parser.add_argument('-m', '--measure',
dest='measure',
metavar='SG',
default=False,
help='compute the SG symmetry measure of the input structures')
parser.add_argument('-o', '--output',
dest='output_name',
metavar='filename',
default=None,
help='store output into a file')
parser.add_argument('-c', '--central_atom',
action='store',
dest='central_atom',
metavar='N',
type=int,
default=0,
help='central atom is in position N in the input structure')

# Extra options
parser.add_argument('--info',
action='store_true',
default=False,
help='print information about the input structures')
parser.add_argument('-v', '--version',
dest='version',
action='store_true',
default=False,
help='print information about the input structures')

# Modifiers
parser.add_argument('--center',
dest='center', metavar='R',
type=float,
default=None,
nargs=3,
help='fix coordinates x,y,z for the center of symmetry operations (Angs)')

args = parser.parse_args()

if args.yaml_input:
with open(args.yaml_input, 'r') as stream:
input_parameters = yaml.load(stream, Loader=yaml.FullLoader)

for key, value in input_parameters.items():
if key.lower() in args:
setattr(args, key.lower(), value)
else:
raise KeyError("Key %s is not valid" % key)

if args.version:
print('Cosymlib version = {}'.format(__version__))
exit()

common_output = open(args.output_name, 'w') if args.output_name is not None else sys.stdout
print_header(common_output)

try:
structures = read_generic_structure_file(args.input_file, read_multiple=True)
except Exception as e:
sys.exit('No input file selected! An existing file must be provide')


structure_set = Cosymlib(structures)

if args.info:
print_input_info(structure_set.get_geometries(), output=common_output)
exit()

# if not args.measure:
# reference = ['ci', 'cs']
# elif args.measure not in ['ci', 'cs']:
# reference = ['ci', 'cs', args.measure]
# else:
# reference = args.measure
if not args.measure:
sys.exit('User should provide a symmetry group measure')
reference = args.measure.lower()

# Symgroup commands
if args.measure:
structure_set.print_geometric_symmetry_measure(reference,
central_atom=args.central_atom,
center=args.center,
output=common_output)

print_footer(common_output)

0 comments on commit cf6157e

Please sign in to comment.