Commit 79993276 authored by marbaix's avatar marbaix
Browse files

Cleanup to remove IDE warnings and fix very minor issues.

parent 2895b4c8
Pipeline #444054 passed with stages
in 43 seconds
......@@ -18,6 +18,7 @@ sortlist = [] # Default sortlist is empty
sortrlev = -1E6 # Default sortrlev means undefined
sorthazl = -1E6 # Default sorthazl means undefined
def skeygroup(be):
"""
Used for sorting embers by group. If sortlist is defined, tries to use the order defined in this list.
......@@ -36,6 +37,7 @@ def skeygroup(be):
# hlp.addlogmes("Sort key for group:" + str(be.group.lower()) + "->" + str(pos))
return pos
def skeyname(be):
"""
Used for sorting embers by name. If sortlist is defined, tries to use the order defined in this list.
......@@ -81,6 +83,7 @@ def skeyrisk(be):
pos = -1 # ignore ember
return pos
def selecsort(lbes, fkey, reverse=False):
"""
Sorts embers in lbes but ignores those absent from sortlist (=> fkey(be) = -1 above)
......@@ -100,6 +103,7 @@ def selecsort(lbes, fkey, reverse=False):
lbes.sort(key=fkey, reverse=reverse)
return lbes
def cbyinterp(rlev, csys, cdefs):
"""
Provides a color by interpolating between the defined color levels associated to risk levels.
......@@ -123,6 +127,7 @@ def cbyinterp(rlev, csys, cdefs):
raise Exception("Undefined color system")
return thecol
class Transition(dict):
"""
A transition is a fraction of an ember containing data about how risk changes from one level to the next.
......@@ -137,8 +142,8 @@ class Transition(dict):
names = ['undetectable to moderate', 'moderate to high', 'high to very high']
colors = ['yellow', 'red', 'purple']
names_syn = {'white to yellow': 'undetectable to moderate',
'yellow to red': 'moderate to high',
'red to purple': 'high to very high'}
'yellow to red': 'moderate to high',
'red to purple': 'high to very high'}
# Phases are "steps" within transitions; they also have synonyms:
phases = ['min', 'median', 'max', 'mode'] # mode is not an actual 'phase', it is only used for elicitation
phases_syn = {'begin': 'min', 'end': 'max', 'most likely': 'mode'}
......@@ -168,6 +173,7 @@ class Transition(dict):
# In this context, the mode is the most likely value in a probability distribution.
self.mode = None
class Ember(object):
"""
An ember is one set of data in a "burning embers" diagram.
......@@ -183,7 +189,7 @@ class Ember(object):
self.risk = [] # Risk levels (array-like : list or numpy array)
self.hazl = [] # Hazard levels (array-like : list or numpy array)
self.conf = [] # Confidence levels
self.trans = [] # Transitions
self.trans = [] # Transitions
self.hazvalid = None # Maximum hazard for which this ember is assumed valid (= risk was assessed)
self.hazn = None # Standard name of the hazard variable
self.meta = {} # Dictionnary of ember-related metadata
......@@ -254,13 +260,13 @@ class Ember(object):
if egr.gp['be_name_rotate'] > 0:
align = 'right'
# rough estimate of the available length (may be improved if used)
namlen = np.sqrt((egr.gp['be_x'] + egr.gp['be_int_x'])**2 + egr.gp['be_bot_y'] **2)
namlen = np.sqrt((egr.gp['be_x'] + egr.gp['be_int_x'])**2 + egr.gp['be_bot_y'] ** 2)
else:
align = 'center'
namlen = egr.gp['be_x'] + egr.gp['be_int_x']
hlp.drawparagraph(c, xmin + egr.gp['be_x'] / 2.0, yamin - egr.gp['fnt_size'] * 0.3, self.name,
length=namlen, align=align, rotate=egr.gp['be_name_rotate'],
valign='top', font=(None,egr.gp['fnt_size']))
valign='top', font=(None, egr.gp['fnt_size']))
# Note:
# Annotating embers could possibly be useful to add information, but it produced PDF errors, hence disabled:
......@@ -369,7 +375,7 @@ class Ember(object):
def gethazl(self, itrans, phase):
"""
Returns the hazard level for a given transition and phase
:param atrans: # or name of transition in the ember
:param itrans: # or name of transition in the ember
:param phase: name of the transition phase (min, max, median...)
"""
trans = self.trans[itrans] if type(itrans) is int else self.transbyname(itrans)
......@@ -397,7 +403,7 @@ class Ember(object):
if phasename in trans:
hlp.addlogwarn("Attemp at adding a transition step that already existed: {} - {}; "
"this is not expected, please report the error and do not use the diagram"
.format(transname,phasename))
.format(transname, phasename))
return
trans[phasename] = hazl
......@@ -408,7 +414,7 @@ class Ember(object):
ilev = 1 + [idv for idv in range(len(self.risk)) if self.risk[idv] < rlev][-1]
self.risk = np.insert(self.risk, ilev, rlev)
self.hazl = np.insert(self.hazl, ilev, hazl)
self.conf.insert(ilev,'<cont>') # Todo: revise?
self.conf.insert(ilev, '<cont>') # Todo: revise?
def getmeta(self, name):
"""
......@@ -467,8 +473,8 @@ class EmberGraph(object):
self.colors = {
'black': col.CMYKColor(0, 0, 0, 1), # Standard black, for texts and lines
'blue': col.CMYKColor(1, 0.4, 0, 0),
'dpurple': col.CMYKColor(0.51, 1.0, 0.31, 0.14), # dark purple
'dyellow': col.CMYKColor(0, 0.2, 0.99, 0), # dark yellow
'dpurple': col.CMYKColor(0.51, 1.0, 0.31, 0.14), # dark purple
'dyellow': col.CMYKColor(0, 0.2, 0.99, 0), # dark yellow
'red': col.CMYKColor(0, 0.88, 0.85, 0),
'green': col.CMYKColor(0.95, 0.0, 0.95, 0),
'vdgrey': col.CMYKColor(0, 0, 0, 0.7),
......@@ -700,7 +706,6 @@ class EmberGraph(object):
# Add label
hlp.drawparagraph(self.c, tbx, sby, gllabel, align='right', font=self.font, valign="center")
# Draw verical axis line if needed (it can't be done before because it needs to be on top)
if self.hasvl:
self.c.line(lbx, self.get_y0(), lbx, self.get_y1())
......@@ -768,14 +773,12 @@ class EmberGraph(object):
ollx = olbx
orlx = orbx + self.lxticks * hasvbx # end of lines (= drawing area edge + tick mark)
talign = 'left'
vbx = orbx
self.hasvr = hasvbx
else: # Left axis
tbx = olbx - self.txspace - self.lxticks * hasvbx # end of text strings
ollx = olbx - self.lxticks * hasvbx # start of lines (= drawing area edge - tick mark)
orlx = orbx
talign = 'right'
vbx = olbx
self.hasvl = hasvbx
if withgrid:
......
......@@ -357,7 +357,7 @@ def drawparagraph(canvas, xx, yy, text, length=2*cm, align='left', valign='botto
ytrans = -ph/2.0
canvas.saveState()
canvas.translate(xx,yy)
canvas.translate(xx, yy)
if rotate:
canvas.rotate(rotate)
......@@ -401,6 +401,7 @@ def rasterize(infilepath, outfilext, fmt='png', width=800, dpi=200, jpegopt=None
return outpath
def getpath_defaults():
print(path.join(path.dirname(__file__), "defaults/"))
return path.join(path.dirname(__file__), "defaults/")
......@@ -21,7 +21,7 @@ from embermaker.helpers import norm
from embermaker import ember as emb
from embermaker import parameters as param
from embermaker.__init__ import __version__
trd = emb.Transition # Transition definitions
trd = emb.Transition # Transition definitions
# For an upcoming release (none of this appears urgent):
# Todo: Test the support for reading confidence levels in the "extended" format
......@@ -63,7 +63,7 @@ def makember(infile=None, outfile=None, prefcsys='CMYK'):
# The file containing default values for parameters or colors will only be open if needed:
def getwbdef():
infdef = os.path.join(hlp.getpath_defaults(), "colors.xlsx")
return(hlp.secure_open_workbook(infdef))
return hlp.secure_open_workbook(infdef)
# Get graph parameters
# --------------------
......@@ -75,7 +75,7 @@ def makember(infile=None, outfile=None, prefcsys='CMYK'):
'haz_bottom_value': (('haz_axis_bottom', 'haz_valid_bottom'), None)})
# Get parameter names, types, and default values:
gp.readmdfile(os.path.join(hlp.getpath_defaults(),"paramdefs.md"))
gp.readmdfile(os.path.join(hlp.getpath_defaults(), "paramdefs.md"))
# Get user-specific parameters if provided
# Todo: consider revising and moving this code to a dedicated section (11/2020)
......@@ -111,7 +111,7 @@ def makember(infile=None, outfile=None, prefcsys='CMYK'):
# -------------------
cpalname = None if 'be_palette' not in gp.keys() else gp['be_palette']
# The UI color choice overrides any choice in the user file; if the UI asks for a default palette, use default wb
if "Color definitions" not in wbmain.sheetnames or cpalname == None or prefcsys != "standard":
if "Color definitions" not in wbmain.sheetnames or cpalname is None or prefcsys != "standard":
hlp.addlogmes("Colours: will use default palettes.")
wbcol = getwbdef()
else:
......@@ -649,7 +649,7 @@ def readembers(sht, gp=None):
conf = '<cont>'
newtrans = False
# Trying to read ember data but we don't have information about the current transition:
if (trans == None or hlp.isempty(row[3].value)) and not hlp.isempty(row[4].value):
if (trans is None or hlp.isempty(row[3].value)) and not hlp.isempty(row[4].value):
hlp.addlogwarn('Input file may be badly formated: data without transition: ' + str(row[4].value))
if trans_phase not in trd.phases:
return {'error': hlp.addlogfail('Input file format error: unknown transition phase in line {}'
......
......@@ -7,6 +7,7 @@ import re
gp.lst(key) => 'list' part of the value
"""
class ParamDict(dict):
"""
ParamDict is meant to store Graphic Parameters. It is a substantially modified type of dictionnary, because
......@@ -42,13 +43,13 @@ class ParamDict(dict):
if isinstance(data, list):
# The input was a list => set it as list part of the parameter (value[1])
value[1] = data
elif value[2] in ('F','L','B'):
elif value[2] in ('F', 'L', 'B'):
data = data.strip() if isinstance(data, str) else data
# The input was not a list, and the parameter is not defined as a string
if data in ['','-']:
if data in ['', '-']:
# The input was empty
value[0]=None
elif value[2]=='B': # The parameter is defined as boolean
value[0] = None
elif value[2] == 'B': # The parameter is defined as boolean
if isinstance(data, str) and data.lower() == 'false' or data == 0:
value[0] = False
elif isinstance(data, str) and data.lower() == 'true' or data == 1:
......@@ -56,21 +57,21 @@ class ParamDict(dict):
else:
hlp.addlogwarn('Ignored parameter {} because its value ({}) could not be'
'converted to a logical value (boolean)'. format(key, data))
else: # A number is expected
else: # A number is expected
try:
if data is not None:
value[0]=float(data)
value[0] = float(data)
except(ValueError, TypeError):
hlp.addlogwarn('Ignored parameter {} because its value ({}) '
'could not be converted to a number'. format(str(key), str(data)))
else:
# The parameter type is string and the input is not a list => string
value[0]=str(data)
value[0] = str(data)
super(ParamDict, self).__setitem__(key, value)
def setnew(self, key, value):
""" Sets a new parameter key/value[main,list,type], handling deprecated parameters"""
key = key.strip(' \t') # Get rid trailing white spaces and/or tabs
key = key.strip(' \t') # Get rid trailing white spaces and/or tabs
isdeprec = self._handle_deprecated(key, value)
if not isdeprec:
super(ParamDict, self).__setitem__(key, value)
......@@ -81,26 +82,25 @@ class ParamDict(dict):
except KeyError:
hlp.addlogwarn('Internal error - requested parameter is not defined: {}'.format(key))
# For consistency with __setitem__, return None as the main value (= no value)
return [None,None,'']
if isinstance(val, list):
return val
else:
hlp.addlogwarn('Malformed parameter: {}:{}'.format(key,val))
return [None,None,'']
val = [None, None, '']
if not isinstance(val, list):
hlp.addlogwarn('Malformed parameter: {}:{}'.format(key, val))
val = [None, None, '']
return val
def __getitem__(self, key):
return self.getvalue(key)[0]
def __repr__(self, *args, **kwargs):
"""Provides a printed string from self"""
out=''
out = ''
for key in list(self):
val = super(ParamDict, self).__getitem__(key)
if len(val) > 1:
out += "; {" if out != '' else '{'
out += key + ": " + str(val[0])
if val[1]:
out += " " + str(val[1])
out += " " + str(val[1])
out += "}"
return out
......@@ -166,7 +166,6 @@ class ParamDict(dict):
"""
self._deprecated = deprecated
def readmdfile(self, filepath):
"""
Generates a dictionnary of parameters (ParamDict) from a standard file providing parameter names, defaults, etc.
......@@ -188,17 +187,17 @@ class ParamDict(dict):
# We reach this point when the line is in a table
# lines containing certain html tags are only for the documentation, => pass
if re.search('<.+?>', line) \
and any (tagf in line for tagf in ['<h2', '<h3>', '<h4>', '<section', '</section']):
and any(tagf in line for tagf in ['<h2', '<h3>', '<h4>', '<section', '</section']):
continue
cells = [cl.strip() for cl in line.split('|')]
if "<del>" in cells[0]: # Deprecated parameter - pass
if "<del>" in cells[0]: # Deprecated parameter - pass
continue
if len(cells) != 3:
hlp.addlogwarn("Internal problem in the list of parameters (no description?): |{}|".format(line))
continue
key, c1, c2 = cells
# Get additional data, if any
if '[' in c1 and ']' in c1: # There is additional data
if '[' in c1 and ']' in c1: # There is additional data
stdat = c1.find('[')
lst = c1[stdat+1: c1.find(']')]
lst = None if lst == '' else lst.split(';')
......@@ -206,25 +205,25 @@ class ParamDict(dict):
else:
main = c1
lst = None
main = main.replace('-','') # '-' or '' are equivalent and mean 'No value'
main = main.replace('-', '') # '-' or '' are equivalent and mean 'No value'
# Get type of data and process value when needed:
if "(number)" in c2:
type = 'F'
dtype = 'F'
main = None if main == '' else float(main)
elif "(length)" in c2:
type = 'L'
dtype = 'L'
# Process units of length, if any (todo: consider moving to a more 'generic' place?)
if type == 'L':
if dtype == 'L':
if ' cm' in main:
main = float(main.replace(' cm', '')) * cm
elif ' mm' in main:
main = float(main.replace(' mm', '')) * mm
else:
main = None if main == '' else float(main)
elif ("logical") in c2:
type = 'B' #Boolean
elif "(logical)" in c2:
dtype = 'B' # Boolean
main = None if main == '' else main.lower() != 'false'
else: # Default type is string
type = 'S'
self.setnew(key,[main,lst,type])
return
\ No newline at end of file
else: # Default type is string
dtype = 'S'
self.setnew(key, [main, lst, dtype])
return
......@@ -25,7 +25,7 @@ bp = Blueprint("sitenav", __name__)
@bp.route("/index")
def index():
if "reset" in request.args:
session["result-msg"]=None
session["result-msg"] = None
# If a result is available, move to the result page
if "result-msg" in session and session["result-msg"] is not None and os.path.isfile(session["pdfpathname"]):
......@@ -42,6 +42,7 @@ def index():
settings['checked_standard'] = 'checked' # Default and fallback if config id mistyped
return render_template("emberweb/start.html", settings=settings)
# Enable downloading examples:
@bp.route('/doc/examples/<path:filename>', methods=['GET', 'POST'])
def examples_fil(filename):
......@@ -59,7 +60,7 @@ def doc(subpage='tutorial'):
with open(doc_page, "r", encoding="utf-8") as input_file:
content = input_file.read()
except FileNotFoundError:
return render_template("emberweb/error.html", message={"error":"Could not handle request"})
return render_template("emberweb/error.html", message={"error": "Could not handle request"})
# Add support for a specific-type of file inclusion
content = webhlp.mdcombine(content, current_app.root_path)
......@@ -67,7 +68,7 @@ def doc(subpage='tutorial'):
content = markdown(content, extensions=['tables'])
# Add support for colspan when empty cells are found
content = webhlp.colspan(content)
#Add code to transform links to buttons when at the beginning of a paragraph
# Add code to transform links to buttons when at the beginning of a paragraph
txbutton = 'class="btn btn-right" > <svg class="btn-icon" aria-hidden="true">\
<use href=' + url_for('static', filename='icons.svg') + '#download></use></svg>'
txmarker = '<p><a href'
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment