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

Add Type Annotations #58

Merged
merged 11 commits into from
Oct 11, 2019
44 changes: 22 additions & 22 deletions solcore/config_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@
import solcore
import glob

home_folder = os.path.expanduser('~')
user_config = os.path.join(home_folder, '.solcore_config.txt')
home_folder: str = os.path.expanduser('~')
user_config: str = os.path.join(home_folder, '.solcore_config.txt')
user_config_data = ConfigParser()
user_config_data.read(user_config)

default_config_data = ConfigParser()
default_config_data.read(solcore.default_config)


def reset_defaults(confirm=False):
def reset_defaults(confirm: bool = False) -> None:
""" Resets the default Solcore configuration in the user home folder.

:return: None
Expand All @@ -39,7 +39,7 @@ def reset_defaults(confirm=False):
print('Default Solcore configuration has been restored!')


def save_user_config():
def save_user_config() -> None:
""" Saves the current user configuration

:return: None
Expand All @@ -48,7 +48,7 @@ def save_user_config():
user_config_data.write(fp)


def remove_source(section, name):
def remove_source(section: str, name: str) -> None:
""" General function to remove sources from the configuration files. It checks if the source exists and, if so, if
it is a default Solcore source. In the later case, it disable the source by setting it to an empty string rather
than removing it.
Expand All @@ -72,7 +72,7 @@ def remove_source(section, name):
print('{}:{} source removed!'.format(section, name))


def add_source(section, name, location):
def add_source(section: str, name: str, location: str) -> None:
""" General function to add sources to the configuration files. If the source already exists, its value will be
replaced by the new one.

Expand All @@ -86,7 +86,7 @@ def add_source(section, name, location):
print('{}:{} source added!'.format(section, name))


def restore_default_source(section, name):
def restore_default_source(section: str, name: str) -> None:
""" Restores the default value of a source, assuming the source has a default value.

:param section: The section of the source.
Expand All @@ -104,7 +104,7 @@ def restore_default_source(section, name):
print('Default Solcore value for {} source {} has been restored!'.format(section, name))


def add_units_source(name, location):
def add_units_source(name: str, location: str) -> None:
""" Adds a Units source to Solcore.

:param name: The name of the source.
Expand All @@ -114,7 +114,7 @@ def add_units_source(name, location):
add_source('Units', name, location=location)


def add_parameters_source(name, location):
def add_parameters_source(name: str, location: str) -> None:
""" Adds a Parameters source to Solcore.

:param name: The name of the source.
Expand All @@ -124,7 +124,7 @@ def add_parameters_source(name, location):
add_source('Parameters', name, location=location)


def add_materials_source(name, location):
def add_materials_source(name: str, location: str) -> None:
""" Adds a Materials source to Solcore.

:param name: The name of the source.
Expand All @@ -135,7 +135,7 @@ def add_materials_source(name, location):
add_source('Materials', name, location=location)


def remove_units_source(name):
def remove_units_source(name: str) -> None:
""" Removes a Units source from Solcore.

:param name: The name of the source.
Expand All @@ -144,7 +144,7 @@ def remove_units_source(name):
remove_source('Units', name)


def remove_parameters_source(name):
def remove_parameters_source(name: str) -> None:
""" Removes a Parameters source from Solcore.

:param name: The name of the source.
Expand All @@ -153,7 +153,7 @@ def remove_parameters_source(name):
remove_source('Parameters', name)


def remove_materials_source(name):
def remove_materials_source(name: str) -> None:
""" Removes a Materials source from Solcore.

:param name: The name of the source.
Expand All @@ -162,7 +162,7 @@ def remove_materials_source(name):
remove_source('Materials', name)


def restore_default_units_source(name):
def restore_default_units_source(name: str) -> None:
""" Restores the default value of a Units source from Solcore.

:param name: The name of the source.
Expand All @@ -171,7 +171,7 @@ def restore_default_units_source(name):
restore_default_source('Units', name)


def restore_default_parameters_source(name):
def restore_default_parameters_source(name: str) -> None:
""" Restores the default value of a Parameters source from Solcore.

:param name: The name of the source.
Expand All @@ -180,7 +180,7 @@ def restore_default_parameters_source(name):
restore_default_source('Parameters', name)


def restore_default_materials_source(name):
def restore_default_materials_source(name: str) -> None:
""" Restores the default value of a Materials source from Solcore.

:param name: The name of the source.
Expand All @@ -189,7 +189,7 @@ def restore_default_materials_source(name):
restore_default_source('Materials', name)


