"""Functions for the command line interface.
"""
from __future__ import division
from __future__ import print_function
import os
import sys
import shutil
import pickle
import numpy as np
[docs]def run_cli(fname='parameters.py'):
"""Function to run iDEA using parameters.py file in current working directory.
"""
from iDEA.input import Input
from iDEA import parameters
try:
# read parameters file into Input object
inp = Input.from_python_file(fname)
except IOError as e:
# if not present, set up empty one
print(e)
question = "Create new input file '{}' in current directory?".format(fname)
answer = input(question + "[y/N]: ").lower().strip()
if not(answer == "y" or answer == "yes"):
sys.exit(1)
else:
pm_path = os.path.abspath(parameters.__file__)
shutil.copyfile(pm_path, fname)
inp = Input.from_python_file(fname)
# perform checks on input parameters
inp.check()
# run job
inp.execute()
[docs]def video_cli():
""" Produce plots, animations and data files from pickle files generated by iDEA
"""
import iDEA.plot
# print splash
print(' ')
print(' * * * **** ***** **** ')
print(' * * * * * * * ')
print(' * * * * * * * * ')
print(' * * * * * ***** * * ')
print(' * * * * * * * * ')
print(' * * * * * * * * ')
print(' * * **** ***** **** ')
print(' ')
print(' +------------------------------------------------------------+')
print(' | Visualise iDEA Outputs |')
print(' | |')
print(' | Created by Jack Wetherell |')
print(' | The University of York |')
print(' +------------------------------------------------------------+')
print(' ')
# import parameters file
print('loading in parameters file...')
pickle_file = "parameters.p"
python_file = "parameters.py"
if os.path.isfile(pickle_file):
f = open(pickle_file,'rb')
pm = pickle.load(f)
f.close()
elif os.path.isfile(python_file):
sys.path.insert(0,os.getcwd())
import parameters as pm
else:
raise IOError("Neither {} nor {} found.".format(pickle_file, python_file))
# gather file information from user
file_names = str(input('enter file names to process (space seperated): ')).split(' ')
td = bool(eval(input('is the data ground-state or time-dependent (gs=0,td=1): ')))
# load the raw data in
print('reading raw data:')
data = []
for fn in file_names:
print('reading {}...'.format(fn))
data.append(iDEA.plot.read_quantity(pm, fn))
# ensure data is all the same shape
for i in range(0, len(data)):
for j in range(0, len(data)):
if data[i].shape != data[j].shape:
raise IOError('all files must have same shapes of data')
# get the dimentions of the data
if td == False:
dim = len(data[0].shape)
else:
dim = len(data[0].shape) - 1
# determine what the user wants to be processed
save_data = bool(eval(input('save to data file (0=no,1=yes): ')))
save_plot = bool(eval(input('save to pdf image (0=no,1=yes): ')))
if td or dim==3:
if save_data or save_plot:
timestep = int(eval(input('timestep to save: ')))
save_anim = bool(eval(input('save to mp4 video (0=no,1=yes): ')))
if save_anim:
step = int(eval(input('sample every n frames: n = ')))
file_name = str(input('name of output file (leave blank for default): '))
if file_name == '':
file_name = None
# process data in specified way
print('processing raw data:')
if td or dim==3:
if save_data:
iDEA.plot.to_data(pm, file_names, data, td, dim, file_name=file_name, timestep=timestep)
if save_plot:
iDEA.plot.to_plot(pm, file_names, data, td, dim, file_name=file_name, timestep=timestep)
if save_anim:
iDEA.plot.to_anim(pm, file_names, data, td, dim, file_name=file_name, step=step)
else:
if save_data:
iDEA.plot.to_data(pm, file_names, data, td, dim, file_name=file_name)
if save_plot:
iDEA.plot.to_plot(pm, file_names, data, td, dim, file_name=file_name)
# finish
print('all jobs done')
[docs]def optimize():
"""Calculate optimal alpha for hybrid Hamiltonian.
Return a tuple of three optimal values of alpha, corresponding to
each condition:
(LUMO-A, LUMO-HOMO, LUMO-I).
If no alpha satisfies a condition, return None.
"""
# Load the raw data.
filenames = ['alphas', 'enN', 'enNm', 'eigH', 'eigL']
data = {}
print('Reading raw data:')
for fn in filenames:
print('gs_hyb_{}.db'.format(fn))
with open('raw/gs_hyb_{}.db'.format(fn), 'rb') as f:
data[fn] = pickle.load(f)
# Ensure all data has the same shape.
for i in data.values():
for j in data.values():
if np.any(i != j) and i.shape != j.shape:
raise IOError('all files must have same shape of data.')
# Create arrays for which to find zero position.
lumo_a = data['enN'] - data['enNm'] - data['eigL']
lumo_homo = data['eigH'] - data['eigL']
homo_i = data['enN'] - data['enNm'] - data['eigH']
# Calculate optimal alphas.
optimals = []
for y_values in [lumo_a, lumo_homo, homo_i]:
alphas = data['alphas']
diff = np.diff(y_values)
# Reverse arrays if sorted in descending order.
if np.all(diff < 0):
alphas = alphas[::-1]
y_values = y_values[::-1]
elif not np.all(diff > 0):
print('Unsorted array for condition. Returning None.')
optimals.append(None)
continue
index_upper = np.searchsorted(y_values, 0)
if 0 < index_upper < y_values.shape[0]:
index_lower = index_upper - 1
y_upper = y_values[index_upper]
y_lower = y_values[index_lower]
y_frac = y_lower / (y_lower - y_upper)
root = (1 - y_frac) * alphas[index_lower] + y_frac * alphas[index_upper]
elif y_values[0] == 0:
root = alphas[0]
else:
root = None
optimals.append(root)
if all(a is None for a in optimals):
print("No optimal alpha found using any condition. Try increasing the input range of alpha.")
return tuple(optimals)
[docs]def optimize_cli():
optimal_alphas = optimize()
cond_names = ("LUMO-A", "LUMO-HOMO", "HOMO-I (GKT)")
print('\nOptimal alpha values:')
for index, item in enumerate(optimal_alphas):
if item is not None:
print("{:12}: {}".format(cond_names[index], item))
[docs]def examples_cli():
"""Start jupyter notebook server in example directory.
If this fails, print the path to the example directory.
"""
import pkg_resources
example_dir = pkg_resources.resource_filename('iDEA', '../examples')
exit_code = os.system('jupyter notebook {}'.format(example_dir))
if exit_code != 0:
print("Find iDEA jupyter notebook examples in\n{}".format(example_dir))