TABLE OF CONTENTS
- 1. ganessa.en2emu/About
- 2. ganessa.epanet2/About
- 3. ganessa.epanet22/About
- 4. ganessa.multithread/Functions_mt
- 5. ganessa.OpenFileMMI/About
- 6. ganessa.OpenFileMMI/iClasses
- 7. ganessa.OpenFileMMI/iFunctions
- 8. ganessa.owa_epanet22/About
- 9. ganessa.parallel/About
- 10. ganessa.parallel/Classes_mt
- 11. ganessa.plot/functions_plot
- 12. ganessa.proj/Classes_proj
- 13. ganessa.proj/functions_proj
- 14. ganessa.sim&th/About
- 15. ganessa.sim&th/Classes
- 16. ganessa.sim&th/Compatibility_
- 17. ganessa.sim&th/Constants_
- 18. ganessa.sim&th/Exceptions_
- 19. ganessa.sim&th/Functions_
- 19.1. Functions_/addSHLtype, addSHL, updateSHL, delSHL
- 19.2. Functions_/areas
- 19.3. Functions_/attr_is_str
- 19.4. Functions_/cmd, addcmdw, execute_, cmdfile
- 19.5. Functions_/commit
- 19.6. Functions_/cwfold
- 19.7. Functions_/dist2link
- 19.8. Functions_/dll_version, full_version
- 19.9. Functions_/extrnodes
- 19.10. Functions_/gencmd, gencmdw, raw_gencmdw, _gencmdw
- 19.11. Functions_/getall
- 19.12. Functions_/getcodescount, nextcode
- 19.13. Functions_/getdemandbycode, getcodedemandinit, nextcodedemand
- 19.14. Functions_/getid
- 19.15. Functions_/getindex, exists_
- 19.16. Functions_/getkeyword, modulekeyword, attrkeyword, attrname, attrindex
- 19.17. Functions_/getvar, getunitname, getunitcoef
- 19.18. Functions_/implemented_
- 19.19. Functions_/importEpanet, exportEpanet
- 19.20. Functions_/is_embedded
- 19.21. Functions_/linkattr, nodeattr, tankattr, linkattrs, nodeattrs, tankattrs, attr_, attrs_, meanattr, linkattrv, tankattrv
- 19.22. Functions_/linkbbox
- 19.23. Functions_/linknodes
- 19.24. Functions_/linkXYZV, branchXYZV
- 19.25. Functions_/loadbin
- 19.26. Functions_/loadres
- 19.27. Functions_/nbobjects
- 19.28. Functions_/nbvertices
- 19.29. Functions_/nlinkattr, nnodeattr, ntankattr, nlinkattrs, nnodeattrs, ntankattrs, nattr, nattrs
- 19.30. Functions_/nodeXYZ
- 19.31. Functions_/openg, init_
- 19.32. Functions_/quit_, close_
- 19.33. Functions_/reset_
- 19.34. Functions_/resfile, res_filename, model_filename, result_filename, emb_model_folder
- 19.35. Functions_/save_, savemodel
- 19.36. Functions_/selectlen, select_
- 19.37. Functions_/setbatchmode
- 19.38. Functions_/setlang
- 19.39. Functions_/setlinkattr, setbranchattr, setnodeattr
- 19.40. Functions_/shearstr
- 19.41. Functions_/wqtracevectsize
- 20. ganessa.sim&th/Iterators
- 21. ganessa.sim/sFunctions
- 21.1. sFunctions/browseH, browseWQ
- 21.2. sFunctions/defcalind, getcalind
- 21.3. sFunctions/demand_pressure, code_pressure
- 21.4. sFunctions/full_solveH
- 21.5. sFunctions/getallminmax
- 21.6. sFunctions/hresults_block, hresults_block_xtra
- 21.7. sFunctions/hstepcount, tslen, mslen, tsval, tsvals, all_ts, msval, tsvalbymts, tsinterv, wqtslen, refdate
- 21.8. sFunctions/inv_summary, inv_varcount, inv_variable
- 21.9. sFunctions/msmooth
- 21.10. sFunctions/setWQresultfile
- 21.11. sFunctions/solveH
- 21.12. sFunctions/stat_quantiles, stat_duration
- 21.13. sFunctions/tsdemand, tsdevice, tsdemandlen, tsdevicelen
- 22. ganessa.sim/sIterators
- 23. ganessa.sort/About
- 24. ganessa.sort/sClasses
- 25. ganessa.th/tFunctions
- 26. ganessa.util/About
- 27. ganessa.util/functions
- 27.1. functions/call_until_false
- 27.2. functions/cmp_version
- 27.3. functions/decode_time, decode_date, as_seconds
- 27.4. functions/dist_to_poly, dist_p_seg, dist, split_poly_at
- 27.5. functions/envoi_msg
- 27.6. functions/FichInfo, banner
- 27.7. functions/formatting: strf2, strf3, strf2loc, strf3loc, stri, hhmmss, hhmmssd, strd
- 27.8. functions/get_proxy
- 27.9. functions/get_python_exe
- 27.10. functions/gfloat, gint, gbool
- 27.11. functions/IniFile, get_, set_, getall, setall, save_
- 27.12. functions/IniFile1L, get_, set_, remove_, save_
- 27.13. functions/is_folder_writeable
- 27.14. functions/is_text, myascii, unistr, str2uni, utf2uni, con2uni
- 27.15. functions/is_wq
- 27.16. functions/lec_csv, csv_with_tabs
- 27.17. functions/list2file
- 27.18. functions/piccolo_context
- 27.19. functions/quotefilename
- 27.20. functions/roundval, scaladjust
- 27.21. functions/toidpic
- 27.22. functions/tsadd
- 27.23. functions/update_package
- 27.24. functions/utf8_bom_encoding
- 27.25. functions/winstr, utf, ws, aws, codewinfile
- 27.26. functions/XMLduration
- 28. ganessa.util/iterators
- 29. Constants/BRANCH, LINK_, NODE_, NOEUD, TANK_, RESERVOIR_, RSV
- 30. Constants/DICT_
- 31. Constants/M
- 32. Constants/STR_ATTR_FR, STR_ATTR_EN, STR_ATTR_SP
1. ganessa.en2emu/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.en2emu provides compatibility for a limited set of functions
used by Ganessa tools, such as OpenFileMMI.SelectModel. It makes use of owa_epanet22
if owa-epanet is installed, otherwise it uses epanet22 legacy, limited API.
It creates a hidden _emu_object ENmodel object for the current model, caching Pipes,
tanks, hydaulic EPS results, pressure and flow unit and coefficients etc.
HISTORY
- 2020-06-19: creation / interface with epanettools (epanet 2.0)
- 2023-10-17: extension with owa-epanet (epanet 2.2) and epanet22
- 2023-10-25: extension with runWQ and changes in epanet project handling
- 2023-10-30: add getpipedata, getallminmax, raw_stat_duration
- 2024-01-15: minor improvement in ENmodel.save_as: keep comments after section header
2. ganessa.epanet2/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.epanet2 provides epanettools API for epanet 2.00.12.
It is a copy of epanettools 0.4.3, with minor fixes.
3. ganessa.epanet22/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.epanet22 provides epanettools API for epanet 2.2,
similar to Epanet 2.0 (legacy API to a single project).
4. ganessa.multithread/Functions_mt [ Introduction ]
[ Top ] [ Introduction ]
4.1. Functions_mt/mp_run [ Fonctions ]
[ Top ] [ Functions_mt ] [ Fonctions ]
DESCRIPTION
This function is provided for legacy compatibility.
parallel.MultiProc should be used instead.
SYNTAX
mp_run(logprint, tasks [, nb_cpu= -1] [, wait= 0.0] [, use_wpnum= False])
ARGUMENT
see MultiProc and run
RESULT
this function is implemented as:
- MultiProc(logprint, nb_cpu, wait, use_wpnum).run(tasks)
HISTORY
- Created 2016.12.14
- Updated 2017.11.14: class interface and optional wpnum argument.
- Updated 2017.11.16: machinery moved to parallel
4.2. Functions_mt/required_cpu [ Fonctions ]
[ Top ] [ Functions_mt ] [ Fonctions ]
SYNTAX
ncpu = required_cpu(nb_cpu)
ARGUMENT
int nb_cpu: expected number of parallel processes, up to the hardware core count.
A negative or null value indicates the number of hardware cores + nb_cpu.
RESULT
int ncpu: actual number of parallel processes (1 ... max physical core count)
EXAMPLE
- required_cpu(-1) returns the hardware core count but one.
5. ganessa.OpenFileMMI/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.OpenFileMMI provides Classes for choosing/opening a model,
a file, a folder.
REMARK
It should be preceded by 'import ganessa.sim'
6. ganessa.OpenFileMMI/iClasses [ Introduction ]
[ Top ] [ Introduction ]
6.1. iClasses/SelectModel, SelectFile,
SelectFolder [ Fonctions ]
[ Top ] [ iClasses ] [ Fonctions ]
PURPOSE
Provide ready-to-use frames for display a preselected model/file/folder name; and
a button allowing selecting a different model(for reading),
file for reading or writing, or folder. SelectModel can load the model,
display the link and node counts.
SYNTAX
- frm = SelectModel(parent, file_name, exts=None, usedef=True, silent=True,
show_emb=False, inp_core=None)
- frm = SelectFile(parent, file_name, exensions, mode, title="", post=None,
show_emb=False, allow_reset=False)
- frm = SelectFolder(parent, folder_name, title="", post=None)
ARGUMENTS
- frame parent: parent frame
- str file_name/folder_name: default value for the model / file / folder.
SelectModel will not load the model at frame creation (it can take some time),
this has to be done by calling the update_info method.
- str or tuple of str exts/extensions: extensions allowed for selecting a file.
If a single extension is allowed, it can be provided as a str instead of a singleton.
- bool usedef: if True, a radiobutton allow to select between _Selected model and
default result file.
- bool silent: if True, .dat and .pic files are read as silently as possible.
- str mode: "r" for reading or "w" for writing. Defaults to "w" if title is set or None.
- str title: will appear in the title of the selection dialog box.
- callable post: function expecting the file/folder name as single argument, and returning
a str that will be displayed below the file/folder name in the frame. It can be defined
later with add_extra_info method.
It will be called after the selection of the file/folder.
- bool show_emb: if False, and the script is run in embedded mode, the selection
button is not displayed (the model / file cannot be changed).
- module inp_core: alternate core able to read .inp Epanet files and providing a few
functions compatible with ganessa.sim (en2emu).
- bool allow_reset: if True, a "reset" button is provided to clear the file name.
RESULT
- frame frm: frame or label frame containing the button selection, the
model/file/folder name, etc.
METHODS
Those 4 methods return the model/file/folder currently Selected:
- str name = frm.getfilename()
- str name = frm.get()
- str name = frm.fname
- str name = frm.getfoldername() (SelectFolder only)
This method appends (SelectModel) or redefines and runs (SelectFile and SelectFolder)
the post-processing function with callable post_proc:
- frm.add_extra_info(post_proc)
- frm.add_extra_model_info(post_proc) (synonym for SelectModel)
For SelectModel, this method returns the text information computed by the loadmodel
(link and node counts) and by additional post-processors added by add_extra_info.
For SelectFile and SelectFolder, this method returns the result of post callable:
This method updates the post processing text displayed in the frame:
These SelectFile methods allow to reset the file name:
- frm.setfilename(name)
- frm.fname = name
This SelectFile method allow to modify read / write mode:
- frm.set_rw_mode("r" or "w")
REMARK
language is initialised to "FR" by default; see setlanguage.
7. ganessa.OpenFileMMI/iFunctions [ Introduction ]
[ Top ] [ Introduction ]
7.1. iFunctions/ask_for_single_input [ Fonctions ]
[ Top ] [ iFunctions ] [ Fonctions ]
PURPOSE
Display a dialog box for a single data entry
SYNTAX
val = ask_for_single_input(reason, defval=None)
ARGUMENTS
- string reason: main prompt displayed in the dialog box
- defval: default value or type of expected value (int, float or str)
(default to None for str input)
RESULT
- (int or float or str) val: value provided by the user, or defval.
REMARKS
- if defval is a type (int, float, str) then user MUST enter a value of
this type and validate with OK. Null string is not allowed.
- if defval is a value (int, float, str) then it is retured if user
cancels the dialog.
HISTORY
- 2025-06-26: function created (2.5.3)
7.2. iFunctions/setlanguage [ Fonctions ]
[ Top ] [ iFunctions ] [ Fonctions ]
PURPOSE
Sets and/or returns the current UI language.
SYNTAX
val = setlanguage(new_lang=None)
ARGUMENTS
- str new_lang: new language to be used: "FR" for French
or any other for English, or None to return current language.
RESULT
- str val: previous/current language
REMARK
language is initialised to "FR" by default.
8. ganessa.owa_epanet22/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.owa_epanet22 provides epanettools compatibility for owa-epanet
package, in the sense it hides the Epanet 2.2 project argument by using a
default single project, but allow to close / create that project for multiprocessing.
HISTORY
9. ganessa.parallel/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.parallel provides a multitasking (parallel) computing
capability based on multiprocessing Process and Queue objects.
10. ganessa.parallel/Classes_mt [ Introduction ]
[ Top ] [ Introduction ]
10.1. Classes_mt/MultiProc, run_,
run_sequential [ Objects ]
[ Top ] [ Classes_mt ] [ Objects ]
DESCRIPTION
The MultiProc class allows to define and run tasks in parallel. A number
of N processing instances (nb_cpu provided, default all cores but one)
are created; then tasks from the tasks list are dispatched to the processing
instances.
An init task (resp. a term task) may be provided; if so it is called by
each processing instance before the 1st task (resp. after the last one).
If init is not provided,
first N tasks are guaranteed to be run on distinct instances and
can also be used for initialisation purposes. Then each task in the list is
associated to the next processing instance available in turn. The execution
order is not guaranteed (except the first N tasks if init is not provided).
run executes the tasks list in parallel processing instances; run_sequential
executes the tasks list sequentially, i.e. init, tasks in order, term.
SYNTAX
- mp = MultiProc(logprint [, nb_cpu= -1] [, wait= 0.0] [, use_wpnum= False] [, reduce= None]
[, progress= None])
- results, resinit, resterm = mp.run(tasks [, init=None] [, term= None])
- results, resinit, resterm = mp.run_sequential(tasks [, init=None] [, term= None] [, wpnum= None])
- comb_results = mp.run(tasks [, init=None] [, term= None])
- comb_results = mp.run_sequential(tasks [, init=None] [, term= None] [, wpnum= None])
- ncpu = mp.nmaxcpu
ARGUMENT
- function logprint: called by mp.run with a single str arg for logging
- int nb_cpu: optional number of parallel processes, up to the hardware core count.
A negative value indicates the number of hardware cores + nb_cpu (defaults to -1).
- float wait: wait time (s) before the first task of each processing instance.
- bool use_wpnum: if True, the function called in task list must accept an
integer keyword argument wpnum, being equal to the process number (1 ... nb_cpu)
in charge of its execution.
- callable progress: function for displaying the overall progression.
It is called after every task completion with the completion rank (starting at 0)
and the total task count, i.e. progress(i, ntasks) where i in range(ntasks).
- callable reduce: function for reducing the simulation results.
the first call to 'init' is used to initialise comb_results;
then every incoming result is merged in turn (in random order):
comb_result = reduce(comb_results, result)
- tasks: list of (func, args) tuples defining the tasks to be run as
result = func(*args) if use_wpnum is False or not set; or
result = func(*args, wpnum= proc_num) otherwise.
if func returns a str or unicode, it will be inserted in the log string.
- optionally, func can be a tuple (fun, erfun); erfun(*args) will be called
for a return value if fun(*args) raise an exception (added 190416).
- init (optional) tuple (func, args) to be called by every processing instance
before any tasks.
- term (optional) tuple (func, args) to be called by every processing instance
after all tasks.
RESULT
- int ncpu: number of processing instances.
When reduce function is not provided:
- results: list of result = func(args), in the original tasks list order.
- resinit: list of results for init calls (empty if init is None).
Its length is the processing instances count.
- resterm: list of results for term calls (empty if term is None).
Its length is the processing instances count.
When reduce function is provided:
- comb_results: reduced results. Roughly reduce(reduce, results, init_result)
REMARKS
- tasks are run in parallel by the set of parallel processes: when a process
ends up a task, it starts executing the next task available in the list.
- the number of processing instances is available as mp.nmaxcpu
- run_sequential is provided for debugging, it loops and execute tasks in turn.
- if the tasks count is smaller than the number of requested cpus, the number
of processing instances is reduced to the task count.
HISTORY
- Created 2016.12.14
- Updated 2017.11.14: class interface and optional wpnum argument.
- Updated 2017.11.17: renamed to parallel; added results return list.
added init and term options
- Updated 2017.11.20: return values as a tuple of 3 lists for tasks, init, term
- Updated 2017.11.30: added progress method
- Updated 2018.04.18: added reduce method; fix init seq run issue.
- Updated 2018.05.14: fix python3 issue
- Updated 2019.04.11: NotImplementedError handling in cpu_count
- Updated 2019.04.16: added erfun handling for return value when fun raises an exception
- Updated 2023.08.07: use f-strings
- Updated 2024.12.19: fix missing 'term' call by run_sequential
11. ganessa.plot/functions_plot [ Introduction ]
[ Top ] [ Introduction ]
11.1. functions_plot/layout [ Fonctions ]
[ Top ] [ functions_plot ] [ Fonctions ]
PURPOSE
Determines the number of pages, lines and columns of a figure
SYNTAX
npages, nlines, ncols = layout(nbplots [, nlmax=6 ] [, ncmax= 4] [, orient= 'h'])
ARGUMENT
- int nbplots: number of graph to plot
- int nlmax (optional, default 6): max nb of graphs per column
- int ncmax (optional, default 4): max nb of graphs per line
- char orient (optional, default 'h'): orientation of the layout (h or v)
RESULT
- int npages: number of pages to plot
- int nlines: number of lines per page
- int ncols: number of columns per page
EXAMPLE
Determine number of pages (nf), lines and columns; then plot page by page
nf, nl, nc = layout(len(mes))
for i in range(nf):
plotmes(graphs[i*nl*nc:(i+1)*nl*nc] , ...)
11.2. functions_plot/plotmes, plotmesx,
pageplot, pageplotx [ Fonctions ]
[ Top ] [ functions_plot ] [ Fonctions ]
PURPOSE
- plotmes plots one or more time series of the same kind in a single page.
- plotmesx plots one or more time series of the same kind on one or more figures.
it makes use of layout in order to determine the number of pages.
- pageplot plots a table of time series.
- plot_close allows to clean up matplotlib scraps and should be called
before the script ends.
SYNTAX
- plotmes(mes, attr [, nl=3 ] [, nc=2 ] [, cmt='' ] [, fgname=''] [, inter=True]
[, orient= 'h'] [, prefix_title=''] [, labels=None])
- plotmesx(mes, attr [, nlx=6 ] [, ncx=4 ] [, cmt='' ] [, fgname=''] [, inter=True]
[, orient= 'h'] [, labels=None])
- pageplot(tsl, title [, nl=3 ] [, nc=2 ] fgname=''] [, inter=True] [, lang='FR'] [, orient= 'h'])
- pageplotx(tsl, title [, nlx=3 ] [, ncx=2 ] fgname=''] [, inter=True] [, lang='FR'] [, orient= 'h'])
- plot_close()
ARGUMENT
- list mes: either a list of element ids, for which the result time series
will be retrieved from the result file and plotted in blue. If a measurement is associated
with an id, it will also be displayed in red on the same id graph.
- or a list of (id, ftime, fval), in which case the additional
time serie (ftime, fval) will be plotted in green on the id graph as 'Reference'
- or a list of (id, ftime, fval1, fval2) or (id, ftime1, fval1, ftime2, fval2)
which will be plotted fval1 as 'Reference' (green) and fval2 as 'Alternate' (magenta)
- string attr: attribute to be plotted
(or attr:DA for residual or attr:DR for relative residual)
- list tsl: list of (id, tvec, vvec [,vvec2, ...]) to be plotted, one per graph.
- string title: title for pageplot(x). If tsl contains 2 or more data series, title can
be given as a tuple (title, legend1, legend2, ...).
- nl, nc: number of lines and columns of plots in the page (plotmes and pageplot only)
- nlx, ncx: maximum number of lines and columns of plots in the page (plotmesx and pageplotx only)
- cmt: optional comment appended to the title
- string fgname: output file name - if not nul, the plot will be saved
into a filename with extension '.png'.
- bool inter: if False, no plot is displayed
- char orient (optional, default 'h'): orientation of the layout (h or v)
- str prefix_title: optional string to be placed before the title
- tuple of str labels:
REMARK
Type of data and units are displayed (in french) in the figure title
HISTORY
- 170426: improvement of x axis labels when time horizon > 24h
- 170618 (1.7.6): added pageplot
- 171120 (1.8.5): added plot_close
- 180924 (2.0.1): added orient kw
- 181105 (2.0.3): added pageplotx
- 200103 (2.0.8): plot reference before simulation
- 200315 (2.1.1): plot chlorine
- 200603 (2.1.3): single (static) measurement plotted as an horizontal line
- 200915 (2.1.5): pageplot(x) allows multiple ts per graph.
- 210111 (2.1.6): fix an overflow error plotting long TS (> 248 days)
- 210301 (2.1.7): optionnally plot bottom & top tank levels ('*' marker)
- 220304 (2.3.0): fix ax.title - replaced with ax.set_title in pageplot (3.9+)
- 220823 (2.3.2): set savefig DPI to 300; plotmes always write ID, name on next line if too long
- 221007 (2.3.4): prefix title with file basename
- 221103 (2.3.4): add "*" separator for prefix title
- 230311 (2.3.7): add xkcd option
- 230511 (2.3.8): pageplot handles more than 2 ts by plot
- 240808 (2.4.6): added labels
12. ganessa.proj/Classes_proj [ Introduction ]
[ Top ] [ Introduction ]
12.1. Classes_proj/FrenchProjMapping [ Objects ]
[ Top ] [ Classes_proj ] [ Objects ]
PURPOSE
Provides and maintains a bijective dict of symbolic -> EPSG usual French CRS.
SYNTAX
projs = FrenchProjMapping()
METHODS
- dict methods: keys(), values(), items(), __getitem__, __setitem__
- item.epsg2symb(epsg: str, default="autre"): returns the symbolic name
associated with the given EPSG. Inserts it if not yet present, with the
symbolic name given as default.
- __setitem__ maintains the bijectivity of the dict and remove any
other key with the same value.
REMARK
Initial dict values are available as FrenchProjMapping().
They include wgs84, various lambert systems for French Metropolitan,
utm20n (Martinique and Guadeloupe), rgaf09 (Martinique), utm40s (la Reunion),
utm22n (Guyanne), and macao
HISTORY
- new in 2.3.1 (220802)
- 2.3.2 (220802) this doc has been added
- 2.3.6 (230217) added Tananarive Laborde grid approx for Madagascar
- 2.4.1 (240412) added Milano
- 2.5.1 (250401) simplify as a dict subclass
13. ganessa.proj/functions_proj [ Introduction ]
[ Top ] [ Introduction ]
13.1. functions_proj/get_spatial_ref [ Fonctions ]
[ Top ] [ functions_proj ] [ Fonctions ]
PURPOSE
Query or retrieves the spatial ref from the (current) model
SYNTAX
crs_name = get_spatial_ref(pic_module [, model_file])
ARGUMENT
- module pic_module: ganessa.sim module
- str model_file: optional name of the model file
RESULT
Name of the CRS as defined in the Piccolo models as "SPATIAL-REF" command
REMARKS
- Before 2022-02-14 Piccolo and Ganessa_SIM API do not return SPATIAL-REF;
in this case SPATIAL-REF is searched in the file model_file with extension replaced with .dat or .pic
- Return value can be a blank str "" if SPATIAL-REF is not defined, or "#NAN#"
for old API or non-existing model_file or SPATIAL-REF not defined in the file.
HISTORY
- new in 2.3.1 (220802)
- 2.3.2 (220802) this doc has been added
13.2. functions_proj/guess_proj, to_epsg,
to_symbolic [ Fonctions ]
[ Top ] [ functions_proj ] [ Fonctions ]
PURPOSE
Determines the CRS (projection) amongst usual French CRS
SYNTAX
- name_or_epsg = guess_proj(point_or_module, as_epsg)
- epsg = to_epsg(name)
- name = to_symbolic(epsg)
ARGUMENT
- Union[Tuple(float, float), module] point_or_module: either a x, y point or
ganessa.sim module. In the latter case, the median X and Y node coordinates are retrieved.
- bool as_epsg: if True, returns the EPSG CRS, otherwise returns the symbolic name
- str name: symbolic name
- str epsg: EPSG:xxxx
RESULT
str name_or_epsg: EPSG:xxxx or symbolic name, depending on the value of as_epsg:
- if True, returns the guess of EPSG:xxxx CRS
- if False, returns one of "wgs84", "lambCorse", lambN", "lamb93", "rgf93-ccll"
where 42 <= ll <= 50, "utm20n", "utm22n", "utm40s", "tananariveLaborde" etc.
EXAMPLE
guess_proj((646464.64, 6868686.8), True) should return EPSG:2154
HISTORY
- new in 2.3.1 (220802)
- 2.3.2 (220802) this doc has been added
- 2.3.6 (230220) added to_epsg and to_symbolic
- 2.3.7 (230223) fix guess_proj w/o returning "autre" causing KeyError in as_epsg()
- 2.3.8 (230413) guess_proj calls get_spatial_ref in module mode
- 2.4.1 (240412) added MonteMario as alternative of rgf93-ccxx if defined
- 2.4.6 (240810) added optional arg name[="autre"] to to_symbolic
- 2.5.1 (250307) fix MonteMario / rgf-cc recognition
14. ganessa.sim&th/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.sim (resp. ganessa.th) provides a Python interface
to Picwin32.dll and Ganessa_SIM.dll (resp. Ganessa_TH.dll) kernel API.
It is provided as python wheels:
- all versions up to version 2.1.9 (april 2021) are compatible with python 2.7.
- from version 2, it is compatible with 32 and 64 bits versions of python 3.6/3.7.
- from version 2.1, it is compatible with python 3.7.6 and 3.8.
- from version 2.1.5, it is compatible with python 3.9.
- from version 2.1.8, it is compatible with python 3.10.
- up to version 2.1.9, it is compatible with python 2.7.
- from version 2.3.3, it is compatible with python 3.11.
- from version 2.3.10, it is compatible with python 3.12.
- from version 2.4.2, it is compatible with python 3.13.
The module name ganessa.sim&th is used for items available both
in .sim and .th environments
INSTALLATION
python -m pip install [--trusted-host pypi.org] ganessa
The package expects the simulation kernel .dll to be found either
in the folders given by %GANESSA_DIR% environment variable (for Ganessa_xx.dll)
or %PICCOLO_DIR% (for Picwin32.dll),
or in the %path% environment variable (either name),
or in %LOCALAPPDATA%/Programs folders:
- Safege/Ganessa_<lang>/Ganessa_SIM.dll (or Suez/...)
- Safege/Piccolo_<lang>/Picwin32.dll (or Suez/...)
- Inetum/Piccolo6_<lang>/Picwin32.dll (starting with version 2.2.3)
- Gfi Progiciels/Piccolo6_<lang>/Picwin32.dll
or in one of the "Program Files (x86)"" sub folders (Picalor6 replaces Piccolo6 if needed):
- "Safege/Ganessa_<lang>/Ganessa_xx" (or Suez/...) (xx = SIM or TH) or
- "Inetum/Piccolo6_<lang>[_ck | _cl]/Picwin32.dll" or
- "Gfi Progiciels/Piccolo6_<lang>[_ck | _cl]/Picwin32.dll" or
- "Adelior/Piccolo5_<lang>/Picwin32.dll"
in either drive C: or D:
USE
Syntax:
import ganessa.sim as pic (or ganessa.th for Picalor)
pic.cmdfile("my file.dat")
Or:
from ganessa.sim import *
cmdfile("my file.dat")
the import will perform the following initialisation tasks:
- determines if it runs in python embedded - cf. is_embedded()
- locate Ganessa_xx.dll or Picwin32.dll kernel
- initialise it (if not run in embedded python)
- locate result.bin in a working subdirectory
- bind termination to ctrl+Z
CONTENT
The package provides the following content:
REMARKS
- Most of the functions are getter. A few direct setter functions are provided
(setlinkattr, setdensity, defcalind, *SHL functions). The general purpose
gencmd(w), addcmd(w), cmd, execute and cmdfile can be used to build / commit
any other settings with command language (see the Piccolo Reference Manual).
- Commands (passed to cmd, execute, cmdfile) should be built in the language
(idiom) of the current version. getkeyword, modulekeyword, attrkeyword allow
to retrieve a given keyword in the current idiom; gencmd(w) allow to build a
command line in the current idiom from symbolic keywords.
- 'setlang' command allow to retrieve the current idiom and switch to another.
- A command file may be written in any of English, French or Spanish, the current
command language interpreter will switch to the xxx language from "_LANG_ xxx"
command until the end of the file, then switch back to the current language.
- Only recent Ganessa_SIM.dll versions can be used with this package, if not recent enough
import will fail and (try to) use any available PicWin32.dll.
- Any suggestion for extending / improving can be mailed to: piccolo@safege.fr
HISTORY
The history of the package is:
- 1.0.0: (140211) creation of the package for python 2.7
- 1.0.3: (140410) plotmesx png takes care of measurement type
- 1.0.4: (140702) added demand getter for a demand code or for all
- 1.0.5: (140908) added Windows 7 paths 'program files (x86)';
added option to get TS by measurement step 'tsvalbymts';
added 'refdate' : retireval of refdate
- 1.0.6: (140908) correction to the grid adjustment in plotmes (util)
- 1.0.7: (140916) getMinMax can be called with a selection name
- 1.0.8: (140925) save function
- 1.0.9: (141006)SimulationError exception catching + save(identical to MMI);
requires numpy 1.8.1
- 1.1.0: (141006) same as 1.0.9 but requires only numpy 1.7.1
- 1.1.1: (141016) minor change to codewinfile=winstr
- 1.1.2: (141020) added 'execute' for multiple commands as strings (\n managed as a separator)
- 1.1.3: (141104) disable useoffset for Y axes in 'util.plotmes'
- 1.1.4: (141118) handling Picwin32.dll provided by GFI after 18-11-2014 (best 03-12-2014)
- 1.1.5: (141205) handling ts < ms in tsvalbymts
- 1.1.6: (150127) nodeXYZ added + bugfix in attrs documentation
- 1.1.7: (150309) minor grammatical changes
- 1.2.0: (150507) change in folder search order (ws7 priority) + language - OK with Picwin32 151203
- 1.2.1: (150527) Picalor enabled as ganessa.th + density and SHL management;
(150603) added 'meanattr';
(150610) added 'addSHLtype'
- 1.2.2: (150709) bug fix calls select* from Selected
- 1.2.3: (150812) bug fix: return value of browseWQ; getall
- 1.2.4: (150910) constants added (WQ, Inverse Pb) + DemandCodes
- 1.2.5: (150922) utils: tuning of plotmes subtitle fontsize for large titles
+ constants (MOD, NOD ...) + 'areas' function
- 1.2.6: (151128) added tsdemand and tsdemandlen, tsdevice and tsdevicelen;
added tables (material, area etc.) access;
utils: added list2file
- 1.3.0: (151202) added support for compatibility with Picwin32 12/2014, 12/2015 and Ganessa;
(151206) addl constants (BRA, DYN, RSV);
(151218) reviewed compatibility with Picwin32 (2015+ -> Piccolo6), (2014 -> Piccolo5)
- 1.3.1: (160108) header, footer and suffix optional args for utils.list2file;
(160113) added memory allocation error exception (inverse module)
- 1.3.2: (160118) added retrieval of problematic devices;
(160126) added 'H' tank attribute in util.plotmes(x)
- 1.3.3: (160226) added getindex, tankattrs, linkattr and linkattrs
- 1.3.4: (160301) added constants for inverse pb;
(160309) added inverse simulation summary;
(160318) added added nxxxxattr and nxxxxatrs function for getting attributes by index;
(160325) added file quote as needed in save function;
(160329) corrected doc (selectlen/select);
(160405) corrected doc, added linkXYZV;
(160408) utils: strloc, strf3loc
- 1.3.5: (160410) added init(folder)
- 1.3.6: (160511) added 'symmetric_node' (Ganessa_TH);
(160531) reviewed compatibility with dll versions since 2014.
- 1.3.7: (160622) added OpenFileMMI Classes: SelectModel, SelectFile, ExecStatus;
(160706) added 'dist2link'; added 'util.dist_to_poly' as pure python backup;
OpenFileMMI uses simulation interface from caller, or None;
changed all Classes to new style;
added 'len' method to 'Selected' and 'Elements'; added 'Graph'
- 1.4.0: (160715) setup changed to build whl from source files;
(160719) minor bug fix in util.plotmes - reuse same fig in non interactive mode
- 1.4.1: (160820) OpenFileMMI SelectFile with null extension; load error handling
- 1.4.2: (160830) added AUTO and QUAL storestep constants; minor fix in gencmd;
added include_depth optional attribute to 'linkXYZV';
(160915) added version_2016b in the Picwin32 lookup table;
(160919) added SelectFolder in OpenFileMMI;
(160922) added setlinkattr as a synonym of setbranchattr;
(160927) intermediate API for Piccolo6 2016 B (dec-2016)
- 1.5.0: (161010) added 'getkeyword';
(161019) minor change in util.plotmes: 160719 patch reviewed for better output;
(161124) added 'stat_quantiles', 'stat_duration', and 'Dynamic_Stats'
- 1.5.1 (161212) bug fix on ts* functions without result file;
added 'retry' optional argument to full_solveH
- 1.5.2 (170105) added folder=option in util.list2file
(170110) build with numpy 1.11.0 - compatible with
- 1.7.0 (170119) build with BIND(C) instead of DEC$ATTRIBUTE C, REFERENCE;
required with ganessa_SIM > 170117 (renamed API functions);
(170125) added fixed_interval to tsdevice, now return float values
- 1.7.1 (170221) minor changes in util.IniFile (default encoding utf-8);
switch to unicode_literals in sim&th, util and prot;
(170223) added compiled util.dist, util.dist_p_seg, util.dist_to_poly
- 1.7.2 (170228) added OpenFileMMI.setlanguage function (FR/US or UK);
(170304) fix getMinMax/getallminmax break in 1.7.0
- 1.7.3 (170313) added WQ, MOD and LNK constants; added DICT.END;
added modulekeyword and attrkeyword;
(170331) added shearstr; match Piccolo 2017 --> NO !
- 1.7.4 (170407) added silent option to init;
(170424) added default '@safege.com' domain to util.envoi_msg
- 1.7.5 (170426) improved util.plotmes(x) for horizon > 24h;
(170512) added module 'multithread';
(170515) fix parent.inidir error in OpenFileMMI; added solveH
- 1.7.6 (170613) added constants (STATIC, QUA.VISUSTEP) and util.group;
minor bug fix in Selected, getMinMax and Dynamic_Stats;
(170618) added title to OpenFileMMI.SelectFile and SelectFolder;
added util.pageplot;
(170620) replaced litteral symbols with attrkeyword();
(170627) match Piccolo 2017 (apr 2017);
- 1.7.7 (170705) added cwfold;
(170707) optional arg for sim&th.close(arg) and prot.close(arg);
added C1 in util.plotmes for chlorine plots;
- 1.7.8pr1 (170808) doc update; upload to pypi
- 1.7.8 (170817) replaced IniFile with json/xml version
- 1.7.9pr1 (170824) prepared for Piccolo 2017b;
(170830) added getunitcoef
- 1.8.0 (170907) sim.py split into core, core_sim, core_th; changed/fixed path lookup;
(170918) added resfile, raw_getcmdw, raw_stat_duration, raw_stat_quantiles
- 1.8.1 (171004) added util.update_package
- 1.8.2 (171016) added util.str2uni (tries utf8 the cp1252 - reverse from unistr);
(171018) minor bug fix for util.update_package;
(171103) added sort.HeapSort class and Graph.dtree
- 1.8.3 (171109) added error msg when OpenFileMMI is imported before sim or th;
(171110) fix _pyganutl import broken in 1.8.0 (util.dist, util.dist_to_poly);
(171114) added multithread.MultiProc class
- 1.8.4 (171120) bug fix / changed multithread.MultiProc.run return values as 3 lists
- 1.8.5 (171120) added util.plot_close to avoid Fatal Python error at exit;
(171128) added linkbbox and util.gbool
- 1.8.6 (171201) added progress keyword to parallel.MultiProc; full_version;
added util.send_report
- 1.8.7 (171208) fix update_package not succeeding in update 'ganessa'
- 1.8.8 (171212) improved update_package proxy configuration using .json files;
added Picwin32.dll lookup into PICCOLO_DIR environment variable;
and '_ck' optional folder suffix
- 1.8.9 (171220) updated full_version; added UPN lookup in send_report;
(180126) added importEpanet and exportEpanet
- 1.9.0 (180227) added con2uni for converting console output to unicode (cp850)
(180305) fixes related to 2to3: _getdll: environ; util: winstr and utf,
IniFile encoding, cmp_version, added version_as_tuple;
(180328) send_report timeout to 2 seconds, added util.is_text;
2 and 3 compatibility changes for unistr, str2uni, utf2uni, ascii.
- 1.9.1 (180418) added a reduce function to parallel.MultiProc; fix seq run
(180502) update_package looks for package in current folder
- 1.9.2 (180514) fix python3 issue in parallel submodule; minor OpenFileMMI fixes;
(180518) fix update_package compatibility with parallel
- 1.9.3 (180525) added epanet2 API and dll (py27 only); fix epanet2.getlinknodes;
(180530) added util.ws
- 1.9.4 (180531) fix utf-8 decoding for IniFile1L;
(180604) fix getindex; added exists
- 1.9.5 (180607) added epanet2 API and dll (compiled from epanettools 0.4.2);
(180608) added an example in README;
(180613) plot funcs moved from ganessa.util to ganessa.plot
- 1.9.6 (180615) fix sim.init handling non-ascii chars in folder name (uploaded 180621)
- 1.9.7 (180705) fix util.IniFile handling non-ascii chars in file name;
(180718) fix OpenFileMMI issue with inidir;
(180813) added support for Piccolo 2018 (released 2018-07-25) and uploaded
- 1.9.8 (180814) 64-bits version for Ganessa_SIM (python 3.6);
minor OpenFileMMI changes (clear_exe, bt_exe_state);
(180815) upload wheels for python 3.7 (32 and 64 bits).
- 2.0.0 (180816) util.group fix (python 3.7); added verbose param in util.update_package;
(180820) added 'wqtracevectsize' for returning the max size of WQ;
concentration vector usable for tracing origin of water;
(180823) added geojsonfile for writing to geojson; fix minor midfile issue;
(180829) added C:/Program Files lookup in x64 env; geojson reader;
(180831) release and upload
- 2.0.1 (180910) util.list2file minor fix; doc fix; minor Elements changes;
(180919) fix ganessa.th break in 2.0.0;
(180924) added orient keyword in ganessa.plot functions; slight behavior change
- 2.0.2 (181003) added util.strf2loc; doc update;
(181011) minor change in sim.seleclen; added util.call_until_false;
(181025) minor fix in ganessa.prot;
(181030) release and upload
- 2.0.3 (181105) added plot.pageplotx; (13) added '.' at head of prot lookup folders;
(181119) changed geojson and midfile to conform to shapefile 2.0;
(181203) added '_cl' suffix option to the Piccolo lookup folder;
len for Selected, Elements and derived iterators;
(181207) fix util.IniFile1L.save with python 3.x;
(181209) doc updated; release and upload
- 2.0.4 (181218) debug mode for unicode control; util.IniFile.get returns ustr;
(181220) OpenFileMMI.ExecStatus.clear: remove 'all' kwarg;
added len to getMinMax and DynamicStats iterators
- 2.0.5 (181229) added util.perfs;
(190107) handle OpenFileMMI.SelectModel(usedef=False);
(190109) changes in update_package permission lookup;
(190131) release and (190211) upload
- 2.0.6 (190411) minor fix in parallel.required_cpu;
(190416) minor evolution to parallel.MultiProc: alternate erfun call on Exception;
(190423) release and upload
- 2.0.7 (190617) added 'extra_data' keyword to sim.savemodel;
(190715) added DYNSTOP SimulationError; minor doc fix;
(190819) improved simulation error check in full_solveH, solveH, solveTH;
(190821) added util.get_python_exe;
(191007) minor fix in OpenFileMMI.SelectFile;
(191008) release and upload
- 2.0.8 (191015) fix README.rst;
(200106) added upstream and downstream methods to sim.Graph;
(200204) fix new python 3.8 dll directory search;
release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.0.9 (200205) fix prot with python 3.8 dll directory search + minor changes;
release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.0 (200214) fix urllib3 requiring proxy scheme in get_proxy;
(200220) Piccolo versions 2017+ required for python 3.x+;
fix to dll directory search, related to FlexLM; fix Example.py;
release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.1 (200306) new sim.WQSources() iterator;
(200313) fix util.scaladjust for range below 1;
fix chlorine (C1) plot.plotmes(x);
(200314) add added util.is_wq and sim.wqtslen; fix sim.tsval for WQ TS;
(200323) doc fixes; add module constant KW (MOD kw, QUA, INV);
add optional return_type=True kw to sim.Selected;
(200324) fix workdir & result file in virtualstore;
release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.2 (200506) add util.IniFile.remove;
(200511) release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.3 (200603) plot.plotmes: single (static) measurement plotted as an horizontal line;
(200604) OpenFileMMI.SelectModel: chdir to model folder to allow relative inner read;
(200619) added en2emu sim-like minimal compatibility module;
(200622) added nbvertices() and fake get_labels();
(200629) release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.4 (200708) dll lookup in '.';
(200819) minor fix on plot.pageplot;
release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.5 (200824) replace util.ascii with util.myascii;
(200915) plot.pageplot(x) allows multiple ts per graph; fix cmdfile;
(200922) added demand profile query by zone and code/zone (tsdemand);
(201109) added util.read_as_idpic;
(201119) release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.6 (201221) fix prot error with null path chunks;
(201222) fix Ganessa_TH integration not working properly;
(210126) added util.split_poly_at; release and upload
- 2.1.7 (210301) plot.plotmes(x) plot tank bottom and top water level when prefixed with '=';
(210307) addl single value plot as horizontal line in plot.pageplot;
(210310) add util.utf8_bom_encoding(file);
(210324) fix util.split_poly_at ValueError: not enough values to unpack (expected 3, got 2);
release and upload (2.7-32 / 3.7 / 3.8 only)
- 2.1.8 (210325) added Graph.pop and len(Graph); added SelectModel.update_info;
fix missing .pyd components resulting in suboptimal use of the API;
release and upload (2.7-32 / 3.7 / 3.8 / 3.9)
- 2.1.9 (210426) util.IniFile removes the -<maxvers><minvers> suffix on param save;
(210428) prot now seek extensive paths incl. ../SafProdLicMgr, C:/Logiciels etc.;
(210429) fix geojson writer (use Transformer, swap return coords);
(210430) release and upload (2.7-32 / 3.7 / 3.8 / 3.9) - last 2.7 release
- 2.2.0 (210506) fix pypi doc; change _fresult and _workdir lookup;
(210517) minor changes to util.strf3 and strf2
(210527) fix Ws10 using utf8 rather than cp1252 in util
(210531) release and upload (3.7 / 3.8)
- 2.2.1 (210609) util.send_report include OS version
(210610) OpenFileMMI.SelectFile: invisible contour & parent cascade for subframe
(210614) Add %localappdata%/Programs/Safege & Suez... to the search path
(210616) Add Inetum to the lookup folders for Piccolo
(210617) Add update_info(-1) to OpenFileMMI.SelectFile
(210618) release and upload (3.7 / 3.8); (210621) upload (3.9) - not passed
- 2.2.2 (210621) Add %localappdata%/Programs/Gfi Progiciels & Inetum to the search path
(210621) fix README.rst; release and upload (3.7 / 3.8 / 3.9);
- 2.2.3 (210623) Minor fix to OpenFileMMI.SelectModel.update_info(-1);
(210624) Added IsolatedNodeSimulationError exception;
(210701) lookup 'Inetum' folder before 'Gfi Progiciels'; addl TS for plot.plotmes
(210702) release and upload 32 (3.5 / 3.6 / 3.7 / 3.8) and 64 (3.7 / 3.8)
- 2.2.4 (210705) fix dll search path order with D: partition
(210723) OpenFileMMI.SelectModel silent read .dat by default
(210819) Handling of python embedding into dll caller (Piccolo.exe) - beta
(210823) add sim.is_embedded()
(210901) add sim.dll_version() from API = not requiring init(); release and upload (3.8 / 3.9)
- 2.2.5 (210913) adaptation to python 3.10;
(210914) plot changes (uses- axes and figures rather than default pyplot funcs);
(210927) fix util.get_proxy doc and return value;
(210929) fix getvar truncate output to 48 (now 256); add model_filename(); util.update_package exits in embedded mode.
(211004) OpenFileMMI.SelectModel kwarg show_emb=False hides dialog in embedded mode;
(211012) util.IniFile kwarg folder=None allows load/save to alternate location;
(211013) OpenFileMMI.SelectModel fix chdir error when filename has no dirname;
(211020) add OpenFileMMI.SelectFile.setfilename;
(211026) add fname property to OpenFileMMI.SelectFile, SelectModel, SelectFolder;
(211027) release and upload (3.8 / 3.9 / 3.10)
- 2.2.6 (211028) add OpenFileMMI.SelectFolder.add_extra_info; .fname setter;
(211106) add type hint to most functions;
(211109) fix _dll_version in embedded mode;
(211112) add emb_model_folder() function;
(211116) minors changes in OpenFileMMI; new util.piccolo_context function for color settings;
(211117) release and upload (3.8 / 3.9 / 3.10)
- 2.2.7 (211124) fix is_wq() for water hardness (TH or HD or DU); setlang accepts 1 or 2 letter arg;
(211126) OpenFileMMI.add_extra_model_info append to previous line if returned text starts with backspace \b;
(211216) refdate returns (unicode) str;
(211230) release and upload (3.8 / 3.9 / 3.10)
- 2.2.8 (220128) fix util compatibility with windows servers;
(220203) dll lookup on E: if it exists and D: does not;
(220203) release and upload (3.8 / 3.9 / 3.10) (should have done it yesterday !)
- 2.2.9 (220211) fix non ascii str passed to Selected must be bytes2;
(220214) fix util.update_package: replace -use-binary with -prefer-binary; -trusted-host pypi.org;
(220222) release and upload (3.8 / 3.9 / 3.10)
- 2.3.0 (220304) fix plot.pageplot[x] issue with python 3.9+ (ax.title); (220309) tune xscale for t < 1h;
(220318) fixed _getdll.AddDllDirectory to allow more than 1 call / close in any order;
(220324) WQSources return str;
(220419) allow multiple init / close (reloads the dll)
(220420) add Selectid(xxx) for Selected(xxx, return_type=False)
(220421) minor change to [E:| D:], C: lookup; release and upload (3.8 / 3.9 / 3.10)
- 2.3.1 (220428) added proj.FrenchProjMapping to handle symbolic / EPSG mapping
(220505) added proj.get_spatial_ref to get SPATIAL-REF from .dat
(220701) added SelectFile.set_rw_mode(x) allowing to change read/write mode
(220706) added SelectFile(allow_reset=False) creates a button calling .clearfilename()
(220719) added util.strf4
(220720) added TableValues iterator for getting values from tables
(220721) added implemented(func_or_iter_name) for checking availability
(220802) release and upload (3.8 / 3.9 / 3.10)
- 2.3.2 (220804) added linkattrv, tankattrv getters for array attributes
(220810) added util.FichInfo.sub_module: used in banner() and send_report
(220820) added Controls iterator (220821) extended with control entities
(220823) plot.plotmes savefig DPI doubled to 300; always write ID (name) on 2 lines if too long
(220824) ControlEntities iterator
(220829) modified Controls to return ControlId and ControlData; added command_logger
(220831) added 2021 and 2022 Picwin32.dll version lookup
(220831) release and upload (3.8 / 3.9 / 3.10)
- 2.3.3 (220902) added CommandLogger.logs to handle non unicode multi word in cmdfile
(220909) add 3rd optional arg to getcalind
(220920) minor fixes in OpenFileMMI.SelectFile; build wheel for 3.11-64
(220923) add inv_varcount, inv_variable, and IPSVariable iterator
(220927) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.4 (221010) plot.plotmes prefix title with file basename; add Graph.extended_segment; doc update
(221103) fix util.quotefilename causing an exeption when a null string is passed
(221110) add Graph.antennas and sort.HeapSort.modify
(221110) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.5 (221111) add SupplyNodes() iterator
(221129) add util.csv_with_tabs
(221213) util.gbool: added "ko" and "x" as False
(221221) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.6 (230206) tsvals: efficent retrieval of multiple TS
(230207) util.update_package: added --trusted-host files.pythonhosted.org and --use-feature=truststore
(230218) add proj.get_transformer and proj.get_transformer
(230220) add proj.to_epsg and proj.to_symbolic
(230221) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.7 (230224) add "null" FrenchProjMapping
(230311) add xkcd style handling in plot.plotmes(x) and plot.pageplot(x)
(230320) add pic.attrname and pic.attrindex (requires Ganessa_SIM >= 230320); add compatibility with recent but not last version of Ganessa_SIM
(230322) plot.plotmes handles non ascii chars (débit, réservoir, M³/h) but this help file does not ?!
(230327) minor changes to (Table and) TableValues returning demand coefs (requires Ganessa_SIM >= 230328)
(230330) Selectid/Selected returns empty iterator for blank selection
(230331) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.8 (230404) fix _getdll.AddDllDirectory use when path is empty (embedded case); fix Writer.field() 4th arg in midfile and geojsonfile
(230413) proj.guess_proj calls get_spatial_ref in module mode
(230419) add ganessa version in send_report
(230502) tsvals: change return order to allow building a dict from return value
(230511) plot.pageplot allow plotting more than 2 TS per plot
(230623) add compiled util.shearstress for direct shearstress calculation
(230626) fix epanet2.solveH() fail to use temp bin file; fix epanet2 computation of tank diameter
(230710) fix minor issues in util.roundval and util.scaladjust
(230712) added epanet22 API and dll (integration manually transposed from epanettools 0.4.2)
(230809) added owa_epanet22 providing epanettools compatibility for owa-epanet
(230817) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.9 (230908) add .get() alias to .getfilename() / .getfoldername() in OpenMMI Classes
(230922) "default project" management in owa_epanet22, for multiprocessing purpose
(231002) updated en2emu and OpenFileMMI to basic handling of Epanet .inp File
(231004) updated sim.update_package to seek importlib.metadata.version
(231017) updated en2emu with extensions, doc; improved html doc
(231018) release and upload (3.8 / 3.9 / 3.10 / 3.11)
- 2.3.10
(231025) updated en2emu with WQ simulation and changes in epanet project
(231106) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12)
- 2.4.0
(231114) add Controls.__len__
(240112) handle en2emu error loading .inp model (non-ascii filename), catch it in OpenFileMMI.SelectModel
(240115) minor improvement in en2emu.ENmodel.save_as: keep comments after changed section header
(240116) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12)
- 2.4.1 (240307) add util.get_this_python_display_name
(240412) added MonteMario projection in proj.FrenchProjMapping
(240418) added util.profilise_folder and util.user_writeable, used by FichInfo and IniFile
(240503) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12)
- 2.4.2 (240611) review util.get_this_python_display_name lookup
(240613) added pygansim2023.pyd for use with 2023 and later Picwin32.dll
(240616) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.4.3 (240625) fix OpenFileMMI.SelectFile use when ganessa.sim not imported
(240702) send_report includes python exe name
(240702) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.4.4 (240702) fix path split in util.profilise_folder ("." case)
(240704) numpy < 2.0 required for ganessa < 2.4.4 or python < 3.12
(240715) util.user_writeable check uses a tempfile in case of parallel runs
(240717) added Pipes([*attrs]) iterator
(240718) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.4.5 (240724) util.send_report sender lookup
(240808) change dependancy numpy < 2.0 if python < 3.13;
(240808) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.4.6 (240809) plot.plotmes[x] labels keyword for ("simulation, "Reference")
(240810) add optional arg name[="autre"] to proj.to_symbolic
(241030) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.4.7 (241219) parallel.MultiProc.run_sequential calls term if defined
(250107) added linknodes function that returns 'from' and 'to' nodes
(250108) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.4.8 (250131) added script full path to util.send_report content
(250210) added Graph.antennas(strict=True) optional keyword
(250211) change profilise_folder to operate when folder not in users;
user_writeable also force profilise when folder name starts with "program";
PYTHON_FROZEN constant; update_package exits with unmatch and frozen/embedded python
(250213) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.5.0 (250220) fixed util.is_folder_writeable for parallel use
(250225) added util.hhmmssd: hour with fractional seconds; sim.all_ts: return all
TS for the given attribute, exact results with Ganessa_SIM >= 250225;
hresults_block and hresults_block_xtra.
(250226) vectorise util.tsadd and add shape parameter ("constant, "linear")
(250127) add demand_pressure: demand/pressure related parameters
and code_pressure: activation of demand pressure for a code.
(ganessa_sim API only)
(250303) doc fixes.
(250303) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.5.1 (250306) Extend sort.HeapSort with key_index option; rename HeapSortRank; move
key option to HeapSortFunc; add Graph.wtree and Graph.path; fix Graph.dtree.
(250310) include '_pygansim2025' in dll lookup (demand_pressure and code_pressure);
fix proj with MonteMario vs rgf-ccxx recognition; minor improvements in
OpenFileMMI (parent.v1 and parent.finalise optional, new get_info method).
(250325) fix issues in midfile and geojsonfile (Readers); compliance with shapefile.
(250327) build '_pygan_th2025.pyd' and include it in dll lookup.
(250401) proj.FrenchProjMapping simplified as dict subclass.
(250403) en2emu.is_embedded and .resfile required when no Picwin32/ganessa_Sim.dll.
(250403) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.5.2 (250407) fix getcalind: _dll_api.dll_version() undefined with dll jan-2022.
(250410) fix en2emu reset / loadbin issues.
(250416) fix core_th: Callable typo (250402) disabling its use in 2.5.1.
(250422) added SIM suffix as an alternative for language (dll lookup)
(250422) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
- 2.5.3 (250424) Graph is a subclass of (link) dict; pop is replaced with pop_link.
(250506) allow use of non compiled side modules with non-Windows platforms
(250619) fix _getdll missing weird configuration handling; added result_filename;
OpenFileMMI.SelectModel(ext="bin") use result_filename in embedded mode.
(250626) added OpenFileMMI.ask_for_single_input; OpenFileMMI.SelectFile use
model_filename + any exts in embedded mode, if file exists.
(250630) release and upload (3.8 / 3.9 / 3.10 / 3.11 / 3.12 / 3.13)
15. ganessa.sim&th/Classes [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
Classes available to ganessa.sim and ganessa.th
15.1. Classes/Graph_, extrnodes,
adjlinks, adjnodes,
propagate, dtree,
wtree, antennas,
segment_other_end, path [ Objects ]
[ Top ] [ Classes ] [ Objects ]
PURPOSE
Builds a simple graph from the current model topology.
SYNTAX
graph = Graph([orientation])
METHODS
- from_n, to_n = graph.extrnodes(alink): returns the from and to nodes of alink
- linkset = graph.adjlinks(anode): returns links adjacent to anode as a set
- nodeset = graph.adjnodes(anode): returns nodes adjacent to anode as a set
- plist = graph.oriented_links(anode): returns a list of (link, index) tuples
- pairs = graph.adj_links_nodes(node): return a set of (link, nodes) tuples
- link, from_n, to_n = graph.poplink(): remove a link and returns it with from and to nodes
- slinks, snodes = graph.propagate(anode [, maxlen= -1]):
returns the sets of links and nodes connected to 'anode' by a path of max link count 'maxlen'
- tree, slinks = graph.dtree(anode [, maxlen= -1]): returns a tree as an ordered dict,
of minimum link count.
- tree = graph.wtree(anode [, weight="L"]): returns a tree as an ordered dict,
of minimum weight (weight for a link is linkattr(alink, weight)).
- linkset, nodeset = graph.downstream(anode [, update='Q'] [, maxlen=-1]):
returns downstream elements with respect to 'update' attribute direction (default Q)
- linkset, nodeset = graph.upstream(anode [, update='Q'] [, maxlen=-1]):
returns upstream elements with respect to 'update' attribute direction (default Q)
- linkset = graph.extended_segment(alink [, addl_boundary_nodes=None]):
returns the set of links on the same segment as alink
- blink, bnode, count = segment_other_end(alink, anode):
returns the other end and link count of segment starting at node anode with link alink
- plist [, unlooped] = graph.antennas([keep_nodes=None][, strict=True]):
returns a list of (link, nodes) tuples of element in antennas. kept_nodes allow to mark
a sequence of nodes to be considered not belonging to antenna.
If strict=False, allow 2 or more parallel segments to be handled as a single segment;
the list of links removed for unlooping is also returned.
- nlist, klist, wlist = graph.path(from_n, to_n [, weight=""]):
returns a minimal path between 'from_n' and 'to_n' nodes. Minimal means cumulated weight when
weight is present, link count otherwise.
ARGUMENTS
- str orientation: the attribute sign will be used for orienting the graph.
(default None, orientation from -> to)
- str alink, anode, node: link, node ID
- int maxlen: compute graph propagation up to maxlen steps (<0 if not limited)
- str weight: attribute to be used as weight
- str update: attribute to be used as link direction (defaut 'Q'; use '' or None to
disable direction update)
- sequence addl_boundary_nodes: sequence of nodes to consider as additional segment boundaries
RESULT
The graph is built from the current model links and nodes:
- set linkset: set of adjacent links ID
- set nodeset: set of adjacent nodes ID
- plist: list of tuples (ID alink, int idx) where idx is the index
of the other node in graph.edges[alink] (graph.edges[alink][1-idx] == anode).
- sets slinks, snodes: sets of links and nodes ID.
- OrderedDict tree: ordered dict where key are node IDs, values are a link ID
and a depth integer value (dtree) or cumulated weight (wtree).
The link allows to connect the node at minimum weight.
- list nlist: list of nodes forming the path (nlist[0] is from_n, nlist[-1] is to_n)
- list klist: list of links connecting node to the next (klist[-1] is "")
- list wlist: list of decreasing cumulated weights to 'to_n' (wlist[-1] is 0).
[wlist[0] - x for x in wlist] is the increasing cumulated weights from 'from_n'.
REMARK
- first key, value returned by dtree/wtree is the root node, and ("", 0)
- dtree may be incorrect up to 2.5.0.
HISTORY
- new in 1.3.7 (160706)
- 1.7.6 (170620): use attrkeyword() for IN and FN
- 1.8.2 (171103): added graph.dtree
- 1.8.5 (171128): updated dtree, added graph.adjnodes
- 2.0.8 (200106): added revert, upstream, downstream
discard degenerated links (same from and to node)
changed internal representation
- 2.1.8 (210325): added pop and __len__
- 2.3.4 (221010): added extended_segment
(221110): added antennas
- 2.4.8 (250210): added segment_other_end; keyword antennas(strict)
- 2.5.1 (250305): added path and wtree; fix HeapSort use for dtree
- 2.5.3 (250424): graph inherit from (link) dict; remove self._edges;
replace pop with pop_link
16. ganessa.sim&th/Compatibility_ [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The installation of ganessa is compatible with several versions of Picwin32.dll
(regular Piccolo / Picalor). Missing functions in older versions should NOT be called.
HISTORY
- 2014 -> 141203 Piccolo5 -- release 2014
- (2015a -> 151217 Piccolo6 & Picalor6 -- release 2015 (Unstable)) - discarded
- 2015 -> 160121 Piccolo6 -- release 2015 sp1
- 2016 -> 160419 Piccolo6 & Picalor6 -- release 2016
- 2016a -> 160930 Piccolo6 release 2016b (incomplete; compatible with 1.4.2)
- 2016b -> 161216 Piccolo6 & Picalor6 -- release 2016b (1.5.0 - 1.5.2)
- 2017 -> 170627 Piccolo6 & Picalor6 -- release 2017 (1.7.7 - 1.7.8)
- 2017b -> 1709xx Piccolo6 & Picalor6 -- release 2017b (1.8.0 - 1.9.6)
- 2018 -> 180725 Piccolo6 & Picalor6 -- release 2018 (1.9.7 - )
- 2020 -> 200306 Piccolo6 & Picalor6 -- release 2020 (2.1.1 - )
- 2021 -> 2103xx Piccolo6 & Picalor6 -- release 2020b (2.1.1 - )
- 2022 -> 2209xx Piccolo6 & Picalor6 -- release 2022 (2.3.3 - )
- 2023 -> 230320 Piccolo6 & Picalor6 -- release 2023 (2.3.7 - )
- 2025 -> 250225 Piccolo6 & Picalor6 -- release 2025 (2.5.0 - )
REMARK
ganessa is compatible with matching or newer versions of Ganessa_SIM/Ganessa_TH.dll only;
except a compatibility break on 170117.
17. ganessa.sim&th/Constants_ [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
Several categories of constants are available:
- constants defining a type of element: see BRANCH or LINK, NODE, RESERVOIR or TANK
- constants defining a command module: M.COM or M.ROOT, M.GEN, M.SIM etc.
- constants defining a command within a module: M.SIM.EXEC
- keywords
18. ganessa.sim&th/Exceptions_ [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
Exceptions available to ganessa.sim and ganessa.th
18.1. Exceptions_/useExceptions, GanessaError,
SimulationError, IsolatedNodeSimulationError [ Exceptions ]
[ Top ] [ Exceptions_ ] [ Exceptions ]
SYNTAX
- oldstat = useExceptions([status])
- try: ... except GanessaError:
- try: ... except SimulationError [as exc]:
- try: ... except IsolatedNodeSimulationError [as exc]:
ARGUMENTS
bool status: if True, errors will raise exceptions
RESULT
- bool oldstat: previous error handling mode
- exception exc: exception object. The attribute exc.reason will provide
additional information on the origin of error
DESCRIPTION
SimulationError is a derived class of GanessaError.
IsolatedNodeSimulationError is a derived class of SimulationError, thrown when a simulation
error originates form isolated nodes.
The simulation error subtypes (exc.reason) are the following:
- SIMERR.ISOL: Isolated nodes
- SIMERR.SLOW_CV: Slow convergence (convergence not obtained within max iteration count)
- SIMERR.Unstable: Unstability (flip between 2 or more equilibrium points)
- SIMERR.FCTAPP: Equipment(s) or storage(s) do not operate properly;
they can be retrieved with the Unstable() iterator
- SIMERR.DIVERGE: Divergence (convergence criteria increase)
- SIMERR.DYNSTOP: The simulation did not complete
- SIMERR.STRUCT: Structural inconsistency
- SIMERR.MEMALLOC: Memory allocation error (WQ or inverse problem)
REMARK
By default, errors do not raise 'GanessaError' exceptions. If set to True,
errors raise exceptions with a string name giving the error message and a int reason
giving the type of exception.
HISTORY
- 190715: added SIMERR.DYNSTOP
- 210624: added IsolatedNodeSimulationError
- 220415: Piccolo 'quit' command terminates
19. ganessa.sim&th/Functions_ [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
functions available to ganessa.sim and ganessa.th
19.1. Functions_/addSHLtype, addSHL,
updateSHL, delSHL [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
- addSHLtype: Add / modify a single head losses (SHL) from the SHL table
- addSHL, updateSHL, delSHL: Add / modify / delete single head losses (SHL)
objects for a given pipe
SYNTAX
- istat = addSHLtype(shltype, values [, comment])
- istat = addSHL(id, shltype, nb)
- istat = updateSHL(id, shltype, nb)
- istat = delSHL(id [, shltype])
ARGUMENTS
- string shltype: type of shl to be added/modified
- float values: direct and reverse SHL coefficients
- string comment: long name of the SHL type
- string id: id of pipe
- int nb: number of SHL of type shltype to be added / updated with
RESULT
int istat: error status (0 if OK)
COMMENTS
If shltype is not given or is '' for delSHL then all SHL are removed from pipe.
REMARK
- these functions require version 2015/12 or higher of Piccolo/Ganessa dll
19.2. Functions_/areas [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
return areas associated with nodes/links
SYNTAX
area = areas(typelt, attr)
ARGUMENTS
- int typelt: type of object (NODE or LINK)
- str attr (optional): area attribute to be returned (ZN or ZP). Default to 'ZN'
RESULT
- counter area: dictionary of node/link counts by area
HISTORY
From version 1.9.0 (05/04/2018) area are returned as unicode strings.
19.3. Functions_/attr_is_str [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
DESCRIPTION
Returns True if the given attribute in the current language is a str value.
SYNTAX
ret = attr_is_str(attrib)
ARGUMENT
str attrib: symbol for the attribute
RESULT
bool ret: True if the attribute value is of type str, False if not
REMARK
Allow to select which function to use
EXAMPLE
linkattrs if attr_is_str(attr) else linkattr
HISTORY
Created 2024-07-18 (2.4.4)
19.4. Functions_/cmd, addcmdw,
execute_, cmdfile [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- istat = cmd(scmd)
- istat = cmdfile(fname [, args])
- istat = addcmdw(scmd)
- istat = execute(scmd1 [ ..., scmdn][, dbg= True])
ARGUMENTS
- string scmd: command line to be executed
- string fname: data/command file name to be read/executed
- string args: optional argument(s) to the command file, as one single string
- string scmd1: command line(s) to be executed ('\n' is handled as a command delimiter)
- string scmdn: optional command lines(s) to be executed (same as scmd1)
- boolean dbg: optional, makes commands to be echoed in the log file.
RESULT
int istat: error status (0 if OK)
REMARKS
- cmd executes the given command
- cmdfile reads/executes the commands from the file.
- addcmdw pushes the command onto the command stack.
- execute pushes the given commands on the stack and executes them.
- The stack size (addcmdw, execute) is 64 or 128.
If an error occurs while reading a file or nested files, the execution stops.
If the useException mode is set, the error will raise a GanessaError
HISTORY
- 1.9.6 (180615): convert str to cp1252
- 2.1.5 (200915): extend cmdfile to allow cmdfile(file, arg1, arg2, ..)
- 2.3.2 (220829): command_logger allows to log activity of cmd, cmdfile and execute
- 2.3.3 (220902): add CommandLogger.logs for handling cmdfile multiword command
19.5. Functions_/commit [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Executes all the commands available on the stack (first in, first executed)
SYNTAX
istat = commit()
RESULT
int istat: error status (0 if OK)
REMARK
If an error occurs, the remaining part of the stack is cleared
19.6. Functions_/cwfold [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
ret = cwfold(folder)
ARGUMENT
str folder: folder name where journal (piccolo.jnl) and work files will be created
RESULT
bool ret: True if folder exists; False otherwise
HISTORY
introduced in 1.7.7 (170705)
* 1.9.6 (180615): fix non-ascii folder str converted to cp1252
19.7. Functions_/dist2link [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the distance and curvilinear abcissae of a point from the given link
SYNTAX
d, s1, s2 = dist2link(id, x, y)
ARGUMENTS
- string id: id of link element
- double x, y: coordinates of the point
RESULT
- double d: distance of the point to the link polyline
- double s1, s2: curvilinear distance of the projection from each extremity
HISTORY
introduced in 1.3.7 (160706)
REMARKS
- dist2link requires version 2016b or higher of Piccolo/Ganessa dll;
if not a pure python calculation is made using linkXYZV
- the polyline length is s1 + s2;
s1= 0 or s2= 0 when the point projection is outside the polyline
- if the id does not exists the return value is (-1, -1, -1)
19.8. Functions_/dll_version, full_version [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- yyyymmdd = dll_version()
- text = full_version()
RESULT
- int yyyymmdd = dll version()
- str text = full_version()
REMARK
Starting with 2.2.4 (210901), if called before init(), dll_version() will
return the version if the .dll is newer than 210831, 0 otherwise.
HISTORY
- dll_version introduced in 1.8.0 (170907)
- full_version introduced in 1.8.6 (171201)
- returns api.dll_version() if defined (210901)
19.9. Functions_/extrnodes [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the from and to node (indexes) form link index
SYNTAX
i_from, i_to = extrnodes(i_link)
ARGUMENTS
- int i_link: index of the link
RESULT
- int i_from: index of from node
- int i_to: index of to node
REMARKS
- Internal indexes start with 1
- Internal index of an element may change after a simulation
or a modification of the model.
- see linknodes to get from and to node IDs
19.10. Functions_/gencmd, gencmdw,
raw_gencmdw, _gencmdw [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Those fuctions allow to generate a language independant command line
based upon the keywords id of a module and its commands (see M).
SYNTAX
- istat = gencmd (module, icmd, [word, scmd, extmode])
- istat = gencmdw(module, icmd, [word, scmd, extmode])
- istat = _gencmdw(module, icmd, [word, scmd, extmode])
ARGUMENTS
- module: constant id for the module
- icmd: constant id for the command in the module (or NONE)
- word: constant id for a keyword (or NONE) (optional)
- scmd: additional string (optional)
- extmode: if set to 1, the command is appended to the previous one (optional)
- string scmd: command line to be executed
RESULT
int istat: error status (0 if OK)
REMARKS
- gencmd builds and executes the given command
- gencmdw and _gencmdw build the command and push it onto the command stack
- gencmd and gencmdw allow a more flexible entry of the first 2 arguments
- If the useException mode is set, an error will raise a GanessaError
- raw_gencmdw is an exported version of _gencmdw
EXAMPLES
The following are equivalent:
- istat = _gencmdw(M.SIM.ROOT, M.SIM.EXEC, DICT.FULLPER)
- istat = gencmdw(M.SIM, "EXEC", DICT.FULLPER)
The following are equivalent:
- istat = _gencmdw(M.SIM.ROOT, M.SIM.EXEC, scmd="15:30")
- istat = gencmdw(M.SIM, "EXEC", scmd="15:30")
HISTORY
1.8.0 (170908): added raw_gencmdw
19.11. Functions_/getall [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
getall returns the value for all objects of the given type
SYNTAX
vect = getall(typelt, attr)
ARGUMENTS
- int typelt: type of element (LINK, NODE, TANK)
- string attr: attribute (result) for which value is requested
RESULT
- float[] vect: vector of values
REMARKS
getall(typelt, attr): when typelt =1 (links), attr can be either a regular attribute
('Q', 'V', 'D', etc.) or a node-based attribute such as 'P:M' for mean pressure,
'P:G' for geometric mean, 'P:N' for min and 'p:X' for max.
19.12. Functions_/getcodescount, nextcode [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
- getcodescount: returns count of used demand codes
- nextcode: returns the list of used codes with node count
SYNTAX
- ncodes = getcodescount(used_only)
- code, demand, count, nbchar = nextcode()
ARGUMENTS
- bool used_only: if True, only codes associated with at least
one node will be returned
RESULT
- int ncodes: number of codes to be returned
- str code: demand codes
- float demand: total nominal demand for the code
- int count: node count
- int nbchar: nb of chars in the demand code string
REMARKS
- these functions require version 2016 or higher of Piccolo/Ganessa dll
- If the GanSim Dll is too old those function will not return data
- See also the Demands(id) iterator
HISTORY
From version 1.9.0 (05/04/2018) codes are returned as unicode strings.
19.13. Functions_/getdemandbycode, getcodedemandinit,
nextcodedemand [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
- getdemandbycode: returns demand for a given node and consumer code by id
- getcodedemandinit: initialises and returns the number of pairs
SYNTAX
- demand, istat = getdemandbycode(nid, code)
- nbpairs = getcodedemandinit(nid)
- code, demand, codelen = nextcodedemand()
ARGUMENTS
- string nid: id of node
- string code: code for which demand value is requested
- int nbpairs: number of demand, csm pairs for the node
RESULT
- float demand: value of the demand (0 if not available)
- int istat: return code (0= 0K -1= unknown code 1= unknown node 3= dll too old)
- int nbpairs: number of code, demand pairs for the node
- string code: demand code
- int codelen: length of code string
REMARKS
- these functions require version 2016 or higher of the Piccolo/Ganessa dll
- If the GanSim Dll is too old those function will not return data
- See also the Demands(nid) iterator
HISTORY
From version 1.9.0 (05/04/2018) codes are returned as unicode strings.
19.14. Functions_/getid [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the id of an element by type and index
SYNTAX
id = getid(typelt, numelt)
ARGUMENTS
- int typelt: type of element
- int numelt: index of element
RESULT
unicode string id: id of the element
REMARKS
- Internal index starts with 1
- Internal index of an element may change after a simulation or
a modification of the model.
HISTORY
From version 1.9.0 (05/04/2018) ids are returned as unicode strings.
19.15. Functions_/getindex, exists_ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- num = getindex(typelt, sid)
- bret = exists(typelt, sid)
ARGUMENT
- int typelt: type of element
- string sid: ID of element
RESULT
- int num: index of element ID (starting at pos 1)
- bool bret: indicates if the element exists in the model
HISTORY
- getindex new in 1.3.3 but not working !
- getindex fixed in 1.9.4 (180604)
- exists created in 1.9.4 (180604)
19.16. Functions_/getkeyword, modulekeyword,
attrkeyword, attrname,
attrindex [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Get keyword or command name by index - for building
command language independant functions
SYNTAX
- sret = getkeyword(code)
- sret = modulekeyword(module, submodule)
- sret = attrkeyword(attr)
- sret = attrname(attr)
- iret = attrindex(sattr)
ARGUMENTS
- int code: code of the keyword (>0) or global command (<0)
- int module: code of the module (<0 for the submodule alone)
- int submodule: code of the module (0 for the module alone)
- int attr: code of the attribute
- str sattr: attribute
RESULT
- str sret: trimmed value of the keyword or global command or module submodule
(null string if the code or module/submodule is not recognised)
- int iret: code for the attribute (0 if undefined)
HISTORY
- getkeyword introduced in 1.4.2 (161010)
- modulekeyword and attrkeyword intoduced in 1.7.3 (170313)
- From version 1.9.0 (05/04/2018) results are returned as unicode strings.
- attrname and attrindex introduced in 2.3.7 (230320) and requires version 2023 (230320) or higher of Piccolo/Ganessa_Sim dll
19.17. Functions_/getvar, getunitname,
getunitcoef [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the value of a Piccolo expression or variable
SYNTAX
- str_val = getvar(expression)
- str_val = getunitname(attr)
- coef = getunitcoef(attr)
ARGUMENTS
- string expression: the expression or user variable to be returned.
See the Piccolo Reference Manual (chap. 2.3) for the predefined variables and
allowed expressions.
- string attr: symbol associated to an attribute
RESULT
- string str_val: a string containing the expected value. If the expression
or variable is not defined or implemented, the value '#NAN#' is returned.
- float coef: a float giving the unit coefficient / internal units
REMARKS
- User variable and simple expressions (system variables) can be abbreviated; e.g.
getvar("WORK") and getvar("WORKDIR") will return the work folder.
- Older Piccolo/Ganessa_SIM may return "#NAN#"" for some predefined variables.
- Unit coefficient of a given attribute can also be returned with
the adequate getvar('unite.'+attr).
- The unit coefficient is the number of internal units per user units:
1 (user unit) = coef (internal unit).
Internal units are SI units excepted:
- diameter and roughness: mm
- pressure: mwc
- concentrations: mg/l (or ppm)
- consumed mass (D1): g
EXAMPLE
If the user flow unit is 'l/s', since internal flow unit is 'm3/s',
getunitcoef("Q") returns 0.001
HISTORY
From version 1.9.0 (05/04/2018) info returned as unicode strings.
19.18. Functions_/implemented_ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
ret = implemented(name)
ARGUMENT
str name: name of the function or iterator
RESULT
bool ret: True if implemented, False if not
HISTORY
Created 2022-07-21 (2.3.1)
19.19. Functions_/importEpanet, exportEpanet [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- istat = importEpanet(fname)
- istat = exportEpanet(fname)
ARGUMENTS
string fname: file name to import from / export to (should be an .inp)
RESULT
int istat: error status (0 if OK)
REMARK
At import, .inp file is first converted to a .inp_cvt.dat Piccolo file,
then this file is read. Syntax error if any will refer to the converted .dat file.
19.20. Functions_/is_embedded [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
ret = is_embedded()
RESULT
- bool ret: indicates whether the python the package runs in is embedded in Piccolo.
REMARKS
- It is used by OpenFileMMI.SelectModel and SelectFile in order to hide the model selection.
- When python is run in embedded mode, from Piccolo, any modification performed in a python
script will occur on the current Piccolo model.
HISTORY
- introduced in 2.2.4 (210823)
- python embedding in Piccolo was introduced on 2025-06-23 in 2.5.3 (250630)
19.21. Functions_/linkattr, nodeattr,
tankattr, linkattrs,
nodeattrs, tankattrs,
attr_, attrs_,
meanattr, linkattrv,
tankattrv [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
- linkattr, nodeattr, rsvattr, attr: return numerical attributes
of a given element by id
- linkattrs, nodeattrs, attrs: return text attributes of a
given element by id
- meanattr: return mean attribute of from and to nodes given by BRANCH id
SYNTAX
- val = linkattr(id, attr)
- val = nodeattr(id, attr)
- val = tankattr(id, attr)
- txt = linkattrs(id, attr)
- txt = nodeattrs(id, attr)
- txt = tankattrs(id, attr)
- val = attr[typelt](id, attr)
- btxt, sz = attrs(typelt, id, attr)
- val = meanattr(id, attr)
- valx, valy, count = linkattrv(id, attr)
- valx, valy, count = tankattrv(id, attr)
ARGUMENTS
- string id: id of element
- string attr: attribute (data or result) for which value is requested
- int typelt: type of element
RESULT
- float val: value of the numerical attribute (0. if not available)
- string txt: value of the text attribute (empty string '' if
undefined or not available)
- byte btxt: value of the text attribute, as a byte (python3) or str(python2)
- int sz: length of the returned string
- valx, valy: array of float for the curve
- count: #points for the returned curve (0 if none)
REMARKS
- Numerical attributes are returned converted in the actual unit system.
- Reservoir text attributes are identical to the underlying node id
- meanattr requires version 2016 or higher of Piccolo/Ganessa dll
- branchattr, rsvattr and branchattrs are synonyms for linkattr, tankattr and linkattrs
- linkattrv, tankattrv requires version 2022 (220804) or higher of Piccolo/Ganessa dll
- tankattrs(rsv_id, "TY") returns fill mode keyword, while "TF" (FR, esp) / "FT" (UK)
returns drain mode (requires version 240416 or higher of Piccolo/Ganessa dll)
- tankattr(rsv_id, "TY") returns 2*fill + drain mode = 0 .. 3 -
(requires version 240418 or higher of Piccolo/Ganessa dll)
HISTORY
- version 1.9.0 (05/04/2018) ids and attributes are returned as unicode strings.
- version 2.3.2 (04/08/2022) added linkattrv and tankattrv
19.22. Functions_/linkbbox [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the link bounding box
SYNTAX
xmin, xmax, ymin, ymax, num = linkbbox(id)
ARGUMENTS
RESULT
- int num: link internal number (0 if not found)
- double xmin, xmax, ymin, ymax: bounding box
HISTORY
Created in 1.8.5 (171128)
19.23. Functions_/linknodes [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Return from and to nodes, in the direction of flow if given
SYNTAX
- from, to = linknodes(id_or_num [, flow=0])
ARGUMENTS
- str or int id_or_num: id or index of link element
- float flow: optional direction of flow to be considered
RESULT
- str from: from (initial) node
- str to: to (final) node
REMARK
- If flow is given and negative, topological from and to nodes are swapped.
- see extrnodes to get from and to node indexes from link index.
HISTORY
2.4.7 (2025-01-07): creation
19.24. Functions_/linkXYZV, branchXYZV [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the XYZ polyline representing a link, and eventually
an additional node attribute
SYNTAX
vec_x, vec_y, vec_z, vec_v, len = linkXYZV(id, [attr], [include_depth])
ARGUMENTS
- string id: id of element
- string attr: optional attribute for which value is requested
- bool include_depth: optional attribute, defaults to False
RESULT
- int len: number of points for the polyline
- double[] vec_x, vec_y: vector of coordinates
- float[] vec_z: vector of interpolated elevations (minus depth if include_depth= True)
- float[] vec_v: vector of interpolated attribute
HISTORY
optional argument include_depth introduced in 1.4.2 (160908)
REMARKS
- Z and V are interpolated from initial and final nodes
- if attribute is missing or not recognised vec_v is null.
- if the link has no vertice, len=2 and the function returns values
from ending nodes
- if the id does not exists the return value is (None, None, None, None, 0)
- branchXYZV is a synonym of linkXYZV.
19.25. Functions_/loadbin [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Clears (removes) all model objects and loads a binary file
SYNTAX
istat = loadbin(fname)
ARGUMENT
string fname: binary data/result file name to be loaded
RESULT
int istat: error status (0 if OK)
REMARKS
- The current model is discarded before the new one is loaded.
- If the file content is not a Piccolo binary file an error occurs.
- Binary result files also contain all data describing the model.
- The filename is quoted if necessary
19.26. Functions_/loadres [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Loads the default binary result file.
SYNTAX
istat = loadres()
RESULT
int istat: error status (0 if OK)
REMARK
The current model is discarded before the data corresponding to
the last simulation making use of the default result file is loaded.
19.27. Functions_/nbobjects [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the number of model elements in the given type
SYNTAX
nb = nbobjects(typelt)
ARGUMENT
int typelt: type of element (LINK, NODE, TANK) or NODE+TANK for supply nodes
RESULT
int nb: number of element in that type
REMARK
Call for tank supply nodes count (NODE+TANK) requires 2022-11-11 or higher version
of Piccolo/Ganessa_SIM dll.
19.28. Functions_/nbvertices [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the number of links with vertices (bends)
SYNTAX
nb = nbvertices()
RESULT
int nb: number of links with vertices
19.29. Functions_/nlinkattr, nnodeattr,
ntankattr, nlinkattrs,
nnodeattrs, ntankattrs,
nattr, nattrs [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
- nlinkattr, nnodeattr, nrsvattr, nattr: return numerical attributes
of a given element by index
- nlinkattrs, nnodeattrs, nattrs: return text attributes of a
given element by index
SYNTAX
- val = nlinkattr(num, attr)
- val = nnodeattr(num, attr)
- val = ntankattr(num, attr)
- txt = nlinkattrs(num, attr)
- txt = nnodeattrs(num, attr)
- txt = ntankattrs(num, attr)
- val = nattr[typelt](num, attr)
- btxt, sz = nattrs(typelt, num, attr)
ARGUMENTS
- int num: index of element (stating at 1)
- string id_or_num: id or index of element
- string attr: attribute (data or result) for which value is requested
- int typelt: type of element
RESULT
- float val: value of the numerical attribute (0. if not available)
- string txt: value of the text attribute (empty string '' if
undefined or not available)
- int sz: length of the returned string
- byte btxt: value of the text attribute, as a byte (python3) or str(python2)
REMARKS
- Numerical attributes are returned converted in the actual unit system.
- Tank text attributes are identical to the underlying node id
HISTORY
From version 1.9.0 (05/04/2018) ids and attributes are returned as unicode strings.
19.30. Functions_/nodeXYZ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the XYZ coordinates and depth of a node
SYNTAX
x, y, z, dz = nodeXYZ(id)
ARGUMENTS
RESULT
- double x, y: coordinates
- float z, dz: elevation and depth
REMARKS
- nodeXYZ requires version 2016 or higher of Piccolo/Ganessa dll
- if the id does not exists the return value is (None, None, None, None)
- In most cases dz is 0.0
19.31. Functions_/openg, init_ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- init([folder] [, silent=False] [, debug=False])
- openg([folder] [, silent=False] [, debug=False])
ARGUMENT
str folder: optional folder name where journal and work files will be created
silent: if set to True, most information and warning message will not show
DESCRIPTION
Initialises the ganessa simulation/command language engine.
REMARKS
- Starting with version 1.3.5, a session should be started by calling init() or init(folder).
however for compatibility with previous releases where init was called at import time,
init is automatically called at 1st call of cmd, cmdfile, execute, load, loadbin
- A session should be terminated by calling quit() or typing <Ctrl>+Z
HISTORY
- introduced in 1.3.5
- 1.9.6 (180615): fix non-ascii folder str converted to cp1252
- 2.3.8 (230419): openg introduced as an alias to init
19.32. Functions_/quit_, close_ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
ret = quit([True])
ret = quit([True])
ARGUMENT
optional bool verbose: if set to True, a message is printed.
Defaults to False.
RESULT
text ret: text string telling that he module has been unloaded.
Terminates the ganessa session and unloads the module ganessa.sim&th
REMARKS
- quit() is automatically called when quitting with <Ctrl>+Z
- close() is a synonym for quit()
- A session should be terminated by calling quit() or typing <Ctrl>+Z
- sys.exit() automatically trigers quit()
HISTORY
- 2.3.0 (220415): do not delete import at close, allowing further init
19.33. Functions_/reset_ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Clears (removes) all model objects
SYNTAX
istat = reset()
RESULT
int istat: error status (0 if OK)
19.34. Functions_/resfile, res_filename,
model_filename, result_filename,
emb_model_folder [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the name of the default binary result file; the model filename;
the actual result file name if defined.
SYNTAX
- name = resfile()
- name = res_filename()
- name = result_filename()
- name = model_filename()
- folder = emb_model_folder()
RESULT
str name: file name or "" if undefined
str folder: folder if called from embedded python or "" if not
HISTORY
- 170919 (1.8.0) Introduced resfile (default binary result file)
- 210929 (2.2.5) Added model_filename and res_filename (= resfile)
- 211112 (2.2.6) Added emb_model_folder
- 250619 (2.5.3) Added result_filename (current binary result file)
19.35. Functions_/save_, savemodel [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- istat = save(fname [, version])
- istat = savemodel(fname [, version] [, extra_data])
ARGUMENTS
- string fname: file name to save to
- string version: optional version string "x.yz" for writing compatible file format,
for text file only.
- list extra_data: list of (selection, attribute_keyword) to be saved.
Selection is a string describing a valid selection at save time; attribute_keyword
is a string name of a valid attribute for import, such as XX, YY, ZZ, K (links), Z (nodes).
Multiple attributes can be provided separated by blanks.
RESULT
int istat: error status (0 if OK)
REMARKS
- 'save' uses the same procedure as Piccolo MMI.
- 'savemodel' is pure python and produces the same hydraulic content;
exotic options and cost data are not saved.
- If filename ends with '.bin' then data is saved as binary. Otherwise data is
saved as text (.dat mode) file.
- If the useException mode is set, any error will raise GanessaError exception.
EXAMPLE
savemodel('myModel.dat', version='3.95', extra_data=[('NOEUD', 'YY ZZ')])
HISTORY
- 190617: added extra_data keyword parameter to savemodel (2.0.7)
19.36. Functions_/selectlen, select_ [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
- selectlen returns the number and type of model elements in the given selection
- select: returns the index vector, number and type of elements in the selection
SYNTAX
- nb, typelt = selectlen(sname)
- vect_idx, nb, typelt = select(sname)
ARGUMENT
string sname: name of selection
RESULT
- int nb: number of element in that selection
- int typelt: type of element of that selection
- int vect_idx[]: index vector of elements in the selection
19.37. Functions_/setbatchmode [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
oldmode = setbatchmode(mode)
ARGUMENT
int mode: batch mode to activate
RESULT
int oldmode: batch mode that was in effect
REMARK
Defaults to 1 (True)
19.38. Functions_/setlang [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
old_lang = setlang([new_lang = "None"])
ARGUMENT
str new_lang: one of 'English', 'French', 'Spanish'. Defaults to 'None'.
RESULT
str old_lang: previous language
DESCRIPTION
Modifiy the current command language to new_lang (console version and macros only).
If the language name is misspelled (or 'None'), it will be ignored withour raising an error,
so the function will just return the current language.
HISTORY
- introduced in 1.8.0 (170912)
- reviewed 2.2.7 (211124) : accepts new_lang with at least 1 letter
19.39. Functions_/setlinkattr, setbranchattr,
setnodeattr [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
SYNTAX
- istat = setlinkattr(id, attr, val)
- istat = setnodeattr(id, attr, val)
- istat = setbranchattr(id, attr, val)
ARGUMENTS
- string id: id of element
- string attr: attribute (data or result) to be set to val
- float val: new value for attr
RESULT
int istat: error status:
- 0 if OK
- 1 if the attribute is not defined for the type of link/node
- -1 if the attribute is not recognised
- -2 if the link/node does not exist
REMARKS
- setbranchattr requires version 2015/12 or higher of Piccolo/Ganessa dll
HISTORY
- setlinkattr is a synonym that has been introduced as 22/09/2016
- setnodeattr has been introduced on 22/06/2020 (2.1.3)
19.40. Functions_/shearstr [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
Returns the shear stress associated with a velocity for the given pipe
SYNTAX
val, grad = shearstr(id, v)
ARGUMENTS
- string id: id of element
- float v: velocity for which value is requested
RESULT
- float val: value of the shear stress
- float grad: value of ds/dv
REMARKS
- val is not defined if id is not a pipe
- requires Piccolo 2017
HISTORY
- 31.03.2017: function created (1.7.3)
19.41. Functions_/wqtracevectsize [ Fonctions ]
[ Top ] [ Functions_ ] [ Fonctions ]
PURPOSE
wqtracevectsize returns the max count of water quality concentrations allowed,
including chlorine (C1).
SYNTAX
n = wqtracevectsize()
RESULT
REMARK
One may expect a return value of either 9 (C1 .. C9)
or 45 (C1 .. C9 + $0 .. $9 + $A .. $Z).
HISTORY
introduced 2.0.0 (180820)
20. ganessa.sim&th/Iterators [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
Iterators available to ganessa.sim and ganessa.th
20.1. Iterators/DemandCodes [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for code, demand, nodecount in DemandCodes():
RESULT
Returns each demand code and node count in turn:
- string code: demand code
- float demand: total demand value for the code
- int count: node count associated with the code
REMARK
- DemandCodes requires version 2016 or higher of Piccolo/Ganessa dll
HISTORY
Added 11/09/2015
20.2. Iterators/Demands [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for code, csm in Demands(node_id):
ARGUMENT
string node_id: id of node
RESULT
Returns each demand code and nominal value for the node in turn:
- string code: demand code
- float csm: demand value for this code
REMARK
- requires version 2016 or higher of Piccolo/Ganessa dll
HISTORY
From version 1.9.0 (05/04/2018) codes are returned as unicode strings.
20.3. Iterators/Elements_ [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for id in Elements(typelt):
ARGUMENT
int typelt: type element constants LINK, NODE, TANK, TANK+NODE
RESULT
string id: id of each element of the given type in turn
HISTORY
- From version 1.9.0 (2018/04/05) ids are returned as unicode strings.
- From version 2.0.3 (2018/12/03) len compatibility with python3
- From version 2.3.5 (2022/11/11) TANK+NODE returns supply nodes
20.4. Iterators/Links_, Branches_ [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
- for id in Links():
- for id in Branches():
RESULT
string id: returns each BRANCH id in turn
REMARK
Branches and Links are equivalent.
HISTORY
From version 1.9.0 (05/04/2018) ids are returned as unicode strings.
20.5. Iterators/Nodes_ [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for id in Nodes():
RESULT
Returns each node id in turn
HISTORY
From version 1.9.0 (05/04/2018) ids are returned as unicode strings.
20.6. Iterators/Pipes [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
PURPOSE
Returns pipe IDs otionnaly with one or more attributes.
SYNTAX
for id in Pipes():
for id, *retvals in Pipes(*attrs):
ARGUMENT
optional str attrs: attributes values to be returned
RESULT
Returns the id [and attributes values if one or more "attr" given] of each pipe element in turn:
- string id: id of the next pipe element
- tuple of float or str retvals: values of the attributes for the pipe (as many as attributes in attrs)
HISTORY
- 2.4.4 (2024/07/17) created
20.7. Iterators/Selectid, Selected [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for id in Selectid(select_name):
for id, typelt in Selected(select_name [, return_type=True]):
ARGUMENT
string select_name: selection definition or selection name
bool return_type: if False, the type is not returned (default True)
RESULT
Returns the id [and type] of each element in the selection in turn:
- string id: id of the next element in the selection
- int type: element type (the same for all ids), if return_type is True
HISTORY
- 2.0.3 (2018/12/03) len compatibility with python3
- 2.1.1 (2020/03/20) add return_type optional keyword argument
- 2.2.9 (2022/02/11) convert string to ansi for Piccolo cmd language
- 2.3.0 (2022/04/20) add Selectid(sname) - same behaviour as Selected(sname, False)
- 2.3.7 (2023/03/30) empty selection returns empty iterator
- 2.4.4 (2024/07/17) added numelt field
20.8. Iterators/SupplyNodes [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for id in SupplyNodes():
RESULT
Returns each supply node id of head tanks in turn
REMARK
Tank nodes are not considered as supply nodes.
HISTORY
Created in 2.3.5 (221111)
20.9. Iterators/Table_ [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for item, objcount in Table(table, typelt=LINK):
ARGUMENTS
- string table: requested table (2 char symbol or table name)
- int typelt: optional type of element (LINK or NODE), if table is ZN or ZP.
Defaults to LINK.
RESULT
Returns each table entry and associated object count in turn:
- string item: table entry (possibly empty string)
- int objcount: node or link count associated with the code
REMARKS
- Table requires version 2015/12 or higher of Piccolo/Ganessa dll
- see TableValues for getting values associated with entries
- in order to get demand counts per zone, use "COEFFICIENT-ZONE" table name.
- empty entry may be reported as "(DEFLT)" or "(DEFAUT)"
HISTORY
- From version 1.9.0 (05/04/2018) items are returned as unicode strings.
- Modified 2023/03/27 (version 2.3.7): added demand codes and zones - requires version 2023 (230327) or higher of Piccolo/Ganessa_Sim dll
20.10. Iterators/TableValues [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
for item, objcount, vect in TableValues(table):
ARGUMENTS
string table: requested table (2 char symbol or table name)
RESULT
Returns each table entry and associated object count and values in turn:
- string item: table entry (possibly empty string for ZN)
- int objcount: link/node count associated with the entry
- float vect: vector of values for the entry.
The vector size depends on the table:
- (D) diameter (1): internal diameter
- (M) material (3): roughness, HW factor C, wave celerity
- (PA/PW) pipewall (7): WQ characteristics
- (FH/PI) hydrants (5): nominal flow, nominal pressure, height, diameter, friction coef K
- (CD) demand codes (2): coefficient and total demand
- (ZN) demand zones (2): coefficient and total demand
REMARKS
- TableValues requires version 2022/07/20 or higher of Piccolo/Ganessa dll
- empty entry may be reported as "(DEFLT)" or "(DEFAUT)"
- Table("CD") does not return indicator of pressure dependant demand for demand codes;
this indicator can be obtained with function: code_pressure(code).
HISTORY
- Created 2022/07/20 (version 2.3.1).
- Modified 2023/03/27 (version 2.3.7): added demand codes and zones - requires version 2023 (230327) or higher of Piccolo/Ganessa_Sim dll
20.11. Iterators/Tanks_, Reservoirs_ [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
SYNTAX
- for id in Tanks():
- for id in Reservoirs():
RESULT
string id: returns each reservoir id in turn
REMARK
Tanks and Reservoirs are equivalent and return both tanks and pressure references.
In order to return specifically either, use Selectid with the appropriate selection:
(FR) "RESERVOIR (VO > 0) FIN" or "RESERVOIR (VO = 0) FIN" (UK) "RESERVOIR (VO > 0) END"
HISTORY
From version 1.9.0 (05/04/2018) ids are returned as unicode strings.
20.12. Iterators/Unstable [ Iterator ]
[ Top ] [ Iterators ] [ Iterator ]
PURPOSE
Provide access to the list of elements which status cannot be determined
thus causing a simulation not converge.
SYNTAX
for item, typelt in Unstable():
ARGUMENTS
none
RESULT
Returns each Unstable element in turn:
- string item: element ID
- int typelt: element type
REMARK
- Unstable requires version 2016 (160118) or higher of Piccolo/Ganessa dll
HISTORY
- new in 1.3.2
- From version 1.9.0 (05/04/2018) items are returned as unicode strings.
21. ganessa.sim/sFunctions [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
functions available to ganessa.sim ONLY.
21.1. sFunctions/browseH, browseWQ [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Retrieves and interpolate results from a given time step or instant:
- browseH retrieves hydraulic results.
- browseWQ retrieves hydraulic
and water quality results
SYNTAX
- istat = browseH(seconds_or_instant [, wq=False])
- istat = browseWQ(time_step_or_instant)
ARGUMENTS
- float seconds: time to load (seconds)
- string instant: instant to load, in the form hh:mm:ss[.dd]
RESULT
int istat: error status (0 if OK)
REMARKS
When called with a numeric value (seconds) is rounded to the nearest second.
For hydraulic results, two set of results may be available at a given instant:
- at boundary of time steps, except beginning and end of the simulation,
results ending the previous time step and results starting the next time step.
- at internal time steps when a state transition occured (pump start/stop etc.).
In such a situation the results are those from the end of the previous interval.
Use "hresults_block(k) for k in range(tslen())" to get all results in time forward order,
including duplicate time.
21.2. sFunctions/defcalind, getcalind [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Compute and return calibration indicators
SYNTAX
- defcalind(lnk_threshold, nod_threshold, rsv_threshold)
- val, ival = getcalind(typelt, id_elt[, rank])
ARGUMENTS
- xxx_threshold : thresholds for computing indicators
- int typelt: type of element
- string id_elt: id of element
- int rank: rank of the calibration indicator
RESULT
val: percentage of values below threshold
ival: indicator rank, from 1 (best) to 4 (worse) (-1 if not defined)
REMARK
- defcalind actually compute all indicators; getcalind returns them.
- 2.3.3 (220909) optional argument rank added - return default indicator if not set;
older dlls return 0, -1 when rank > 1
- 2.5.2 (250407) fix _dll_api.dll_version() undefined with dll jan-2022
21.3. sFunctions/demand_pressure, code_pressure [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
- demand_pressure returns current demand-dependant parameters
- code_pressure returns code dependance when pressure dependant demand is active
SYNTAX
- state, law_index, exponent, p0, p1, babove, bdepth, law_name = demand_pressure()
- active = code_pressure(code)
ARGUMENTS
- str code: code to be examined
RESULT
- int state: 0 if not active / 1 active for all demand codes / -1 active for some
- int law_index: 1 .. 5 (1=EXP, 2=ELL, 3=SQRT, 4=LIN, 5=POW)
- float exponent: exponent if law is of power type (3 .. 5)
- float p0, p1: cancellation and fixed pressure thresholds
- bool babove: if true, demand / pression equation holds when P > p1
- bool bdepth: if True, node depth is taken into account (pipe pressure is used)
- str law_name: equation demnd = f(P)
(EXPONENTIELLE, ELLOPTIQUE, RACINE-CARREE, LINEAIRE, PUISSANCE)
(EXPONENTIAL, ELLPTIC, SQUARE-ROOT, LINEAR, POWER)
- bool active: True if demand associated with code is pressure dependant when pdd active
HISTORY
2025.02.27 (2.5.0): creation
21.4. sFunctions/full_solveH [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Runs the full simulation and loads the result file for browsing results
SYNTAX
istat = full_solveH([resultfile] [, silent] [, iverb] [, retry])
ARGUMENT
- string resultfile: if provided, the results will be written in the file
instead of the default 'result.bin'. If the file exists it will be superseded.
If not it will be created.
- bool silent: if set to True, simulation runs without any output.
Optional - if False or not set, leaves 'iverb' unchanged.
- integer iverb: if provided, controls the amount of output during simulation
(SIM IVERB parameter). The defaults is -1.
- bool retry: if set to True, the simulation is run again twice if it fails
because of isolated nodes. Optional - defaults to False
RESULT
int istat: error status (0 if OK)
REMARKS
- Unless explicitely disabled, results are saved to a binary file,
which defaults to the file 'result.bin' in the ganessa work directory.
- Binary result files also contain all data describing the model.
- silent=True overrides iverb setting if provided.
HISTORY
- 1.5.1: optional argument 'retry' added
- 2.0.7: improved error check (19/08/19)
- 2.2.3: retry=True retries the simulation twice, in case STOP-ON-APP is OFF (26/06/21)
21.5. sFunctions/getallminmax [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
- getallminmax returns the min, max, average and mindate, maxdate
for all objects of the given type
SYNTAX
- vec_min, vec_max, vec_avg, vec_tmin, vec_tmax = getallminmax(typelt, attr)
ARGUMENTS
- int typelt: type of element (LINK, NODE, TANK)
- string attr: attribute (result) for which value is requested
RESULT
- float[] vec_min, vec_max, vec_avg: min, max and avg values for all elements
- float[] vec_tmin, vec_tmax: vector of instants where the min, max value is reached
21.6. sFunctions/hresults_block, hresults_block_xtra [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Retrieves simulation results by block, at exact intermediate time steps,
including duplicate dates (ending of previous condition, and stating new)
SYNTAX
- istat = hresults_block(time_step_index, get_incidents)
- step, date = hresults_block_xtra()
ARGUMENTS
- int time_step_index: time step index to load, within [0, tslen()[
- bool get_incidents: if True, incidents are collected from ending block
RESULT
- int istat: error status (0 if OK, >0 in case of reading error, -1 other error)
- int step: user time step the block belongs to (<0 if initial or intermediate
simulation step; >0 if user time step right boundary = end of interval)
- float date: simulation date
EXAMPLE
for k in range(tslen()):
hresults_block(k)
step, date = hresults_block_xtra()
do something else
REMARKS
- iterating over range(tslen()) allow to browse results by increasing order, including
end of previous conditions and start of new conditions happening at the same time.
- hresults_block_xtra returns information related to the previous hresults_block call.
HISTORY
- 2025-02-25 (2.5.0) creation
21.7. sFunctions/hstepcount, tslen,
mslen, tsval,
tsvals, all_ts,
msval, tsvalbymts,
tsinterv, wqtslen,
refdate [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
- hstepcount: returns the number of user time steps
- tslen, mslen: return number of elements in the time serie
- tsval, msval: return the time series of results and measurements
- tsvals: returns a list of time series of results
- all_ts: returns all time series of a type as a matrix
- tsvalbymts: return the time series of results at measurement time steps
for a given element type, id and attribute
- tsinterv: number and boundaries of user time steps
- refdate: return date corresponding to the beginning of simulation
SYNTAX
- hsc = hstepcount()
- len = tslen()
- len = mslen(typelt, id, attr)
- vec_tim, vec_val, len = tsval(typelt, id, attr, [interval])
- vec_tim, vec_mes, len = msval(typelt, id, attr, [interval])
- vec_tim, vec_val, len = tsvalbymts(typelt, id, attr)
- vec_tim, len, [(vec_val, len), ...] = tsvals(typelt, [id, ...], attr, [interval])
- vec_tim, len, [(id, vec_val), ...] = tsvals(typelt, [id, ...], attr, [interval], valid_only=True)
- matrix_val, vec_tim, vec_tim2 = all_ts(typelt, attr)
- tmin, tmax, len = tsinterv()
- len, tmax = wqtslen(typelt)
- sdate = refdate()
ARGUMENTS
- int typelt: type of element
- string id: id of element
- string attr: attribute (data or result) for which value is requested
- float interval (optional): if present, requests the time serie
at given fixed interval in seconds
RESULT
- int hsc: number of user time steps
- int len: number of values for the time serie
- float32[] vec_tim: vector of instants in seconds
- float32[] vec_val: vector of simulated results at the instants vec_tim
- float32[] vec_mes: vector of measurements at the instants vec_tim
- float64[] vec_tim2: vector of instants in seconds with distinct values:
beginning of time step (identical to end of previous) are incremented by 0.2 s
- float32[item_index, time_index] matrix_val: matrix of simulated results
- float tmin and tmax: first (vec_tim[0]) and last (vec_tim[-1])
instants available in the result time series
- string sdate: date time at beginning of the simulation (iso format)
REMARKS
- The time vector is identical for simulation results of all elements of all types,
and can be much larger than the number of (user) time steps (hstepcount() <= tslen()).
- two consecutive instants in the time vector for simulation results may
be identical at time step boundaries, change status instants etc. tsvals and all_ts
use and return a modified time vector where second identical value is shifted by 0.2 s.
- Each element may have a different measurement time vector form the others
- Measurements time series may have different begin and end dates from results
- Add 'sdate' in order to get absolute date time
- hstepcount requires version 2016 or higher of Piccolo/Ganessa dll
HISTORY
- 12/12/2016 (1.5.1): bug fix when no simulation result available
- 15/03/2020 (2.1.1): added wqtslen; fix tsval for WQ ts
- 05/02/2023 (2.3.6): added tsvals for efficiently returning multiple ts
- 02/05/2023 (2.3.8): revert return values of tsvals (id, ts) allowing to build a dict
- 24/02/2025 (2.5.0): fix tsvals by shifting second same time value by 0.2 s;
added all_ts (better results for both with dll version >= 20250225)
21.8. sFunctions/inv_summary, inv_varcount,
inv_variable [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
SYNTAX
- iter, iter100, fobjmin, fobj100, fobj0, flambda = inv_summary()
- vcount = inv_varcount(stype)
- num, val, delta = inv_variable(stype, idx)
ARGUMENTS
- str stype: type of variable (ZN, PR, K, CS)
- int idx: index of variable
RESULT
- int iter: number of iterations
- int iter100: number of iterations required to get 1.01 * min
- float fobjmin: minimum value of misfit function
- float fobj100: misfit function at iteration iter100
- float fobj0: misfit function before fitting
- float flambda: Levenberg-Marquardt multiplier
- int vcount: number of variables of the type
- int num: element (link or node or tank) index, starting at 1
- float val: value of variable of type stype and rank idx
- float delta: variation of variable (final - initial value)
REMARK
- inv_summary requires version 2016 (160309) or higher of Piccolo/Ganessa dll
- inv_varcount and inv_variable require version 2022 (220924) or higher
HISTORY
- new in 1.3.4
- 2.3.3: added inv_varcount and inv_variable
21.9. sFunctions/msmooth [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Defines the smoothing time width for time series of measurements
SYNTAX
msmooth(twidth)
ARGUMENTS
twidth: characteristic time window for smoothing, in seconds
REMARKS
- The smoothing algorithm is a convolution with exp(-(t/twidth)^2).
- Best results are expected when twidth is in the order of magnitude
or larger than the sampling interval.
- call msmooth(0.0) in order to cancel smoothing.
21.10. sFunctions/setWQresultfile [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Defines the binary result file(s) for WQ simulation.
SYNTAX
setWQresultfile([fnode] , [flink])
ARGUMENTS
- str fnode: name of the node WQ result file
- str flink: name of the link WQ result file (optional)
REMARK
- if fnode is omitted, either use None or flink=filename
- this command can be used either before running the simulation, for writing
the file(s), or afterwards, in order to choose which result file(s) to browse.
21.11. sFunctions/solveH [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
Runs the simulation at a given instant
SYNTAX
istat = solveH(time [, retry])
ARGUMENT
- int or str time: instant to run the simulation - default to 0.
if int: time in seconds; if str: time in the format hh:mm[:ss]
- bool silent: if set to True, simulation runs without any output.
Optional - if False or not set, leaves 'iverb' unchanged.
- integer iverb: if provided, controls the amount of output during simulation
(SIM IVERB parameter). If not set, leaves 'iverb' unchanged.
- bool retry: if set to True, the simulation is run again if it fails
because of isolated nodes. Optional - defaults to False
RESULT
int istat: error status (0 if OK)
HISTORY
- added 2017.05.15 - version 1.7.5
- changed 2019.04.23 - version 2.0.6 - added a third retry
- changed 2019.08.19 - version 2.0.7 - improved error check
21.12. sFunctions/stat_quantiles, stat_duration [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
stat_quantiles and stat_duration returns stat info associated with result TS
of a given attribute for all elements in a selection.
raw_stat_quantiles and raw_stat_duration are pass_thru versions where
the selection is provided as its type, buffer and length
SYNTAX
- quantiles = stat_quantiles(sel, attr, qtl)
- duration = stat_duration(sel, attr, sop, threshold)
- quantiles = raw_stat_quantiles(typelt, attr, qtl, bufsel, nb)
- duration = raw_stat_duration(typelt, attr, sop, threshold, bufsel, nb)
ARGUMENTS
- string sel: selection of elements for which stats are expected
- string attr: attribute over which the stat is computed
- float iterable qtl: quantiles to be computed (0 <= qtl[i] <= 1)
- string sop: comparison operator '<' or '>'
- float threshold: comparison threshold (expressed in attribute unit)
- int typelt: selection object type
- int nb: selection count
- int[] bufsel: selection vector of indices
RESULT
- float[:,:] quantiles: 2-dim array of quantiles - shape (#sel, #qtl).
quantiles[i] is the array of quantiles for the element in position i;
quantiles[:, k] is the array of quantile qtl[k] for all elements
- float[:] duration: array of cumulated duration (att sop threshold) - shape (#sel, ).
The functions return an empty list if the selection or qtl is empty .
EXAMPLE
- cd = stat_duration('BRANCH (d > 500) end', 'V', '>', 0.7)
- qtl = stat_quantiles('BRANCH (d > 500) end', 'V', [0.5, 0.95, 1.0])
will return median, 95% quantile and maximum for velocity.
REMARK
Allowed attributes are:
- links: flow (Q), velocity (V), head loss (PC / HL), gradient (GR)
- nodes: Head (HH / CH), pressure (P) and pipe pressure (PP)
- tanks: level (NC / CL), height (H), volume (CV / VC), volume percentage (V%),
flow (Q), filling flow (IQ / QR), draught flow (OQ / QV),
- all: water quality attributes T, C0 ... C9.
See also: getallminmax, getMinMax, Dynamic_Stats
HISTORY
- new in 1.5.0 (161124) - should be compatible with 2016b kernel.
- 1.8.0 (170908): added raw_stat_quantiles and raw_stat_duration
21.13. sFunctions/tsdemand, tsdevice,
tsdemandlen, tsdevicelen [ Fonctions ]
[ Top ] [ sFunctions ] [ Fonctions ]
PURPOSE
- tsdemandlen: returns the number of values in the profile (demand code)
- tsdevicelen: returns the number of values in the device state TS
- tsdemand: return the profile time series (demand type)
- tsdevice: return the device state time series(boundary conditions)
SYNTAX
- tslen = tsdemandlen(code [, zone])
- vec_tim, vec_val, len, mode = tsdemand(code, [,zone])
- tslen = tsdevicelen(sid[, attr])
- vec_tim, vec_val, len, mode = tsdevice(sid [, attr] [, fixed_interval])
ARGUMENTS
- string code: demand type of element
- string zone: area of element
- string sid: device element ID
- string attr: pump attribute (speed or number of units)
or "N" or "NV" or "H" for reservoirs or ""
- float fixed_interval (optional): if present and > 0, return values at the give time step
RESULT
- int tslen: number of values for the time serie (0 if none)
- float[] vec_tim: vector of instants in seconds
- float[] vec_val: vector of demand coefficients (not percentages) or settings
(for pumps: 0= off, 1 or higher= open/active)
- int mode: type of demand profile (<0 as time series, >0 based on time steps)
REMARKS
- These functions require version 2016 or higher of Piccolo/Ganessa dll
- Demand zones require version 2020b or higher
- when the demand code or equipment does not exist or has no forcing TS associated,
the value (None, None, 0, 0) is returned.
- The demand coefficient for the demand type 'code' can be retrieved
as float(getvar('coefficient:' + code))
- tsdevice("", "T") retrives the user time steps boundaries.
- A pump is shut off when the number of units running is 0, even if rotation speed is > 0.
HISTORY
- 25.01.2017: added 'fixed_interval' parameter to tsdevide; changed return value to float
- 22.09.2020: added the query of demand profile by zone
- 08.08.2022: added the query of pressure reference TS (using N or NV or H)
22. ganessa.sim/sIterators [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
Iterators available to ganessa.sim ONLY
22.1. sIterators/ControlEntities [ Iterator ]
[ Top ] [ sIterators ] [ Iterator ]
PURPOSE
Provide access to the control entities
SYNTAX
for name, item_names, descr_combs, pump_count, combis in ControlEntities():
ARGUMENTS
none
RESULT
Returns each control entity information in turn:
- str name: name of the control entity (can be used for dynamic data or controls)
- List[str] item_names: names of the links forming the control entity. Pumps are at the end.
- List[str] descr_combs: optional description of the combinations
- int pump_count: number of pumps in the control entity
- ndarray combis[comb_count, fitting_count + pump_count]: fitting settings per combination
REMARKS
- ControlEntities requires version 2022 (220824) or higher of Piccolo/Ganessa_Sim dll
- #items in the control entity is len(item_names); #combinations is len(descr_combs)
- Pumps have 2 settings: number of pumps running and speed, all other have one.
- The setting for any fitting and combination is combis[cmb_idx, fitting_idx]. For pumps this
returns the status of the pump; the speed is at combis[cmb_idx, fitting_count + pump_idx]
- Pump speed is returned as -1 for fixed speed pumps
EXAMPLE
For a control entity comprising 1 valve and 2 pumps and 4 combinations, the iterator will return
('ENTITY_NAME', ['VALVE_NAME', 'PUMP1', 'PUMP2'], ['Descr1', 'Descr2', 'Descr3', 'Descr4'], 2, combis)
where shape(combis) is (4, 5):
- combis(x, 0): status (0 / 1) for the valve
- combis(x, 1): status (0 / 1) for pump#1
- combis(x, 2): status (0 / 1) for pump#2
- combis(x, 3): speed for pump#1
- combis(x, 4): speed for pump#2
HISTORY
- 2.3.2 (220824) creation
- 2.3.11 (231114) added __len__
22.2. sIterators/Controls_ [ Iterator ]
[ Top ] [ sIterators ] [ Iterator ]
PURPOSE
Provide access to the controls on pumps and manual valves
SYNTAX
for control_id, control_data in Controls([which]):
ARGUMENTS
str which: "GU" or "GROUPE-CONTROLE" for getting control entities;
leave blank for valves and pumps
RESULT
Returns each control information in turn - control_id is a ControlId NamedTuple:
- int mtype: type of master (controller element) as one of LINK, NODE or TANK.
- str master: master ID
- str slave: controlled link ID (pump or manual valve or control entity)
- int priority: priority of the control
- int initial_state: initial slave state when controller position is between start and stop threshold
control_data = ControlData NamedTuple:
- str period: name of the time period on which the control operates; possibly ""
- bool active: True if the control is active for the given period
- array start: array of start thresholds
- array stop: array of stop thresholds
- int nbval: number of threshold values
- float delay: delay after the condition is met for changing
REMARKS
- Controls requires version 2022 (220821) or higher of Piccolo/Ganessa_Sim dll
- nbval is 1 for valves and pumps with a single unit; otherwise it is equal to the number of pump units.
With control entities, it is the number of combination minus one.
- multiple controls can be set for a given ControlId (pair of master and slave), on several periods
(time intervals); null period is the default value
HISTORY
22.3. sIterators/Dynamic_Stats [ Iterator ]
[ Top ] [ sIterators ] [ Iterator ]
PURPOSE
Iterator which returns stat info associated with result TS
of a given attribute for all elements in a selection in turn.
SYNTAX
for id, retval in Dynamic_Stats(sel, attr [, quantile= qtl] [, duration= (sop, threshold)]):
ARGUMENT
- string sel: selection
- string attr: attribute
- float iterable qtl: quantiles to be computed (0 <= qtl[i] <= 1)
- string sop: comparison operator '<' or '>'
- float threshold: comparison threshold (expressed in attribute unit)
RESULT
Returns the id and type of each element in the selection in turn:
- string id: id of the next element in the selection
- retval: result of the requested stat.
The return value depends on the input parameters:
- if duration= (sop, threshold) is present, returns the cumulated duration for which attribute (sop) threshold.
- if not, if quantile= qtl is present, returns a numpy array of the quantiles for the element id.
- without duration and quantile keywords, the return value is [minval, maxval, avg] over the result TS.
REMARK
See also getallminmax, stat_quantiles, stat_duration, getMinMax
HISTORY
- new in 1.5.0 (161124) - should be compatible with 2016b kernel.
- 181220: added __len__
22.4. sIterators/getMinMax [ Iterator ]
[ Top ] [ sIterators ] [ Iterator ]
PURPOSE
Returns the id, min, max, avg value reached by the attribute for each object
of the given type or selection in turn
SYNTAX
for id, vmin, vmax, vavg in getMinMax(typelt or selection, sattr):
ARGUMENT
- int typelt: type element constants LINK, NODE, TANK
- string selection: name of a selection
- string attr: attribute (result) for which value is requested
RESULT
id, vmin, vmax, vavg: str element id, minimum, maximum and average values
for the attribute over the simulation
HISTORY
22.5. sIterators/IPSVariable [ Iterator ]
[ Top ] [ sIterators ] [ Iterator ]
PURPOSE
Provide access to the fitted values after IPS
SYNTAX
for sid, val, delta in IPSVariable(stype):
str stype: IPS variable category (ZN, PR, K, CS)
RESULTARGUMENTS
Returns each variable identifier and value:
- str sid: node (ZN, CS) or link (K) or tank (PR) ID
- float val: value
- float delta: variation of variable after IPS
REMARK
- IPSVariable requires version 2022 (220924) or higher of Piccolo/Ganessa_Sim dll
HISTORY
22.6. sIterators/WQSources [ Iterator ]
[ Top ] [ sIterators ] [ Iterator ]
PURPOSE
Provide access to the sequence of source items
SYNTAX
for node, code, attr, tvec, cvec, nvec in WQSources(node=None):
ARGUMENTS
string node: specific node to look for, or '' for all nodes.
RESULT
Returns each source boundary condition in turn:
- string node: node ID
- string code: code associated to the source (or '' if forcing)
- string attr: WQ attribute (T, C0 ... C9, $0 ... $9, $A ...$ Z)
- float tvec[], cvec[]: time and quantity vector (time serie)
- int nvec : TS size
If node is given (non blank string):
- if it exists, data will be returned for this node only
- if the node does not exists, the return sequence is empty
If the node is not given, all WQ data will be returned
REMARK
- WQSources requires version 2020 (200306) or higher of Piccolo/Ganessa_Sim dll
HISTORY
23. ganessa.sort/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.sort provides sorting functions and Classes used by the Ganessa tools.
24. ganessa.sort/sClasses [ Introduction ]
[ Top ] [ Introduction ]
24.1. sClasses/HeapSort, HeapSortFunc,
HeapSortRank [ Objects ]
[ Top ] [ sClasses ] [ Objects ]
SYNTAX
hs = HeapSortRank([index_key]): creates the heap structure.
"optional" arg rank must be provided to the methods.
hs = HeapSortFunc(rank_func [, index_key]): creates the heap structure.
"optional" arg rank is computed as rank_func(item), it must not be provided to the methods.
hs = HeapSort([key=None] [, index_key]): function that returns HeapSortFunc(key, index_key)
if key is present, otherwise returns HeapSortRank(index_key).
Instances provide the following methods:
- rank = hs.remove(item): removes item - raise KeyError if not found
- item, rank = hs.pop(): removes and returns the item of lowest rank.
- hs.push(item [, rank]): inserts or replace item with given rank.
If the item is already present, its rank and position are updated.
- hs.modify(item, offset): modify item rank by offset (HeapSortRank only).
- hs.update(item [, rank]): same as push but does nothing if rank unchanged.
- hs.update_if_lower(item [, rank]): same as push but does nothing if new rank
is higher or equal than the actual rank.
- hs.update_if_higher(item [, rank]): same as push but does nothing if new rank
is lower or equal than the actual rank.
- count = len(hs): returns the item count in the heap structure.
ARGUMENTS
- optional function index_key: function extracting from item the key to be used for entries,
as index_key(item).
- function rank_func: function computing rank of item being inserted (HeapSortFunc),
as rank_func(item).
- function key: used to select between HeapSortFunc(key, index_key) or HeapSortRank(index_key).
- item: item to be pushed / popped.
- number rank: defines the ordering of items. Mandatory with HeapSortRank methods.
Forbidden with HeapSortFunc methods.
RESULT
- hs: HeapSortxxxx class member
- number rank: rank of removed element
- int count: remaining item count in the heap structure.
REMARKS
- 'index_key' allow to use composite items such as tuple where e.g. the first element
is meaningful for the search, other elements being additional attributes to be kept together.
In such a case, index_key=itemgetter(0) tells that first element is the true key.
- HeapSortFunc can be used when rank is a subelement of composite items. In case of tuples
(item_id, item_rank, ...) the expected instanciation is HeapSortFunc(itemgetter(1), itemgetter(0)).
- HeapSort function is provided for compatibility with previous version of the HeapSort class.
HISTORY
- Introduced in 1.8.2 (171031)
- 2.3.4 (221110): added rank and modify methods; remove returns rank
- 2.5.1 (250306): added index_key optional argument; implement key=func option
as a subclass HeapSortFunc of HeapSortRank in order to improve performance; define
HeapSort as a function, for compatibility.
25. ganessa.th/tFunctions [ Introduction ]
[ Top ] [ Introduction ]
DESCRIPTION
functions available to ganessa.th ONLY
25.1. tFunctions/solveTH [ Fonctions ]
[ Top ] [ tFunctions ] [ Fonctions ]
PURPOSE
Runs the thermo-hydraulic simulation
SYNTAX
istat = solveTH([silent=False [, iverb=-1 [, retry=True]]])
ARGUMENTS
- bool silent: if set to True, simulation runs without any output.
Optional - if False or not set, leaves 'iverb' unchanged.
- integer iverb: if provided, controls the amount of output during simulation
(SIM IVERB parameter). If not set, leaves 'iverb' unchanged.
- bool retry: if set to True, the simulation is run again if it fails
because of isolated nodes. Optional - defaults to False
RESULT
int istat: error status (0 if OK)
HISTORY
- added 2017.05.15 - version 1.7.5
- changed 2019.08.19 - version 2.0.7 - improved error check
25.2. tFunctions/symmetric_node [ Fonctions ]
[ Top ] [ tFunctions ] [ Fonctions ]
SYNTAX
ids = symmetric_node(sid)
ARGUMENTS
string sid: node ID for which the symmetric (counterpart node on
the other circuit) is looked for
RESULT
- string sid: id of the counterpart node. '' if not found.
REMARKS
- always returns '' with Piccolo/Ganessa_SIM
- the counterpart can be found only if the hot and cold circuits are almost symmetric
- symmetric_node requires version 2016B (160511) or higher of Picalor/Ganessa TH dll
HISTORY
new in 1.3.6
26. ganessa.util/About [ Introduction ]
[ Top ] [ Introduction ]
PURPOSE
The module ganessa.util provides useful functions used by the Ganessa tools.
REMARK
Some of the functions must be preceded by 'import ganessa.sim'
27. ganessa.util/functions [ Introduction ]
[ Top ] [ Introduction ]
27.1. functions/call_until_false [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
PURPOSE
Calls a function with args until return is false
SYNTAX
res = call_until_false(func, args [, maxcount=99])
ARGUMENT
- callable func: function to be called with args
- args: *args to func
- int maxcount: optional max count, defaults to 99 (use -1 for infinite)
RESULT
- tuple of successive return values
REMARK
Use of this function is meaningful with side-effect functions.
The function is repeatedly called with the same argument list; the result
is not just duplicated.
HISTORY
- introduced 2.0.3 (1801011)
- 2.4.4 (240716): fixed doc (default maxcount is 99)
27.2. functions/cmp_version [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
PURPOSE
Compare two tuples and/or version numbers "x[.y[.z]]"
SYNTAX
res = cmp_version(vers1, vers2)
ARGUMENT
tuple or str vers1, vers2: either tuples or list of integers or version string
RESULT
-1 if vers1 < vers2; 0 if vers1 == vers2; 1 if vers1 > vers2
REMARK
str args are converted to tuple of integers before comparison so mixed comparison is allowed
EXAMPLE
cmp_version("3.9", "3.10") (equivalent to cmp_version("3.9", (3, 10))) returns -1
27.3. functions/decode_time, decode_date,
as_seconds [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- fval = decode_time(input_tstring [, factor])
- dval = decode_date(input_dstring)
- fval = as_seconds(arg [, factor])
ARGUMENT
- string input_tstr: duration in the form of float or hh:mm:ss or XML duration string.
- optional float factor: multiplier (default to 1)
- string input_dstr: date in a versatile format YYYY/MM/DD hh:mm:ss or DD/MM/YYYY hh:mm:ss
or the iso format YYYY-MM-DDThh:mm:ss where 'T' can be replaced with a blank ' '.
- arg: number or timedelta or input_tstring as above.
RESULT
- float fval: number of seconds. The result is multiplied by factor only if input_string is a float.
- date dval: date. The exception 'ValueError' is raised if the date cannot be read.
HISTORY
- 2023-06-05 (2.3.8) added utcoffset handling - returns local time.
- 2023-06-19 (2.3.8) added as_seconds.
27.4. functions/dist_to_poly, dist_p_seg,
dist, split_poly_at [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
PURPOSE
Computes the distance of a point (xn, yn) to a polyline or a segment
SYNTAX
- d, s1, s2 = dist_to_poly(xn, yn, nbpoly, xpoly, ypoly)
- d, s1, s2 = dist_to_poly(xn, yn, points)
- d, s, slength = dist_p_seg(xn, yn, x1, y1, x2, y2)
- d = dist(x1, y1, x2, y2)
- k, xsplit, ysplit, totlen = split_poly_at(xpoly, ypoly, s, nbpoly)
- sh, dsh = shearstress(diamm, crug, v)
ARGUMENTS
- double xn, yn: point coordinates
- int nbpoly: number of points
- double[] xpoly, ypoly: vertices of the polyline
(number of vertices in the polyline >= 2; 2 for a plain segment)
- sequence points: sequence of pairs of float or double
- double x1, y1, x2, y2: coordinates of a segment extremities
- double s: curvilinear position to split at
- float diamm: pipe diameter in mm
- float crug: pipe roughness in mm or C factor
- float v: velocity in M/s - should be nonzero
RESULT
- double d: distance of point to the polyline or segment
- double s1, s2: curvilinear position of the point projection on the polyline, from each extremity
- double s: curvilinear position of the point projection on the segment, starting from (x1, y1)
- double slength: length of the segment (x1, y1), (x2, y2)
- int k: rank of splitted segment (0: before or at start; nb: after or at end)
- double xsplit, ysplit: coordinates of the scurvilinear position s on the plyline
- double totlen: total length of the polyline before splitting
- float sh: shear stress
- float dsh: derivative of shear stress with respect to velocity
REMARKS
- d= 0 means that the point is on the polyline.
- s1>0 and s2>0 means that the point projection is at least on one of the segments.
HISTORY
- 1.7.1 (170223) introduced compiled versions of these 3 functions;
pure python versions names are prefixed with '_'
- 2.1.6 (210126) added split_poly_at
- 2.1.7 (210324) fix split_poly_at 'ValueError: not enough values to unpack (expected 3, got 2)'
- 2.3.8 (230623) added shearstress
27.5. functions/envoi_msg [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
status = envoi_msg(exp, dst, objet, texte [, serveur=smtp.safege.net] [, pwd=None])
ARGUMENT
- string exp: adresse expediteur du message
- string dst: adresse destinataire (ou [dst1, dst2 ... ])
- string objet: objet
- string texte: texte du message
- string serveur (optionnel): serveur d'envoi
RESULT
- bool status: True si le message est parti sans erreur
HISTORY
- 171201: added pwd kwarg
- 220810: added sub_module info if any
- 230419: added ganessa version
- 240724: changed exp lookup to mail / UserPrincipalName / username
- 250131: added script full path
27.6. functions/FichInfo, banner [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- fi = FichInfo(filename, version="", as_title=True)
- txt = fi.banner()
ARGUMENT
- str filename: input file name - expects the name of the caller '__file__'
- optional str version: version of the tool
- optional bool: as_title: if True, the banner will be used as title for command window
- .sub_module: optional FichInfo to include in the banner
RESULT
a class member containing the following fields and method:
- nom: basename of the input filename without extension
- vers: date of last modification of filename in the form 'YYMMDD'
- pyvers: current version of python 'x.y.z'
- banner() returns a string containing all the elements above
HISTORY
- 180814 (1.9.8): appended '32/64 bits' to banner info
- 220810 (2.3.2): added sub_module inclusion for banner()
- 230123 (2.3.6): added as_title option
- 230330 (2.3.7): add .name as a property: synonym to .nom
- 240418 (2.4.1): wkdir defined in profile if source folder not writeable
- 240715 (2.4.4): write access check uses a tempfile for parallel runs
27.7. functions/formatting: strf2, strf3,
strf2loc, strf3loc,
stri, hhmmss,
hhmmssd, strd [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- txt = strf2(fval)
- txt = strf3(fval)
- txt = stri(ival)
- hms = hhmmss(val [, rounded=False] [, days=False])
- hmsd = hhmmssd(val [, digits=1])
- dmy = strd(dval)
ARGUMENT
- int or float val: number of seconds
- int ival: integer input value
- float fval: float input value
- date dval: datetime input value
- bool rounded: round value to the nearest second value
- bool or str days: if True and hours >= 24, then writes d<days>hh:mm:ss
- int digits: number of mantissa digits
RESULT
- string txt: string representation of the input value
- string hms: representation of time in the form 'hh:mm:ss' or 'd<sep>hh:mm:ss'
when days=True and fval >= 86400; <sep> is days if days is a str, otherwise ' '.
- string hmsd: representation of time in the form 'hh:mm:ss.d'
- string dmy: date time in the isoformat except TZ: YYYY-MM-DDTHH:MM:SS
REMARK
- strf2, strf3: values larger that 1 are written with at most 2 or 3 digits after decimal dot.
- strf2loc, strf3loc use the local decimal dot (. or ,).
- strd: the value 'val' is rounded to seconds id rounded= True
HISTORY
- 23/11/2020 (2.1.6): added 'days' keyword to hhmmss.
- 23/02/2025 (2.5.0): added hhmmssd
27.8. functions/get_proxy [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
proxy = get_proxy([folder=None] [, default=""])
ARGUMENTS
- optional string folder: folder to search for proxy .json file
- optional string default: default value for proxy
RESULT
string proxy: value of the proxy, False if not found
REMARKS
The .json configuration files are searched for either a "proxy" key
or the first element of the first list. Files names are:
'https_proxy', 'Mise_a_jour_packages', 'proxy'.
HISTORY
- 1.8.8 (171212) created get_proxy
- 2.1.0 (200214) fix urllib3 requiring proxy scheme (http[s]://)
- 2.1.5 (210927) fix kwarg name default in doc; fix return value
27.9. functions/get_python_exe [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
name = get_python_exe()
RESULT
str name: path/name to the python executable in use, possibly without extension
HISTORY
2.0.7 (190821) created
27.10. functions/gfloat, gint,
gbool [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- fval = gfloat(input_string)
- ival = gint(input_string)
- bval = gbool(input_string)
ARGUMENT
string input_str: string value to be converted to a float or int or bool.
The decimal separator can either be '.' or ','.
RESULT
- float fval or int ival: numerical value after conversion
- bool bval: semantic boolean value.
Unlike bool builtin, gbool('False'), gbool('n') and gbool('0') return False
HISTORY
- 171127: gbool added
- 221213: gbool: added "ko" and "x" as False
27.11. functions/IniFile, get_,
set_, getall,
setall, save_ [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- mycfg = IniFile(filename, folder=None)
- txt = mycfg.get(group, key, default)
- obj = mycfg.getall(group)
- mycfg.set(group, key, value)
- mycfg.setall(group, obj)
- value = mycfg.remove(group, key)
- mycfg.save(folder=None)
ARGUMENT
- string filename: input file name - expects the name of the caller '__file__'
in order to get the same file path and name with extension .json
- string folder: alternate folder to load from / save to
- string group: group of keys
- string key, value: value of key to be stored/retrieved
- object obj: object to be stored; may be a dict of lists.
RESULT
- mycfg = IniFile(filename): loads the init file and returns the groups of keys
- val = mycfg.get(group, key, val) allows to update val if the value of group/key
is defined.
- object obj: object retrieved.
- set() allows to set key with value
- save() saves the files back. If folder was given and exists, then the file
is saved into that folder instead of the filename folder.
- remove() returns the mapping or None if not found
HISTORY
- Default format changed from .xml to .json in aug 2017;
previous settings will be converted.
- getall and setall added in march 2018.
- 180705 (1.9.7) IniFile handles non-ascii filenames
- 181218 (2.0.4) get returns unicode strings
- 200506 (2.1.2) remove method
- 210426 (2.1.9) remove trailing '-<maxver><minver>' from the basename
- 211012 (2.2.5) add folder kwarg
- 240418 (2.4.1) use IniFile from profile if it exists
- 240715 (2.4.4) write access check uses a tempfile for parallel runs
27.12. functions/IniFile1L, get_,
set_, remove_,
save_ [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- mycfg = IniFile1L(filename)
- txt = mycfg.get(key, default)
- mycfg.set(key, value)
- value = mycfg.remove(key)
- mycfg.save()
ARGUMENT
- string filename: input file name - expects the name of the caller '__file__'
in order to get the same file path and name with extension .json
- string key, value: value of key to be stored/retrieved
RESULT
- mycfg = IniFile1L(filename): loads the init file and returns the keys
- val = mycfg.get(key, val) allows to update val if the value of key is defined.
- set() allows to set key with value
- save() saves the files back
- remove() returns the mapping or None if not found
HISTORY
- 210426 (2.1.9) remove trailing '-<maxver><minver>' from the basename
- 210708 (2.2.4) getall and setall
27.13. functions/is_folder_writeable [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
stat = is_folder_writeable(folder)
ARGUMENT
- string folder: folder to be checked
RESULT
REMARKS
- created 2.4.8 (2025-02-11) with the appropriate exceptions !
- fixed 2.5.0 (2025-02-20) for simultaneous calls
27.14. functions/is_text, myascii,
unistr, str2uni,
utf2uni, con2uni [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- bret = is_text(input_str)
- atxt = myascii(input_str)
- utxt = unistr(input_str)
- utxt = str2uni(input_str)
- utxt = utf2uni(input_str)
- utxt = con2uni(input_str)
ARGUMENT
input_str: value to be converted. Can be of any type:
non text input are first converted to unicode.
RESULT
- bool bret: indicator telling if the object item is a string (unicode or byte).
Equivalent to isinstance(input_str, basestring) in python 2.7
- unicode or string atxt: string of same type as input_str where non-ascii charcacters
have been replaced with the best match (i.e. 'é' is replaced with 'e').
- unicode utxt: unicode string decoded from input_str (multiple codecs tried in turn);
unistr tries 'cp1252', 'utf-8', 'cp850', 'iso-8859-1';
str2uni tries 'utf-8', 'cp1252', 'cp850', 'iso-8859-1';
tostr acts as unistr in python2 and as str2uni in python3;
con2uni tries cp850 then tostr.
HISTORY
- in version 1.9.0, those functions are defined separately for python2 and python3.
- since version 1.9.1, the definitions have been merged.
- since version 2.1.5 (2020/08/24), 'ascii' replaced with 'myascii'
- since version 2.2.0 (2021/05/27) myascii tries several codecs
27.15. functions/is_wq [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
bret = is_wq(attr, lang=None)
ARGUMENT
unicode or byte string attr: attribute
str lang: kernel lang (default None)
RESULT
bool bret: true if att in T, C0 .. C9, $0 .. $9, $A .. $Z
HISTORY
- introduced 14.03.2020 - 2.1.1
- added water hardness (TH / HD / DU 24.11.2021 - 2.2.7)
27.16. functions/lec_csv, csv_with_tabs [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
header, body = lec_csv(filename [, sep=','] [, skip_before=0] [, skip_after=0] [, as_tuple=False] [, trim=True])
content = csv_with_tabs(filename [, sep=','] [, skip_before=-1] [, skip_after=0] [, as_tuple=False] [, trim=True])
ARGUMENT
- string filename: input file name
- optional string sep: optional column separator. Default ','.
- optional int skip_before: number of lines to be skipped before reading header.
- optional int skip_after: number of lines to be skipped after reading header.
- optional bool as_tuple: bool indicating if records are lists (default) or tuples.
- optional bool trim: when True (default), values are returned trimmed.
RESULT
- header: list/tuple of strings read from the 1st line.
- body: list of lines, each being a list/tuple of text fields.
- content: dictionary of tabs; content[a_tab] is a list of lines, each being a list/tuple of text fields.
header if any is the 1st line.
REMARKS
- csv_with_tabs: new in 2.3.5 (2022-11-29)
- default skip_before is 0 for lec_csv (= 1st line is a header) and -1 for csv_with_tabs(no header)
but it makes no difference for csv_with_tabs.
27.17. functions/list2file [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
fname = list2file(idlist [, header] [, footer] [, folder] [, suffix])
ARGUMENT
- idlist: list of id (unicode str).
- header: optional string to be placed before the list
- footer: optional string to be placed after the list
- folder: optional folder to create the file (default temp folder).
- suffix: optional string to be used as a suffix for fname. Defaults to 'IDs.txt'
RESULT
str fname: name of a temporary file containing header if any, elements of idlist,
footer if any, one per line.
27.18. functions/piccolo_context [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
PURPOSE
Reads Context.pic and return colorset and tresholds for given attribute
SYNTAX
attr, cname, tvals, cvals = piccolo_context(fcontext, attr=None, verbose=False)
ARGUMENT
- str fcontext: name of context file
- str attr: attribute to find colorset and thresholds
- bool verbose: for printing lookup messages
RESULT
- str attr: attribute found
- str cname: name of colorset
- list tvals: str list of values / float list of thresholds
- list cvals: str list of colors
REMARK
Returns as many colors as str thresholds if attr is alphanumeric;
one more color than float thresholds if attr is numeric.
A tuple of None is returned in case of failure
HISTORY
- introduced 2.2.6 (211117)
27.19. functions/quotefilename [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
txt = quotefilename(name)
ARGUMENT
RESULT
- string txt: file name quoted with double quotes if it contains a whitespace.
HISTORY
- added 11/09/2015.
- 2022/11/03 - fix null string causing an IndexError exception
27.20. functions/roundval, scaladjust [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
PURPOSE
Computes a rounded approximation of a float number
SYNTAX
- rmin, rbest, rmax = roundval(val, reltol= 0.01)
- rval = scaladjust(val)
ARGUMENT
- float val: value to be rounded
RESULT
- float rmin, rmax: lower and upper values approximations (rmax - rmin < reltol*|val|)
- float rbest: best approximation (one of rmin, rmax)
- float rval: value rounded at 1., 2. or 5. in the order of magnitude of val.
REMARK
scaladjust is used to determine the grid interval for plots as scaladjust(0.25*(ymax-ymin))
HISTORY
- 20.03.13 (2.1.1) fixed rounding when val < 1
- 23.07.10 (2.3.8) fixed roundval when 0.1 < abs(val)*reltol <1 or val < 0
27.21. functions/toidpic [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
out_str = toidpic(input_str)
ARGUMENT
unicode or string input_str: string value to be converted to a Piccolo ID
RESULT
ascii string where blank, comma, equal are replaced with underscore, other
non litteral or digit are replaced with minus.
27.22. functions/tsadd [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
PURPOSE
Sums two t, v time series being defined on different time steps
SYNTAX
- tr, vr = tsadd(t1, v1, t2, v2[, shape="constant"])
ARGUMENT
- sequence or np.array t1, t2: x values of ts 1 and 2 (ordered)
- sequence or np.array v1, v2: y values of ts 1 and 2
- str shape: "constant" (default) or "linear".
RESULT
- np.array tr: ordered union of x values t1 and t2
- np.array vr: sum of v1 and v2 considered piecewise constant
or piecewise linear depending on shape parameter
27.23. functions/update_package [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
stat = update_package(package_name [, minvers=""] [, pypi_name=None]
[, deps= False] [, https_proxy= None] [, verbose= True])
ARGUMENT
- string package_name: name of the package as used in the import statement
- optional string minvers: minimum version required, in the form x.y[.z]
- optional string pypi_name: package name in pypi, if different from package_name
- optional bool deps: set to True to install the dependencies
- optional string https_proxy: url and port of the proxy if required.
RESULT
bool stat: true if the package has been installed or updated
REMARKS
- minvers can also be provided as a list or tuple of ints
- proxy lookup starts with HTTPS_PROXY environment variable, then
configuration files lookup using get_proxy() function.
HISTORY
- 1.8.1 (171009) added
- 1.8.7 (171208) revised to allow ganessa to update itself
- 1.8.8 (171212) proxy config .json files lookup added
- 1.9.1 (180502) python3
- 1.9.2 (180518) use tempfile for testing access (MT compatibility)
- 2.0.0 (180818) added verbose parameter
- 2.0.5 (190109) remove testing access
- 2.0.7 (190821) modified python exe lookup for venv compatibility
- 2.0.9 (200205) minor fix in version_as_tuple: remove 4th level (post)
- 2.1.5 (210929) exit in embed mode if version inappopriate
- 2.2.9 (220214) replace -only-binary with -prefer-binary; add --trusted-host pypi.org
- 2.3.6 (230207) --use-feature=truststore; --trusted-host files.pythonhosted.org
- 2.3.9 (231004) check version with importlib.metadata.version if variable not found
27.24. functions/utf8_bom_encoding [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
encoding = utf8_bom_encoding(filename=None)
ARGUMENT
- string filename: input file name (defaults to None)
RESULT
string encoding:
- 'utf_8_sig' if no file argument passed
- 'utf_8_sig' if file exists and encoding is utf8-bom
- None if file does not exists or encoding is not utf8-bom
HISTORY
- 210310 (2.1.7): creation
- 210423 (2.1.9): fix empty file resulting in StopIteration exception
27.25. functions/winstr, utf,
ws, aws,
codewinfile [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
- out_txt = winstr(input_str)
- out_txt = utf(input_str)
- out_str = ws(input_str)
- out_astr = aws(input_str)
ARGUMENT
unicode or byte string input_str: string value to be encoded to windows-compatible string
RESULT
- out_txt encoded into Windows-1252 or utf-8 (no change if no accent or special character)
- out_str: (unicode) string in python3, Windows-1252 encoded string in python2
- out_astr: (unicode) string in python3, ascii unicode string in python2
REMARK
codewinfile and winstr are synonyms
HISTORY
- ws has been introduced 30.05.2018 - 1.9.3
- aws has been introduced 12.06.2018 - 1.9.5
27.26. functions/XMLduration [ Fonctions ]
[ Top ] [ functions ] [ Fonctions ]
SYNTAX
ival = XMLduration(input_string)
ARGUMENT
string input_str: XML duration string value to be converted to a number of seconds.
The input format is [-]PnYnMnDTnHnMnS where:
- leading 'P' is mandatory,
- at least one duration item must be present
- 'T' is mandatory if any hour, minute, second is present
- all items are integers except second that may be either int or float.
RESULT
int ival: number of seconds
28. ganessa.util/iterators [ Introduction ]
[ Top ] [ Introduction ]
28.1. iterators/group_ [ Iterator ]
[ Top ] [ iterators ] [ Iterator ]
SYNTAX
for items in group(iterable, count):
ARGUMENT
- iterable: iterable
- int count: group size
RESULT
this iterator allows to return the elements of iterable grouped
by lists of size count. The last list may contain less than group elements
HISTORY
- 1.7.6 (170613): iterator added
- 2.0.0 (180816): python 3.7 compatibility
29. Constants/BRANCH, LINK_,
NODE_, NOEUD,
TANK_, RESERVOIR_,
RSV [ Constants ]
[ Top ] [ Constants ]
DESCRIPTION
Those constants allow to select one of the three types of model elements:
- LINK or BRANCH: branches elements such as Pipes, pumps, valves
- NODE or NOEUD
- TANK or RESERVOIR or RSV
REMARK
M.LNK, M.NOD and M.RSV are object constants for calling BRANCH, NODE and RESERVOIR modules
30. Constants/DICT_ [ Constants ]
[ Top ] [ Constants ]
DESCRIPTION
The DICT class provide a dictionnary tree for keywords
SYNTAX
DICT.SYMBOLIC_NAME
CONTENT
- FULLPER: extended simulation (ENCHAINE in French)
- EXPORT
- INSTANT
31. Constants/M [ Constants ]
[ Top ] [ Constants ]
DESCRIPTION
The M class provide a dictionnary tree for modules. It provides a
hierarchical naming of the commands by modules, for building
language-independant commands using gencmd, gencmdw, _gencmdw functions.
SYNTAX
One of the following:
- M.MODULE_SYMBOLIC_NAME
- M.MODULE_SYMBOLIC_NAME.COMMAND__SYMBOLIC_NAME or
- M.MODULE_SYMBOLIC_NAME..NONE or M.NONE or M.VOID
CONTENT
The available MODULE_SYMBOLIC_NAME are:
ROOT: modules names: BRA, NOD, RSV, DYN, MOD, SIM, QUA, MES, LAB, FIR, INV, OPT.
They can be used in three forms, as first argument for the functions above:
- M.ROOT.SIM or M.SIM.ROOT: equals the index of the module name
- M.SIM: can be used in gencmd and gencmdw only as first argument
GEN: general purpose commands:
- LOAD: load a binary file
- OPEN and CLOSE: open and close an output file
- QUIT: the quit command
- READ: read a command language or data file
example: gencmd(M.GEN, M.GEN.OPEN, DICT.EXPORT, 'filename.txt')
- EXPORT, SAVE: export or save to a (previously opened) file
- IMPORT: import attributes for a type of element from a file
- FIND: command for retrieving a given period or instant
- MESSAGE: writes a message to the console
- DEFPARAM, DEFVAR: define a positional parameter (%1 ... %9) or variable
- UNIT: redefine units name and coef
- EOF: the end-of-file command
LNK: link commands and submodules, including link types (.PIPE .PUMP .NRV .PRV .PSV .FCV .TCV etc.)
NOD: node commands and submodules:
- CONS: demand acquisition submodule
- COEF, AREA: demand coefficient by demand type and area
- TOPO: topograpy submodule
RSV: reservoir command and submodules:
- CHAR: characteristics
- LEVEL: initial level acquisition submodule
MES: measurement commands:
- SMOOTH: allow to define the smoothing interval
SIM: simulation commands:
- FILE: define a result file name
- EXEC: runs the simulation
QUA: Water quality module commands
REMARK
The above codes are not exhaustive. Please refer to the script.
32. Constants/STR_ATTR_FR, STR_ATTR_EN,
STR_ATTR_SP [ Constants ]
[ Top ] [ Constants ]
DESCRIPTION
Sets of attributes whose values are str; other attributes are numeric.
* STR_ATTR_FR: French str attributes
* STR_ATTR_EN: English str attributes
* STR_ATTR_SP: Spanish str attributes
REMARK
see attr_is_str for testing against current language.