Skip to content

Commit

Permalink
add
Browse files Browse the repository at this point in the history
  • Loading branch information
jbae11 committed Dec 3, 2020
2 parents 3b1bf2c + f69a0f5 commit 90a26e7
Show file tree
Hide file tree
Showing 60 changed files with 3,820 additions and 634 deletions.
7 changes: 7 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
before_script:
- pip install -r reqs.txt

run-test:
script:
- python setup.py install
- pytest ./tests/unit_test.py
11 changes: 11 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Copyright 2020 Jin Whan Bae

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
207 changes: 186 additions & 21 deletions cyclus_gui/gui/arche_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,12 @@
import xmltodict
import uuid
import os
import http.client
import shutil
import json
import paramiko
import copy
from cyclus_gui.gui.run_cyclus import cyclus_run
import urllib.request
import subprocess
from cyclus_gui.gui.read_xml import *
Expand All @@ -33,24 +36,22 @@ def __init__(self, master, output_path):
['cycamore', 'FuelFab'], ['cycamore', 'GrowthRegion'], ['cycamore', 'ManagerInst'],
['cycamore', 'Mixer'], ['cycamore', 'Reactor'], ['cycamore', 'Separations'],
['cycamore', 'Storage']]
meta_file_path = os.path.join(self.output_path, 'm.json')
self.meta_file_path = os.path.join(self.output_path, 'm.json')
if os.path.isfile(os.path.join(self.output_path, 'archetypes.xml')):
self.arche, self.n = read_xml(os.path.join(self.output_path, 'archetypes.xml'), 'arche')
else:
try:
command = 'cyclus -m'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
jtxt = process.stdout.read()
with open(meta_file_path, 'wb') as f:
with open(self.meta_file_path, 'wb') as f:
f.write(jtxt)
self.arche = self.read_metafile(meta_file_path)
self.arche = self.read_metafile(self.meta_file_path)
messagebox.showinfo('Found', 'Found Cyclus, automatically grabbing archetype libraries :)')
except:
try:
# try to download m.json from gitlab
url = 'https://code.ornl.gov/4ib/cyclus_gui/raw/master/src/m.json'
urllib.request.urlretrieve(url, meta_file_path)
self.arche = self.read_metafile(meta_file_path)
# try to download m.json from gitlab
self.arche = self.get_metafile_from_git(self.meta_file_path)
messagebox.showinfo('Downloaded', 'Downloaded metadata from https://code.ornl.gov/4ib/cyclus_gui/\nIt seems like you do not have Cyclus.\n So I filled this for you :)')
except:
messagebox.showinfo('No Internet', 'No internet, so we are going to use metadata saved in the package.\n Using all cyclus/cycamore arcehtypes as default.')
Expand All @@ -61,10 +62,13 @@ def __init__(self, master, output_path):
Button(self.master, text='Add Row', command= lambda : self.add_more()).grid(row=1)
Button(self.master, text='Add!', command= lambda : self.add()).grid(row=2)
Button(self.master, text='Default', command= lambda: self.to_default()).grid(row=3)
Button(self.master, text='Import libraries (local)', command= lambda: self.import_libraries(local=True)).grid(row=4)
Button(self.master, text='Import libraries (remote)', command= lambda: self.import_libraries(local=False)).grid(row=5)

Label(self.master, text='').grid(row=4)

Button(self.master, text='Done', command= lambda: self.done()).grid(row=5)
Label(self.master, text='').grid(row=6)

Button(self.master, text='Done', command= lambda: self.done()).grid(row=7)
Label(self.master, text='Library').grid(row=0, column=2)
Label(self.master, text='Archetype').grid(row=0, column=3)
self.entry_list = []
Expand All @@ -73,6 +77,155 @@ def __init__(self, master, output_path):

# status window
self.update_loaded_modules_window()
self.check_duplicate()


def get_metafile_from_git(self, meta_file_path):
url = 'https://code.ornl.gov/4ib/cyclus_gui/raw/master/src/m.json'
urllib.request.urlretrieve(url, meta_file_path)
arche = self.read_metafile(meta_file_path)
return arche


def check_duplicate(self):
prev = []
duplicate = []
for a in self.arche:
if a[1] not in prev:
prev.append(a[1])
else:
duplicate.append(a[1])
if duplicate:
self.duplicates = True
self.duplicate_window_dict = {}
for i in duplicate:
self.choose_between_duplicate(i)



def choose_between_duplicate(self, duplicate_name):
self.duplicate_window_dict[duplicate_name] = Toplevel(self.master)
self.duplicate_window_dict[duplicate_name].title('Choice!')
Label(self.duplicate_window_dict[duplicate_name], text='Duplicate archetype name. Pick one to keep:').pack()
j = [i for i in self.arche if i[1] == duplicate_name]
for i in j:
Button(self.duplicate_window_dict[duplicate_name], text='%s:%s' %(i[0],i[1]), command=lambda:self.delete_all_but(i, j)).pack()


def delete_all_but(self, chosen, all_):
for i in all_:
if i != chosen:
self.delete_arche(i)
self.duplicate_window_dict[i[1]].destroy()
self.duplicates = False
self.update_loaded_modules_window()





def import_libraries(self, local):
self.import_window = Toplevel(self.master)
if local:
self.import_window.title('Load metadata from local Cyclus installation')
Label(self.import_window, text='Cyclus executable path / command:', bg='yellow').pack()
entry = Entry(self.import_window)
entry.pack()
Button(self.import_window, text='Import', command=lambda:self.locally_import(entry)).pack()
else:
self.import_window.title('Load metadata from remote Cyclus installation')
Label(self.import_window, text='Server / IP:').grid(row=0, column=0)
server = Entry(self.import_window)
server.insert(END, 'azure')
server.grid(row=0, column=1)

Label(self.import_window, text='Username:').grid(row=1, column=0)
username = Entry(self.import_window)
username.grid(row=1, column=1)

Label(self.import_window, text='Password:').grid(row=2, column=0)
password = Entry(self.import_window)
password.grid(row=2, column=1)

Label(self.import_window, text='Proxy Hostname:').grid(row=3, column=0)
proxy = Entry(self.import_window)
proxy.grid(row=3, column=1)

Label(self.import_window, text='Proxy Port:').grid(row=4, column=0)
proxy_port = Entry(self.import_window)
proxy_port.grid(row=4, column=1)

Button(self.import_window, text='Import', command=lambda:self.remote_import(server, username, password, proxy, proxy_port)).grid(row=5, columnspan=2)

def remote_import(self, server, username, password, proxy, proxy_port):
if server.get() == 'azure':
ip = '40.121.41.236'
else:
ip = server.get()

username = username.get()
password = password.get()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
proxy_hostname = proxy.get()
proxy_port = proxy_port.get()
try:
if proxy_hostname != '':
http_con = http.client.HTTPConnection(proxy_hostname, proxy_port)
headers = {}
http_con.set_tunnel(ip, 22, headers)
http_con.connect()
sock = http_con.sock
ssh.connect(ip, username=username, password=password, sock=sock, allow_agent=False, look_for_keys=False)
else:
ssh.connect(ip, username=username, password=password, allow_agent=False, look_for_keys=False)

except Exception as e:
messagebox.showerror('Error', 'Connection to remote server failed!\n\n %s' %e)
self.import_window.destroy()
return

i, o, e = ssh.exec_command('/home/baej/.local/bin/cyclus -m')
output = '\n'.join(o.readlines())
error = '\n'.join(e.readlines())
print('output', output)
print('error', error)
if len(output) == 0:
messagebox.showerror('Error', 'Connected, but execution of command \n cyclus -m \n in remote server failed!\n\n %s' %error)
self.import_window.destroy()
else:
print('eh')
with open(self.meta_file_path, 'w') as f:
f.write(output)
messagebox.showinfo('Done', 'Successfully read metadata file!')
self.arche = self.read_metafile(self.meta_file_path)
print('e')
self.update_loaded_modules_window()
self.import_window.destroy()



def locally_import(self, entry):
temp_metafile = self.meta_file_path + '_temp'
cmd = str(entry.get())
command = '%s -m > %s' %(cmd, temp_metafile)
proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
out, err = proc.communicate()
print('out', out)
print('err', err)
try:
self.arche = self.read_metafile(temp_metafile)
messagebox.showinfo('Success', 'Import successful.')
shutil.move(temp_metafile, self.meta_file_path)
self.update_loaded_modules_window()
self.import_window.destroy()
except Exception as e:
for i in [out,err]:
if i is not None:
messagebox.showerror('Error', 'Import failed!\n\n %s' %(i.decode('utf-8')))
self.import_window.destroy()



