Skip to content

Commit

Permalink
More refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
jkarns275 committed May 30, 2019
1 parent af5a46c commit 1d7a8dd
Show file tree
Hide file tree
Showing 47 changed files with 3,771 additions and 5,255 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ data/*
src/*.pyc
*.pyc
src/__pycache__/
*/__pycache__/*
test_data/*
Config.toml
.idea/*
Expand All @@ -16,8 +17,10 @@ build/
*.toc
*.synctex
*.aux
*.pdf
build/*
dist/*
/binaries/Linux/bin/*
/binaries/Mac OSX/bin/*
/binaries/Windows/bin/*
/binaries/Windows/bin/*
/venv/*
10 changes: 8 additions & 2 deletions src/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
This is the main module. It basically checks that there is a hapi api key, asks for one if there
is not one, and launches the main GUI. Thats about it.
is not one, and launches the main GUI. That's about it.
"""
from multiprocessing import freeze_support
import sys
Expand All @@ -11,9 +11,15 @@
from startup import fix_cwd, check_version
from app import run


check_version()
fix_cwd()

if __name__ == '__main__':
freeze_support()
sys.exit(run())
try:
sys.exit(run())
except TypeError as err:
print(f"Encountered type error:\n {str(err)}")
except Exception as err:
print(f"Encountered an error: \n {str(err)}")
6 changes: 3 additions & 3 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ def obtain_apikey():

from widgets.apikey_help_widget import ApiKeyHelpWidget, ApiKeyValidator

if Config.hapi_api_key == '0000' or \
ApiKeyValidator.APIKEY_REGEX.match(Config.hapi_api_key) is None:
if Config.hapi_api_key == '0000' or ApiKeyValidator.APIKEY_REGEX.match(
Config.hapi_api_key) is None:
app = QtWidgets.QApplication(sys.argv)
_ = ApiKeyHelpWidget()
app.exec_()
Expand All @@ -47,7 +47,7 @@ def verify_internet_connection_and_obtain_api_key():
try:
with urllib.request.urlopen(
f"{CrossSectionApi.BASE_URL}/{CrossSectionApi.API_ROUTE}/{Config.hapi_api_key}" \
f"{CrossSectionApi.XSC_META_ROUTE}"):
f"{CrossSectionApi.XSC_META_ROUTE}"):
pass
return True
except HTTPError as _:
Expand Down
1 change: 1 addition & 0 deletions src/data_structures/bands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@


class Band:

def __init__(self, nu: List[float], sw: List[float], band_id: str):
self.x = nu
self.y = sw
Expand Down
37 changes: 13 additions & 24 deletions src/data_structures/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,14 @@ class Cache:
def __init__(self, path: str, web_fetch_routine: Callable[[], Union[str, bytes, Any]],
lifetime: timedelta):
"""
:param path: The path, starting from the cache root, of the file that the cache should be
located or stored.
:param web_fetch_routine: A function which will return a string on success, and something
else otherwise. The
something else can be retrieved using the err function. web_fetch_routine should
not throw any
exceptions, and should return a string or bytes on success, and anything else
will be considered a
failure.
else otherwise. The something else can be retrieved using the err function.
web_fetch_routine should not throw any exceptions, and should return a string or bytes on
success, and anything else will be considered a failure.
:param lifetime: A duration, after which, the cached results should be thrown out and
re-retrieved. Therefore it
is the lifetime of the cached data!
re-retrieved.
"""

self.path = "{}/{}/{}".format(Config.data_folder, Cache.CACHE_ROOT, path)
Expand All @@ -60,11 +55,9 @@ def __init__(self, path: str, web_fetch_routine: Callable[[], Union[str, bytes,
def __load_from_file(self) -> bool:
"""
Attempts to load the cache from a file. If the containing directories don't exist they're
created, and then the
__load_from_web function will be called.
created, and then the __load_from_web function will be called.
:return: Returns False if the function failed to load the file. This either means it
doesn't exist or something
weird happened
doesn't exist or something weird happened
"""
import os.path

Expand All @@ -82,8 +75,8 @@ def __load_from_file(self) -> bool:
text = file.read() # This reads whole contents of the file.
parsed = json.loads(text)
# This means the lifetime of the cache has expired (parsed['timestamp'] contains
# the unix timestamp of
# when the file was written added to the number of seconds before expiration).
# the unix timestamp of when the file was written added to the number of seconds
# before expiration).
if int(time.time()) > parsed['timestamp']:
return False
self.cached = parsed['cached']
Expand All @@ -110,10 +103,8 @@ def __load_from_web(self) -> bool:
return False
try:
with open(self.path, 'w+') as file:
file.write(json.dumps({
'timestamp': int(time.time()) + self.lifetime,
'cached': self.cached
}))
file.write(json.dumps(
{'timestamp': int(time.time()) + self.lifetime, 'cached': self.cached}))
except Exception as e:
print('Failed to write to CrossSectionMeta cache: {}'.format(str(e)))
return True
Expand All @@ -133,8 +124,7 @@ def ok(self) -> bool:
def data(self) -> str:
"""
:return: The cached data, if it exists. If `self.ok()` returns true this should return a
str. Otherwise, it
will return None.
str. Otherwise, it will return None.
"""
return self.cached

Expand All @@ -150,9 +140,8 @@ def __init__(self, path: str, web_fetch_routine: Callable[[], Union[str, Any]],

def data(self) -> Any:
"""
:return: The cached data as parsed JSON. Will return None if there is no cached data (
i.e. something went wrong)
or if the data is invalid JSON.
:return: The cached data as parsed JSON. Will return None if there is no cached data (i.e.
something went wrong) or if the data is invalid JSON.
"""
try:
res = json.loads(self.cached)
Expand Down
2 changes: 1 addition & 1 deletion src/data_structures/lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ class Lines:
```
This is the schema hapi version < 2.0 uses already.
"""

def __init__(self, table: Dict[str, Any]):
Expand Down Expand Up @@ -84,6 +83,7 @@ def set_page(self, page_number):


class Line:

def __init__(self, line_index: int, line: List[Union[int, float, str]], lines: 'Lines'):
self.line_index = line_index
self.line = line
Expand Down
18 changes: 8 additions & 10 deletions src/data_structures/xsc.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ class CrossSection:
"""

def __init__(self, nu: Iterable[float], abscoef: Iterable[float], step: float, numin: float,
numax: float,
molecule: str, len: int, pressure: float, temp: float):
numax: float, molecule: str, len: int, pressure: float, temp: float):
self.nu = tuple(nu)
self.abscoef = tuple(abscoef)
self.step = step
Expand Down Expand Up @@ -74,9 +73,8 @@ def __init__(self, molecule_id: int, wn_range: Tuple[float, float] = None,
def get_cross_sections(self) -> List[str]:
if self.molecule_id not in CrossSectionMeta.molecule_metas:
return []
return [item['filename']
for item in CrossSectionMeta.molecule_metas[self.molecule_id]
if self.xsc_is_conformant(item)]
return [item['filename'] for item in CrossSectionMeta.molecule_metas[self.molecule_id] if
self.xsc_is_conformant(item)]

def xsc_is_conformant(self, xsc) -> bool:
"""
Expand All @@ -86,8 +84,8 @@ def xsc_is_conformant(self, xsc) -> bool:
conditions of this filter, otherwise false.
"""
return (self.pressure_range is None or (
self.pressure_range[0] < xsc['pressure'] < self.pressure_range[1])) \
and (self.temp_range is None or (
self.temp_range[0] < xsc['temperature'] < self.temp_range[1])) \
and (self.wn_range is None or (
xsc['numin'] < self.wn_range[0] and xsc['numax'] > self.wn_range[1]))
self.pressure_range[0] < xsc['pressure'] < self.pressure_range[1])) and (
self.temp_range is None or (
self.temp_range[0] < xsc['temperature'] < self.temp_range[1])) and (
self.wn_range is None or (
xsc['numin'] < self.wn_range[0] and xsc['numax'] > self.wn_range[1]))
11 changes: 5 additions & 6 deletions src/graphing/hapi_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ def __init__(self, x=(), y=(), use_scatter_plot=True, name=""):
self.series = self.create_series()
for i in range(0, len(x)):
# Since qt won't graph a chart using a log scale if there is a negative or zero
# value,
# make sure everything is > 0.
# This shouldn't be a problem since all of the graph types work with positive
# quantities.
# value, make sure everything is > 0. This shouldn't be a problem since all of
# the graph types work with positive quantities.
if y[i] < 1e-138:
self.append(x[i], 1e-138)
else:
Expand Down Expand Up @@ -50,8 +48,9 @@ def isVisible(self) -> bool:
def internal_copy(self):
"""
Makes a copy of the underlying series. This is needed because after removing a series
from a chart,
Qt deallocates the QLineSeries.
from a chart, Qt deallocates the QLineSeries (the qt documents say the QChart gains
ownership of the QLineSeries, which gives the QChart the responsibility of managing the
memory.
"""
new_series = self.create_series()
for point in self.series.pointsVector():
Expand Down
Loading

0 comments on commit 1d7a8dd

Please sign in to comment.