def welcome_message(show):
def welcome_message(show: bool) -> None:
""" Sets if the welcome message must be shown or not

:param show: True/False for showing/hiding the welcome message
Expand All @@ -198,7 +198,7 @@ def welcome_message(show):
user_config_data['Configuration']['welcome_message'] = int(show)


def verbose_loading(show):
def verbose_loading(show: bool) -> str:
mhrownaghi marked this conversation as resolved.
Show resolved Hide resolved
""" Sets if the loading messages (besides the welcome message) must be shown or not

:param show: True/False for showing/hiding the loading messages
Expand All @@ -207,7 +207,7 @@ def verbose_loading(show):
user_config_data['Configuration']['verbose_loading'] = int(show)


def set_location_of_spice(location):
def set_location_of_spice(location: str) -> None:
""" Sets the location of the spice executable. It does not test if it works.

:param location: The location of the spice executable.
Expand All @@ -217,7 +217,7 @@ def set_location_of_spice(location):
save_user_config()


def set_location_of_smarts(location):
def set_location_of_smarts(location: str) -> None:
""" Sets the location of the SMARTS distribution (the root folder). It does not test if it works.

:param location: The location of the SMARTS distribution.
Expand All @@ -227,7 +227,7 @@ def set_location_of_smarts(location):
save_user_config()


def get_current_config():
def get_current_config() -> None:
""" Prints the current Solcore configuration

:return: None
Expand All @@ -241,7 +241,7 @@ def get_current_config():
print()


def check_user_config():
def check_user_config() -> None:
""" Checks if there's a user configuration file, asking if it needs to be created.

:return: None
Expand Down
18 changes: 13 additions & 5 deletions solcore/crystals.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
Calculates the k-points of the Brillouin zone in a given direction
"""
import numpy as np
from typing import List, Dict, Tuple

label_map = {
label_map: Dict[str, str] = {
"Gamma": "$\Gamma$",
"X": "X",
"K": "K",
Expand All @@ -12,7 +13,8 @@
"U": "U",
}

def brillouin_critical_points(a):

def brillouin_critical_points(a: float) -> Dict[str, np.ndarray]:
return {
"Gamma": np.array((0, 0, 0)),
"X": np.pi / a * np.array((0, 2, 0)),
Expand All @@ -23,7 +25,11 @@ def brillouin_critical_points(a):
}


def traverse_brillouin(a, traverse_order=("L", "Gamma", "X", "W", "K", "Gamma"), steps=30):
def traverse_brillouin(a: float,
traverse_order: tuple = ("L", "Gamma", "X",
"W", "K", "Gamma"),
steps: int = 30) -> Tuple[np.ndarray, float,
List[Tuple[float, str]]]:

critical_points = brillouin_critical_points(a)
traverse_list = list(traverse_order)
Expand Down Expand Up @@ -57,9 +63,11 @@ def traverse_brillouin(a, traverse_order=("L", "Gamma", "X", "W", "K", "Gamma"),
return np.array(coords), graph_cords / scale, list(zip(xticks / scale, [label_map[s] for s in traverse_order]))


def kvector(a, t=0, p=np.pi, fraction=0.2, points=50, vin=None):
def kvector(a: float, t: float = 0, p: float = np.pi,
fraction: float = 0.2, points: int = 50,
vin: np.ndarray = None) -> np.ndarray:
""" Calculates the k points in a direction given by the spheric angles theta (t) and phi (p).
The fraction of the Brilluin zone calculated is given by "fraction" and the number of points by "points".
If "vin" is given, the direction of interest is taken from this vector."""

Expand Down
22 changes: 12 additions & 10 deletions solcore/interpolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ class interp1d(object):
UnivariateSpline - a more recent wrapper of the FITPACK routines
"""

def __init__(self, x, y, kind='linear', axis=-1,
copy=True, bounds_error=False, fill_value=np.nan):
def __init__(self, x: np.ndarray, y: np.ndarray, kind: str = 'linear',
axis: int = -1, copy: bool = True, bounds_error: bool = False,
fill_value: float = np.nan):
""" Initialize a 1D linear interpolation class.

Description
Expand Down Expand Up @@ -118,7 +119,7 @@ def __init__(self, x, y, kind='linear', axis=-1,
self.x = x
self.y = oriented_y

def _call_linear(self, x_new):
def _call_linear(self, x_new: np.ndarray) -> np.ndarray:

# 2. Find where in the orignal data, the values to interpolate
# would be inserted.
Expand Down Expand Up @@ -148,7 +149,7 @@ def _call_linear(self, x_new):

return y_new

def _call_nearest(self, x_new):
def _call_nearest(self, x_new: np.ndarray) -> np.ndarray:
""" Find nearest neighbour interpolated y_new = f(x_new)."""

# 2. Find where in the averaged data the values to interpolate
Expand All @@ -165,12 +166,12 @@ def _call_nearest(self, x_new):

return y_new

def _call_spline(self, x_new):
def _call_spline(self, x_new: np.ndarray) -> np.ndarray:
x_new = np.asarray(x_new)
result = splev(x_new.ravel(), self._spline)
return result.reshape(x_new.shape + result.shape[1:])

def __call__(self, x_new):
def __call__(self, x_new: np.ndarray) -> np.ndarray:
"""Find interpolated y_new = f(x_new).