def read_metafile(self, meta_file_path):
with open(meta_file_path, 'r') as f:
Expand Down Expand Up @@ -145,7 +298,6 @@ def add(self):
messagebox.showerror('Error', message)
return
else:

string = 'Adding %i new libraries' %(len(enter) - len(dont_add_indx))
if len(dont_add_indx) != 0:
string += '\n Ignoring empty rows: '
Expand All @@ -154,39 +306,52 @@ def add(self):
for indx, val in enumerate(enter):
if indx in dont_add_indx:
continue
if val in self.arche:
continue
self.arche.append(val)
self.update_loaded_modules_window()


def done(self):

self.check_duplicate()
if self.duplicates:
messagebox.showerror('Check Duplicates', 'See if you have any duplicate archetype names!\nThere should be a window that tells you to choose one.')
return

string = '<archetypes>\n'
for pair in self.arche:
string += '\t<spec>\t<lib>%s</lib>\t<name>%s</name></spec>\n' %(pair[0], pair[1])
string += '</archetypes>\n'
with open(os.path.join(self.output_path, 'archetypes.xml'), 'w') as f:
f.write(string)
messagebox.showinfo('Success', 'Successfully created archetype file!')
self.master.destroy()


def guide(self):

self.guide_window = Toplevel(self.master)
self.guide_window.geometry('+%s+0' %int(self.screen_width/1.2))
guide_string = """
All Cyclus and Cycamore archetypes are already added. If there are additional archetypes
you would like to add, click the `Add Row' button, type in the library and archetype,
and press `Add!'.
All Cyclus and Cycamore archetypes are already added. If there are additional archetypes
you would like to add, click the `Add Row' button, type in the library and archetype,
and press `Add!'.
Try not to delete cycamore::DeployInst and agents::NullRegion, since they are the
default for this GUI.
Try not to delete cycamore::DeployInst and agents::NullRegion, since they are the
default for this GUI.
If you made a mistake, you can go back to the default Cyclus + Cycamore
archetypes by clicking `Default'.
If you made a mistake, you can go back to the default Cyclus + Cycamore
archetypes by clicking `Default'.
Once you're done, click `Done'.
Once you're done, click `Done'.
FOR MORE INFORMATION:
http://fuelcycle.org/user/input_specs/archetypes.html
FOR MORE INFORMATION:
http://fuelcycle.org/user/input_specs/archetypes.html
"""
Label(self.guide_window, text=guide_string, justify=LEFT).pack(padx=30, pady=30)
st = ScrolledText(master=self.guide_window,
wrap=WORD)
st.pack()
st.insert(INSERT, guide_string)

11 changes: 5 additions & 6 deletions cyclus_gui/gui/backend_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from tkinter import messagebox
from tkinter import filedialog
from tkinter.scrolledtext import ScrolledText
import xmltodict
import uuid
import os
import shutil
Expand All @@ -19,7 +18,7 @@


class BackendWindow(Frame):
def __init__(self, master, output_path):
def __init__(self, master, output_path, filename='cyclus.sqlite'):
"""
does backend analysis
"""
Expand All @@ -31,7 +30,7 @@ def __init__(self, master, output_path):
self.output_path = output_path
self.master.geometry('+0+%s' %int(self.screen_height/4))
self.configure_window()
self.get_cursor()
self.get_cursor(filename)
self.get_id_proto_dict()
self.get_start_times()

Expand Down Expand Up @@ -129,8 +128,8 @@ def get_id_proto_dict(self):
self.id_proto_dict[agent['agentid']] = agent['prototype']


def get_cursor(self):
con = lite.connect(os.path.join(self.output_path, 'cyclus.sqlite'))
def get_cursor(self, filename='cyclus.sqlite'):
con = lite.connect(os.path.join(self.output_path, filename))
con.row_factory = lite.Row
self.cur = con.cursor()

Expand Down Expand Up @@ -657,7 +656,7 @@ def plot_flow(self):
maxy = 14 * len(flow_clean)
y_coords = np.linspace(0, maxx, len(flow_clean))[::-1]
x_coords = np.linspace(0, maxy, max([len(q) for q in flow_clean]))
xgap = x_coords[1] - x_coords[0]
# xgap = x_coords[1] - x_coords[0]
ygap = y_coords[1] - y_coords[0]

uniq_commods = list(set(df['Commodity']))
Expand Down
Loading

0 comments on commit 90a26e7

Please sign in to comment.