Parameters
Expand Down Expand Up @@ -223,7 +224,7 @@ def __call__(self, x_new):
axes[self.axis:self.axis] = list(range(nx))
return y_new.transpose(axes)

def _check_bounds(self, x_new):
def _check_bounds(self, x_new: np.ndarray) -> np.ndarray:
"""Check the inputs for being in the bounds of the interpolated data.

Parameters
Expand Down Expand Up @@ -259,7 +260,8 @@ def _check_bounds(self, x_new):
class BilinearInterpolation(object):
"""docstring for BilinearInterpolation"""

def __init__(self, x=None, y=None, z=None, fill_value=0.):
def __init__(self, x: list = None, y: list = None,
z: list = None, fill_value: float = 0.):
mhrownaghi marked this conversation as resolved.
Show resolved Hide resolved
super(BilinearInterpolation, self).__init__()
self.x = np.array(x)
self.y = np.array(y)
Expand All @@ -278,7 +280,7 @@ def __init__(self, x=None, y=None, z=None, fill_value=0.):
1], "The number of columns in z (which is %s), must be the same as number of elements in y (which is %s)" % (
y_s[0], z_s[1])

def __call__(self, xvalue, yvalue):
def __call__(self, xvalue: float, yvalue: float) -> np.ndarray:
"""The intepolated value of the surface."""
try:
x_i = 0
Expand Down Expand Up @@ -362,7 +364,7 @@ def __call__(self, xvalue, yvalue):
y = np.array([0., np.pi / 4, np.pi / 2])

# Some reflectivity values
# rads @ 400nm, rads @ 600nm, rads @ 601m, rads @ 1000nm
# rads @ 400nm, rads @ 600nm, rads @ 601m, rads @ 1000nm
z = np.array([[0., 0., 0.], [1e-9, 1e-9, 1e-9], [1 - 1e-9, 1 - 1e-9, 1 - 1e-9], [1., 1., 1.]])
# print z.shape

Expand Down
26 changes: 13 additions & 13 deletions solcore/science_tracker.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import inspect

bibliography = []
bibliography_id = []
science_tracking = []
track_science_references = False
track_each_reference_call = False
bibliography: list = []
bibliography_id: list = []
science_tracking: list = []
track_science_references: bool = False
track_each_reference_call: bool = False


def hexID(obj):
def hexID(obj: str) -> str:
return "{}".format(id(obj))


def science_reference(short_purpose, reference):
def science_reference(short_purpose: str, reference: str) -> None:
"""Marker acting as a reference for the origin of specific information
Acts as a marker in code where particular alogrithms/data/... originates. General execution of code silently passes
these markers, but remembers how and where they were called. Which markers were passed in a particular program run
can be recalled with print_references().
Arguments:
short_purpose: Identify the thing being referenced (string)
reference: The reference itself, in any sensible format.
Expand Down Expand Up @@ -49,7 +49,7 @@ def science_reference(short_purpose, reference):
science_tracking.append((call_record, short_purpose, bibliography_id.index(identifier) + 1))


def print_references():
def print_references() -> None:
""" recall the science_reference markers passed, print out the referenes."""
global bibliography, bibliography_id, science_tracking, track_each_reference_call

Expand All @@ -64,7 +64,7 @@ def print_references():
print("[{}] - {}".format(i + 1, b))


def track_science(track_each_call=False):
def track_science(track_each_call: bool = False):
"""configure science references -- determine whether or not each call separately or only the first for each
reference."""
global track_science_references, track_each_reference_call
Expand All @@ -73,11 +73,11 @@ def track_science(track_each_call=False):


if __name__ == "__main__":
def myRandomFunctionA():
def myRandomFunctionA() -> None:
myRandomFunctionB(d=1)


def myRandomFunctionB(d):
def myRandomFunctionB(d) -> None:
a = 1

science_reference("doing something smart", "My Awesome Book, by me.")
Expand Down