Technical Reference of the Digraph3 modules

Author:Raymond Bisdorff, University of Luxembourg FSTC/CSC
Version:Revision: Python 3.5
Copyright:R. Bisdorff 2013-2016

Installation

Dowloading the Digraph3 ressources

Three download options are given:

  1. Either (easiest under Linux or Mac OS-X), by using a git client:

    ..$ git clone https://github.com/rbisdorff/Digraph3
    
  2. or a subversion client:

    ..$ svn co http://leopold-loewenheim.uni.lu/svn/repos/Digraph3
    
  3. Or, with a browser access, download and extract the latest distribution tar.gz archive from this page:

    http://leopold-loewenheim.uni.lu/Digraph3/dist/
    

On Linux or Mac OS, ..$ cd to the extracted <Digraph3> directory:

../Digraph3$ make install

installs (with sudo !!) the digraphs module in the current running python environment. Pythhon 3.5 (or later) environment is recommended:

../Digraph3$ make tests

runs a nose test suite in the ./test directory (python3 nose package required ..$ pip3 install nose ):

../Digraph3$ make verboseTests

runs a verbose (with stdout not captured) nose test suite:

../Digraph3$ make pTests

runs the nose test suite in multiple processing mode when the GNU parallel shell tool is installed and multiple cores are detected.

To be fully functional, the Digraph3 resources mainly need the graphviz tools and the R statistics resources to be installed. When exploring digraph isomorphisms, the nauty isomorphism testing program is required. Two specific criteria and actions clustering methods of the OutrankingDigraph class furthermore require the calmat matrix computing resource to be installed.

Organisation of the Digraph3 python3 source code

The Digraph3 source code is split into several interdependent modules of which the digraphs module is the master module.

Developping the Rubis decision support methodology is an ongoing research project of Raymond Bisdorff <http://leopold-loewenheim.uni.lu/bisdorff/>, University of Luxembourg.

digraphs module

A tutorial with coding examples is available here: Working with the Digraph3 software ressources

Python3+ implementation of digraphs

Copyright (C) 2006-2017 Raymond Bisdorff

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

class digraphs.AsymmetricPartialDigraph(digraph)[source]

Bases: digraphs.Digraph

Renders the asymmetric part of a Digraph instance.

Note

  • The non asymmetric and the reflexive links are all put to the median indeterminate characteristic value!
  • The constructor makes a deep copy of the given Digraph instance!
class digraphs.BreakAddCocsDigraph(digraph=None, Cpp=False, Piping=False, Comments=False, Threading=False, nbrOfCPUs=1)[source]

Bases: digraphs.Digraph

Specialization of general Digraph class for instantiation of chordless odd circuits augmented digraphs.

Parameters:

  • digraph: Stored or memory resident digraph instance.
  • Cpp: using a C++/Agrum version of the Digraph.computeChordlessCircuits() method.
  • Piping: using OS pipes for data in- and output between Python and C++.

A chordless odd circuit is added if the cumulated credibility of the circuit supporting arcs is larger or equal to the cumulated credibility of the converse arcs. Otherwise, the circuit is broken at the weakest asymmetric link, i.e. a link (x, y) with minimal difference between r(x S y) - r(y S x).

addCircuits(Comments=False)[source]

Augmenting self with self.circuits.

closureChordlessOddCircuits(Cpp=False, Piping=False, Comments=True, Debug=False, Threading=False, nbrOfCPUs=1)[source]

Closure of chordless odd circuits extraction.

showCircuits(credibility=None, Debug=False)[source]

show methods for chordless odd circuits in CocaGraph

showComponents()[source]
class digraphs.BrokenCocsDigraph(digraph=None, Cpp=False, Piping=False, Comments=False, Threading=False, nbrOfCPUs=1)[source]

Bases: digraphs.Digraph

Specialization of general Digraph class for instantiation of chordless odd circuits broken digraphs.

Parameters:

  • digraph: stored or memory resident digraph instance.
  • Cpp: using a C++/Agrum version of the Digraph.computeChordlessCircuits() method.
  • Piping: using OS pipes for data in- and output between Python and C++.

All chordless odd circuits are broken at the weakest asymmetric link, i.e. a link (x, y) with minimal difference between r(x S y) and r(y S x).

breakChordlessOddCircuits(Cpp=False, Piping=False, Comments=True, Debug=False, Threading=False, nbrOfCPUs=1)[source]

Breaking of chordless odd circuits extraction.

breakCircuits(Comments=False)[source]

Break all cricuits in self.circuits.

showComponents()[source]
class digraphs.CSVDigraph(fileName='temp', valuationMin=-1, valuationMax=1)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for reading stored csv formatted digraphs. Using the inbuilt module csv.

Param:
fileName (without the extension .csv).
showAll()[source]
class digraphs.CirculantDigraph(order=7, valuationdomain={'min': Decimal('-1.0'), 'max': Decimal('1.0')}, circulants=[-1, 1])[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary circulant digraphs.

Parameters:
order > 0;
valuationdomain ={‘min’:m, ‘max’:M};
circulant connections = list of positive and/or negative circular shifts of value 1 to n.
Default instantiation C_7:
order = 7,
valuationdomain = {‘min’:-1.0,’max’:1.0},
circulants = [-1,1].

Example session:

>>> from digraphs import CirculantDigraph
>>> c8 = CirculantDigraph(order=8,circulants=[1,3])
>>> c8.exportGraphViz('c8')
*---- exporting a dot file dor GraphViz tools ---------*
Exporting to c8.dot
circo -Tpng c8.dot -o c8.png
# see below the graphviz drawing
>>> c8.showChordlessCircuits()
No circuits yet computed. Run computeChordlessCircuits()!
>>> c8.computeChordlessCircuits()
...
>>> c8.showChordlessCircuits()
*---- Chordless circuits ----*
['1', '4', '7', '8'] , credibility : 1.0
['1', '4', '5', '6'] , credibility : 1.0
['1', '4', '5', '8'] , credibility : 1.0
['1', '2', '3', '6'] , credibility : 1.0
['1', '2', '5', '6'] , credibility : 1.0
['1', '2', '5', '8'] , credibility : 1.0
['2', '3', '6', '7'] , credibility : 1.0
['2', '3', '4', '7'] , credibility : 1.0
['2', '5', '6', '7'] , credibility : 1.0
['3', '6', '7', '8'] , credibility : 1.0
['3', '4', '7', '8'] , credibility : 1.0
['3', '4', '5', '8'] , credibility : 1.0
12 circuits.
>>>
circulant [1,3] digraph
showShort()[source]
class digraphs.CoDualDigraph(other, Debug=False)[source]

Bases: digraphs.Digraph

Instantiates the associated codual -converse of the negation- from a deep copy of a given Digraph instance called other.

Note

Instantiates self as other.__class__ ! And, deepcopies, the case given, the other.description, the other.criteria and the other.evaluation dictionaries into self.

class digraphs.CocaDigraph(digraph=None, Cpp=False, Piping=False, Comments=False)[source]

Bases: digraphs.Digraph

Old CocaDigraph class without circuit breakings; all circuits and circuits of circuits are added as hyper-nodes.

Warning

May sometimes give inconsistent results when an autranking digraph shows loads of chordless cuircuits. It is recommended in this case to use instead either the BrokenCocsDigraph class (preferred option) or the BreakAddCocsDigraph class.

Parameters:

  • digraph: Stored or memory resident digraph instance.
  • Cpp: using a C++/Agrum version of the Digraph.computeChordlessCircuits() method.
  • Piping: using OS pipes for data in- and output between Python and C++.

Specialization of general Digraph class for instantiation of chordless odd circuits augmented digraphs.

addCircuits(Comments=False)[source]

Augmenting self with self.circuits.

closureChordlessOddCircuits(Cpp=False, Piping=False, Comments=False)[source]

Closure of chordless odd circuits extraction.

showCircuits(credibility=None)[source]

show methods for chordless odd circuits in CocaGraph

showComponents()[source]
class digraphs.CompleteDigraph(order=5, valuationdomain=(-1.0, 1.0))[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary complete graphs of order 5 in {-1,0,1} by default.

Parameters:
order > 0; valuationdomain=(Min,Max).
class digraphs.ConverseDigraph(other)[source]

Bases: digraphs.Digraph

Instantiates the associated converse or reciprocal version from a deep copy of a given Digraph called other.

Instantiates as other.__class__ !

Depp copies the case given the description, the criteria and the evaluation dictionary into self.

class digraphs.CoverDigraph(other, Debug=False)[source]

Bases: digraphs.Digraph

Instantiates the associated cover relation -immediate neighbours- from a deep copy of a given Digraph called other. The Hasse diagram for instance is the cover relation of a transitive digraph.

Note

Instantiates as other.__class__ ! Copies the case given the other.description, the other.criteria and the other.evaluation dictionaries into self.

class digraphs.Digraph(file=None, order=7)[source]

Bases: object

Genuine root class of all Digraph3 modules. See tutorial working with the digraphs module

All instances of the digraphs.Digraph class contain at least the following components:

  1. A collection of digraph nodes called actions (decision alternatives): a list, set or (ordered) dictionary of nodes with ‘name’ and ‘shortname’ attributes,
  2. A logical characteristic valuationdomain, a dictionary with three decimal entries: the minimum (-1.0, means certainly false), the median (0.0, means missing information) and the maximum characteristic value (+1.0, means certainly true),
  3. The digraph relation : a double dictionary indexed by an oriented pair of actions (nodes) and carrying a characteristic value in the range of the previous valuation domain,
  4. Its associated gamma function : a dictionary containing the direct successors, respectively predecessors of each action, automatically added by the object constructor,
  5. Its associated notGamma function : a dictionary containing the actions that are not direct successors respectively predecessors of each action, automatically added by the object constructor.

A previously stored digraphs.Digraph instance may be reloaded with the file argument:

>>> from randomDigraphs import RandomValuationDigraph
>>> dg = RandomValuationDigraph(order=3,Normalized=True,seed=1)
>>> dg.save('testdigraph')
Saving digraph in file: <testdigraph.py> 
>>> from digraphs import Digraph
>>> dg = Digraph(file='testdigraph') # without the .py extenseion
>>> dg.__dict__
{'name': 'testdigraph',
'actions': {'a1': {'name': 'random decision action', 'shortName': 'a1'},
            'a2': {'name': 'random decision action', 'shortName': 'a2'},
            'a3': {'name': 'random decision action', 'shortName': 'a3'}},
'valuationdomain': {'min': Decimal('-1.0'), 'med': Decimal('0.0'),
                        'max': Decimal('1.0'), 'hasIntegerValuation': False,},
'relation': {'a1': {'a1': Decimal('0.0'), 'a2': Decimal('-0.66'), 'a3': Decimal('0.44')},
             'a2': {'a1': Decimal('0.94'), 'a2': Decimal('0.0'), 'a3': Decimal('-0.84')},
             'a3': {'a1': Decimal('-0.36'), 'a2': Decimal('-0.70'), 'a3': Decimal('0.0')}},
'order': 3,
'gamma': {'a1': ({'a3'}, {'a2'}), 'a2': ({'a1'}, set()), 'a3': (set(), {'a1'})},
'notGamma': {'a1': ({'a2'}, {'a3'}),
             'a2': ({'a3'}, {'a1', 'a3'}),
             'a3': ({'a1', 'a2'}, {'a2'})}}
>>>
MISgen(S, I)[source]
generator of maximal independent choices (voir Byskov 2004):
  • S ::= remaining nodes;
  • I ::= current independent choice

Note

Inititalize: self.MISgen(self.actions.copy(),set())

absirred(choice)[source]

Renders the crips -irredundance degree of a choice.

absirredundant(U)[source]

Generates all -irredundant choices of a digraph.

absirredval(choice, relation)[source]

Renders the valued -irredundance degree of a choice.

absirredx(choice, x)[source]

Computes the crips -irredundance degree of node x in a choice.

abskernelrestrict(choice)[source]

Parameter: prekernel Renders absorbent prekernel restricted relation.

absorb(choice)[source]

Renders the absorbency degree of a choice.

absorbentChoices(S)[source]

Generates all minimal absorbent choices of a bipolar valued digraph.

agglomerationDistribution()[source]

Output: aggloCoeffDistribution, meanCoeff Renders the distribution of agglomeration coefficients.

aneighbors(node)[source]

Renders the set of absorbed in-neighbors of a node.

automorphismGenerators()[source]

Add automorphism group generators to digraph.

averageCoveringIndex(choice, direction='out')[source]

Renders the average covering index of a given choice in a set of objects, ie the average number of choice members that cover each non selected object.

bestRanks()[source]

renders best possible ranks from indegrees account

bipolarKCorrelation(digraph, Debug=False)[source]

Renders the bipolar Kendall correlation between two bipolar valued digraphs computed from the average valuation of the XORDigraph(self,digraph) instance.

Warning

Obsolete! Is replaced by the self.computeBipolarCorrelation(other) Digraph method

bipolarKDistance(digraph, Debug=False)[source]

Renders the bipolar crisp Kendall distance between two bipolar valued digraphs.

Warning

Obsolete! Is replaced by the self.computeBipolarCorrelation(other, MedianCut=True) Digraph method

chordlessPaths(Pk, n2, Odd=False, Comments=False, Debug=False)[source]

New procedure from Agrum study April 2009 recursive chordless path extraction strating from path Pk = [n2, ...., n1] and ending in node n2. Optimized with marking of visited chordless P1s.

circuitAverageCredibility(circ)[source]

Renders the average linking credibility of a COC.

circuitCredibilities(circuit, Debug=False)[source]

Renders the average linking credibilities and the minimal link of a COC.

circuitMaxCredibility(circ)[source]

Renders the minimal linking credibility of a COC.

circuitMinCredibility(circ)[source]

Renders the minimal linking credibility of a COC.

closeSymmetric()[source]

Produces the symmetric closure of self.relation.

closeTransitive(Irreflexive=True, Reverse=False)[source]

Produces the transitive closure of self.relation.

collectcomps(x, A, ncomp)[source]

Recursive subroutine of the components method.

components()[source]

Renders the list of connected components.

computeAllDensities(choice=None)[source]

parameter: choice in self renders six densitiy parameters: arc density, double arc density, single arc density, strict single arc density, absence arc density, strict absence arc densitiy.

computeArrowRaynaudOrder()[source]

Renders a linear ordering from worst to best of the actions following Arrow&Raynaud’s rule.

computeArrowRaynaudRanking()[source]

renders a linear ranking from best to worst of the actions following Arrow&Raynaud’s rule.

computeAverageValuation()[source]

Computes the bipolar average correlation between self and the crisp complete digraph of same order of the irreflexive and determined arcs of the digraph

computeBadChoices(Comments=False)[source]

Computes characteristic values for potentially bad choices.

Note

Returns a tuple with following content:

[(0)-determ,(1)degirred,(2)degi,(3)degd,(4)dega,(5)str(choice),(6)absvec]

computeBadPirlotChoices(Comments=False)[source]

Characteristic values for potentially bad choices using the Pirlot’s fixpoint algorithm.

computeBipolarCorrelation(other, MedianCut=False, filterRelation=None, Debug=False)[source]

obsolete: dummy replacement for Digraph.computeOrdinalCorrelation method

computeChordlessCircuits(Odd=False, Comments=False, Debug=False)[source]

Renders the set of all chordless odd circuits detected in a digraph. Result (possible empty list) stored in <self.circuitsList> holding a possibly empty list tuples with at position 0 the list of adjacent actions of the circuit and at position 1 the set of actions in the stored circuit.

computeChordlessCircuitsMP(Odd=False, Threading=False, nbrOfCPUs=None, Comments=False, Debug=False)[source]

Multiprocessing version of computeChordlessCircuits().

Renders the set of all chordless odd circuits detected in a digraph. Result (possible empty list) stored in <self.circuitsList> holding a possibly empty list tuples with at position 0 the list of adjacent actions of the circuit and at position 1 the set of actions in the stored circuit. Inspired by Dias, Castonguay, Longo, Jradi, Algorithmica (2015).

Returns a possibly empty list of tuples (circuit,frozenset(circuit)).

If Odd == True, only circuits of odd length are retained in the result.

computeCoSize()[source]

Renders the number of non validated non reflexive arcs

computeConcentrationIndex(X, N)[source]

Renders the Gini concentration index of the X serie. N contains the partial frequencies. Based on the triangle summation formula.

computeConcentrationIndexTrapez(X, N)[source]

Renders the Gini concentration index of the X serie. N contains the partial frequencies. Based on the triangles summation formula.

computeCondorcetWinners()[source]

Wrapper for condorcetWinners().

computeCopelandRanking()[source]

Renders a linear ranking from best to worst of the actions following Copelands’s rule.

computeCppChordlessCircuits(Odd=False, Debug=False)[source]

python wrapper for the C++/Agrum based chordless circuits enumeration exchange arguments with external temporary files

computeCppInOutPipingChordlessCircuits(Odd=False, Debug=False)[source]

python wrapper for the C++/Agrum based chordless circuits enumeration exchange arguments with external temporary files

computeCutLevelDensities(choice, level)[source]

parameter: choice in self, robustness level renders three robust densitiy parameters: robust double arc density, robust single arc density, robust absence arc densitiy.

computeDensities(choice)[source]

parameter: choice in self renders the four densitiy parameters: arc density, double arc density, single arc density, absence arc density.

computeDeterminateness()[source]

Computes the Kendalll distance in % of self with the all median valued (indeterminate) digraph.

computeGoodChoiceVector(ker, Comments=False)[source]
Characteristic values for potentially good choices.
[(0)-determ,(1)degirred,(2)degi,(3)degd,(4)dega,(5)str(choice),(6)domvec]
computeGoodChoices(Comments=False)[source]

Computes characteristic values for potentially good choices.

..note:

Return a tuple with following content:

[(0)-determ,(1)degirred,(2)degi,(3)degd,(4)dega,(5)str(choice),(6)domvec,(7)cover]
computeGoodPirlotChoices(Comments=False)[source]

Characteristic values for potentially good choices using the Pirlot fixpoint algorithm.

computeKemenyIndex(otherRelation)[source]

renders the Kemeny index of the self.relation compared with a given crisp valued relation of a compatible other digraph (same nodes or actions).

computeKemenyOrder(orderLimit=7, Debug=False)[source]

Renders a ordering from worst to best of the actions with maximal Kemeny index. Return a tuple: kemenyOrder (from worst to best), kemenyIndex

computeKemenyRanking(isProbabilistic=False, orderLimit=7, seed=None, sampleSize=1000, Debug=False)[source]

Renders a ordering from worst to best of the actions with maximal Kemeny index.

Note

Returns a tuple: kemenyRanking (from best to worst), kemenyIndex.

computeKohlerOrder()[source]
computeKohlerRanking()[source]
computeMeanInDegree()[source]

Renders the mean indegree of self. !!! self.size must be set previously !!!

computeMeanOutDegree()[source]

Renders the mean degree of self. !!! self.size must be set previously !!!

computeMeanSymDegree()[source]

Renders the mean degree of self. !!! self.size must be set previously !!!

computeMedianOutDegree()[source]

Renders the median outdegree of self. !!! self.size must be set previously !!!

computeMedianSymDegree()[source]

Renders the median symmetric degree of self. !!! self.size must be set previously !!!

computeMoreOrLessUnrelatedPairs()[source]

Renders a list of more or less unrelated pairs.

computeNetFlowsOrder()[source]

Renders an ordered list (from worst to best) of the actions following the net flows ranking rule.

computeNetFlowsRanking()[source]

Renders an ordered list (from best to worst) of the actions following the net flows ranking rule.

computeODistance(op2, comments=False)[source]

renders the squared normalized distance of two digraph valuations.

Note

op2 = digraphs of same order as self.

computeOrbit(choice, withListing=False)[source]

renders the set of isomorph copies of a choice following the automorphism of the digraph self

computeOrderCorrelation(order, Debug=False)[source]

Renders the ordinal correlation K of a digraph instance when compared with a given linear order (from worst to best) of its actions

K = sum_{x != y} [ min( max(-self.relation(x,y)),other.relation(x,y), max(self.relation(x,y),-other.relation(x,y)) ]

K /= sum_{x!=y} [ min(abs(self.relation(x,y),abs(other.relation(x,y)) ]

Note

Renders a dictionary with the key ‘correlation’ containing the actual bipolar correlation index and the key ‘determination’ containing the minimal determination level D of self and the other relation.

D = sum_{x != y} min(abs(self.relation(x,y)),abs(other.relation(x,y)) / n(n-1)

where n is the number of actions considered.

The correlation index with a completely indeterminate relation is by convention 0.0 at determination level 0.0 .

Warning

self must be a normalized outranking digraph instance !

computeOrdinalCorrelation(other, MedianCut=False, filterRelation=None, Debug=False)[source]

Renders the bipolar correlation K of a self.relation when compared with a given compatible (same actions set)) digraph or a [-1,1] valued compatible relation (same actions set).

If MedianCut=True, the correlation is computed on the median polarized relations.

If filterRelation != None, the correlation is computed on the partial domain corresponding to the determined part of the filter relation.

Warning

Notice that the ‘other’ relation and/or the ‘filterRelation’, the case given, must both be normalized, ie [-1,1]-valued !

K = sum_{x != y} [ min( max(-self.relation[x][y]),other.relation[x][y]), max(self.relation[x][y],-other.relation[x][y]) ]

K /= sum_{x!=y} [ min(abs(self.relation[x][y]),abs(other.relation[x][y])) ]

Note

Renders a tuple with at position 0 the actual bipolar correlation index and in position 1 the minimal determination level D of self and the other relation.

D = sum_{x != y} min(abs(self.relation[x][y]),abs(other.relation[x][y])) / n(n-1)

where n is the number of actions considered.

The correlation index with a completely indeterminate relation is by convention 0.0 at determination level 0.0 .

computeOrdinalCorrelationMP(other, MedianCut=False, Threading=True, nbrOfCPUs=None, Comments=False, Debug=False)[source]

Multi processing version of the digraphs.computeOrdinalCorrelation() method.

Note

The relation filtering and the MedinaCut option are not implemented in the MP version.

computePairwiseClusterComparison(K1, K2, Debug=False)[source]

Computes the pairwise cluster comparison credibility vector from bipolar-valued digraph g. with K1 and K2 disjoint lists of action keys from g actions disctionary. Returns the dictionary {‘I’: Decimal(),’P+’:Decimal(),’P-‘:Decimal(),’R’ :Decimal()} where one and only one item is strictly positive.

computePreKernels()[source]
computing dominant and absorbent preKernels:
Result in self.dompreKernels and self.abspreKernels
computePreRankingRelation(preRanking, Normalized=True, Debug=False)[source]

Renders the bipolar-valued relation obtained from a given preRanking in decreasing levels (list of lists) result.

computePreorderRelation(preorder, Normalized=True, Debug=False)[source]

Renders the bipolar-valued relation obtained from a given preordering in increasing levels (list of lists) result.

computePrincipalOrder(plotFileName=None, Colwise=False, imageType=None, TempDir=None, Comments=False, Debug=False)[source]

Renders a ordered list of self.actions using the decreasing scores from the first rincipal eigenvector of the covariance of the valued outdegrees of self.

Note

The method, relying on writing and reading temporary files by default in a temporary directory is threading and multiprocessing safe ! (see Digraph.exportPrincipalImage method)

computePrudentBetaLevel(Debug=False)[source]

computes alpha, ie the lowest valuation level, for which the bipolarly polarised digraph doesn’t contain a chordless circuit.

computeRankedPairsOrder(Cpp=False, Debug=False)[source]

Renders an actions ordering from the worst to the best obtained from the ranked pairs rule.

computeRankedPairsRanking()[source]

Renders an actions ordering from the best to the worst obtained from the ranked pairs rule.

computeRankingByBestChoosing(CoDual=False, CppAgrum=False, Debug=False)[source]

Computes a weak preordering of the self.actions by recursive best choice elagations.

Stores in self.rankingByBestChoosing[‘result’] a list of (P+,bestChoice) tuples where P+ gives the best choice complement outranking average valuation via the computePairwiseClusterComparison method.

If self.rankingByBestChoosing[‘CoDual’] is True, the ranking-by-choosing was computed on the codual of self.

computeRankingByBestChoosingRelation(rankingByBestChoosing=None, Debug=False)[source]

Renders the bipolar-valued relation obtained from the self.rankingByBestChoosing result.

computeRankingByChoosing(actionsSubset=None, CppAgrum=False, Debug=False, CoDual=False)[source]

Computes a weak preordring of the self.actions by iterating jointly best and worst choice elagations.

Stores in self.rankingByChoosing[‘result’] a list of ((P+,bestChoice),(P-,worstChoice)) pairs where P+ (resp. P-) gives the best (resp. worst) choice complement outranking (resp. outranked) average valuation via the computePairwiseClusterComparison method.

If self.rankingByChoosing[‘CoDual’] is True, the ranking-by-choosing was computed on the codual of self.

computeRankingByChoosingRelation(rankingByChoosing=None, actionsSubset=None, Debug=False)[source]

Renders the bipolar-valued relation obtained from the self.rankingByChoosing result.

computeRankingByLastChoosing(CoDual=False, CppAgrum=False, Debug=False)[source]

Computes a weak preordring of the self.actions by iterating worst choice elagations.

Stores in self.rankingByLastChoosing[‘result’] a list of (P-,worstChoice) pairs where P- gives the worst choice complement outranked average valuation via the computePairwiseClusterComparison method.

If self.rankingByChoosing[‘CoDual’] is True, the ranking-by-last-chossing was computed on the codual of self.

computeRankingByLastChoosingRelation(rankingByLastChoosing=None, Debug=False)[source]

Renders the bipolar-valued relation obtained from the self.rankingByLastChoosing result.

computeRankingCorrelation(ranking, Debug=False)[source]

Renders the ordinal correlation K of a digraph instance when compared with a given linear ranking of its actions

K = sum_{x != y} [ min( max(-self.relation(x,y)),other.relation(x,y), max(self.relation(x,y),-other.relation(x,y)) ]

K /= sum_{x!=y} [ min(abs(self.relation(x,y),abs(other.relation(x,y)) ]

Note

Renders a tuple with at position 0 the actual bipolar correlation index and in position 1 the minimal determination level D of self and the other relation.

D = sum_{x != y} min(abs(self.relation(x,y)),abs(other.relation(x,y)) / n(n-1)

where n is the number of actions considered.

The correlation index with a completely indeterminate relation is by convention 0.0 at determination level 0.0 .

computeRelationalStructure(Debug=False)[source]

Renders the counted decomposition of the valued relations into the following type of links: gt ‘>’, eq ‘=’, lt ‘<’, incomp ‘<>’, leq ‘<=’, geq ‘>=’, indeterm ‘?’

computeRubisChoice(CppAgrum=False, Comments=False, _OldCoca=False, BrokenCocs=True, Threading=False, nbrOfCPUs=1)[source]

Renders self.strictGoodChoices, self.nullChoices self.strictBadChoices, self.nonRobustChoices.

CppgArum = False (default | true : use C++/Agrum digraph library for computing chordless circuits in self.

Warning

Changes in site the outranking digraph by adding or braking chordless odd outranking circuits.

computeRubyChoice(CppAgrum=False, Comments=False, _OldCoca=False)[source]

dummy for computeRubisChoice() old versions compatibility.

computeSingletonRanking(Comments=False, Debug=False)[source]

Renders the sorted bipolar net determinatation of outrankingness minus outrankedness credibilities of all singleton choices.

res = ((netdet,singleton,dom,absorb)+)

computeSize()[source]

Renders the number of validated non reflexive arcs

computeSizeTransitiveClosure()[source]

Renders the size of the transitive closure of a digraph.

computeSlaterOrder(isProbabilistic=False, seed=None, sampleSize=1000, Debug=False)[source]

Reversed return from computeSlaterRanking method.

computeSlaterRanking(isProbabilistic=False, seed=None, sampleSize=1000, Debug=False)[source]

Renders a ranking of the actions with minimal Slater index. Return a tuple: slaterOrder, slaterIndex

computeTransitivityDegree()[source]

Renders the transitivity degree of a digraph.

computeUnrelatedPairs()[source]

Renders a list of more or less unrelated pairs.

computeValuationLevels(choice=None, Debug=False)[source]

renders the symmetric closure of the apparent valuations levels of self in an increasingly ordered list. If parameter choice is given, the computation is limited to the actions of the choice.

computeValuationPercentages(choice, percentiles, withValues=False)[source]

Parameters: choice and list of percentages. renders a series of quantiles of the characteristics valuation of the arcs in the digraph.

computeValuationPercentiles(choice, percentages, withValues=False)[source]

Parameters: choice and list of percentages. renders a series of quantiles of the characteristics valuation of the arcs in the digraph.

computeValuationStatistics(Sampling=False, Comments=False)[source]

Renders the mean and variance of the valuation of the non reflexive pairs.

computeWeakCondorcetWinners()[source]

Wrapper for weakCondorcetWinners().

computeupdown1(s, S)[source]

Help method for show_MIS_HB2 method. fills self.newmisset, self.upmis, self.downmis.

computeupdown2(s, S)[source]

Help method for show_MIS_HB1 method. Fills self.newmisset, self.upmis, self.downmis.

computeupdown2irred(s, S)[source]

Help method for show_MIS_HB1 method. Fills self.newmisset, self.upmis, self.downmis.

condorcetWinners()[source]

Renders the set of decision actions x such that self.relation[x][y] > self.valuationdomain[‘med’] for all y != x.

contra(v)[source]

Parameter: choice. Renders the negation of a choice v characteristic’s vector.

convertRelationToDecimal()[source]

Converts the float valued self.relation in a decimal valued one.

convertValuationToDecimal()[source]

Convert the float valuation limits to Decimals.

coveringIndex(choice, direction='out')[source]

Renders the covering index of a given choice in a set of objects, ie the minimum number of choice members that cover each non selected object.

crispKDistance(digraph, Debug=False)[source]

Renders the crisp Kendall distance between two bipolar valued digraphs.

Warning

Obsolete! Is replaced by the self.computeBipolarCorrelation(other, MedianCut=True) Digraph method

detectChordlessCircuits(Comments=False, Debug=False)[source]

Detects a chordless circuit in a digraph. Returns a Boolean

detectChordlessPath(Pk, n2, Comments=False, Debug=False)[source]

New procedure from Agrum study April 2009 recursive chordless path extraction starting from path Pk = [n2, ...., n1] and ending in node n2. Optimized with marking of visited chordless P1s.

detectCppChordlessCircuits(Debug=False)[source]

python wrapper for the C++/Agrum based chordless circuits detection exchange arguments with external temporary files. Returns a boolean value

determinateness(vec, inPercent=True)[source]

Renders the determinateness of a bipolar characteristic vector [(r(x),x),(r(y),y), ...] of length n in valuationdomain [Min,Max]:

result = sum_x abs(r(x))/(n*(Max-Min)

If inPercent, result shifted (+1) and reduced (/2) to [0,1] range.

diameter(Oriented=False)[source]

Renders the (by default non-oriented) diameter of the digraph instance

digraph2Graph(valuationDomain={'min': -1, 'med': 0, 'max': 1}, Debug=False, conjunctiveConversion=True)[source]

Convert a Digraph instance to a Graph instance.

dneighbors(node)[source]

Renders the set of dominated out-neighbors of a node.

domin(choice)[source]

Renders the dominance degree of a choice.

dominantChoices(S)[source]

Generates all minimal dominant choices of a bipolar valued digraph.

Note

Initiate with S = self.actions,copy().

domirred(choice)[source]

Renders the crips +irredundance degree of a choice.

domirredval(choice, relation)[source]

Renders the valued +irredundance degree of a choice.

domirredx(choice, x)[source]

Renders the crips +irredundance degree of node x in a choice.

domkernelrestrict(choice)[source]

Parameter: prekernel Renders dominant prekernel restricted relation.

exportD3(fileName='index', Comments=True)[source]

This function was designed and implemented by Gary Cornelius, 2014 for his bachelor thesis at the University of Luxembourg. The thesis document with more explanations can be found here .

Parameters:
  • fileName, name of the generated html file, default = None (graph name as defined in python);
  • Comments, True = default;

The idea of the project was to find a way that allows you to easily get details about certain nodes or edges of a directed graph in a dynamic format. Therefore this function allows you to export a html file together with all the needed libraries, including the D3 Library which we use for graph generation and the physics between nodes, which attracts or pushes nodes away from each other.

Features of our graph include i.e.
:
  • A way to only inspect a node and it’s neighbours
  • Dynamic draging and freezing of the graph
  • Export of a newly created general graph

You can find the list of fututres in the Section below which is arranged according to the graph type.

If the graph is an outrankingdigraphs:
  • Nodes can be dragged and only the name and comment can be edited.
  • Edges can be inspected but not edited for this purpose a special json array containing all possible pairwiseComparisions is generated.
If the graph is a general graph:
  • Nodes can be dragged, added, removed and edited.
  • Edges can be added, removed, inverted and edited. But edges cannot be inspected.
  • The pairwiseComparisions key leads to an empty array {}.

In both cases, undefined edges can be hidden and reappear after a simple reload.(right click - reload)

The generated files:
  • d3.v3.js, contains the D3 Data-driven Documents source code, containing one small addition that we made in order to be able to easyly import links with a different formatself.
  • digraph3lib.js, contains our library. This file contains everything that we need from import of an XMCDA2 file, visualization of the graph to export of the changed graph.
  • d3export.json, usually named after the python graph name followed by a ticket number if the file is already present. It is the JSON file that is exported with the format “{“xmcda2”: “some xml”,”pairwiseComparisions”:”{“a01”: “some html”,...}”}.
Example 1:
  1. python3 session:
    >>> from digraphs import RandomValuationDigraph
    >>> dg = RandomValuationDigraph(order=5,Normalized=True)
    >>> dg.exportD3()
    or
    >> dg.showInteractiveGraph()
    
  2. index.html:
    • Main Screen:
      _images/randomvaluation_d3_main.png
    • Inspect function:
      _images/randomvaluation_d3_inspect.png

Note

If you want to use the automatic load in Chrome, try using the command: “python -m SimpleHTTPServer” and then access the index.html via “http://0.0.0.0:8000/index.html”. In order to load the CSS an active internet connection is needed!

exportGraphViz(fileName=None, actionsSubset=None, bestChoice=set(), worstChoice=set(), noSilent=True, graphType='png', graphSize='7, 7', relation=None)[source]

export GraphViz dot file for graph drawing filtering.

exportPrincipalImage(Reduced=False, Colwise=False, plotFileName=None, Type='png', TempDir='.', Comments=False)[source]

Export as PNG (default) or PDF the principal projection of the valued relation using the three principal eigen vectors.

Warning

The method, writing and reading temporary files: tempCol.r and rotationCol.csv, resp. tempRow.r and rotationRow.csv, by default in the working directory (./), is hence not safe for multiprocessing programs, unless a temporary dirctory is provided

flatChoice(ch, Debug=False)[source]

Converts set or list ch recursively to a flat list of items.

forcedBestSingleChoice()[source]

Renders the set of most determined outranking singletons in self.

gammaSets()[source]

Renders the dictionary of neighborhoods {node: (dx,ax)} with set dx gathering the dominated, and set ax gathering the absorbed neighborhood.

generateAbsPreKernels()[source]

Generate all absorbent prekernels from independent choices generator.

generateDomPreKernels()[source]

Generate all dominant prekernels from independent choices generator.

graphDetermination(Normalized=True)[source]

Output: average normalized (by default) arc determination:

averageDeterm = ( sum_(x,y) [ abs( relf-relation[x][y] - Med )] / n ) / [( Max-Med ) if Normalized],

where Med = self.valuationdomain[‘med’] and Max = self.valuationdomain[‘max’].

htmlRelationMap(tableTitle='Relation Map', relationName='r(x R y)', actionsSubset=None, rankingRule='Copeland', symbols=['+', '&middot;', '&nbsp;', '-', '_'], Colored=True, ContentCentered=True)[source]

renders the relation map in actions X actions html table format.

htmlRelationTable(tableTitle='Valued Relation Table', relationName='r(x R y)', hasIntegerValues=False, actionsSubset=None, isColored=False)[source]

renders the relation valuation in actions X actions html table format.

inDegrees()[source]

renders the median cut indegrees

inDegreesDistribution()[source]

Renders the distribution of indegrees.

independentChoices(U)[source]

Generator for all independent choices with neighborhoods of a bipolar valued digraph:

Note

  • Initiate with U = self.singletons().
  • Yields [(independent choice, domnb, absnb, indnb)].
inner_prod(v1, v2)[source]

Parameters: two choice characteristic vectors Renders the inner product of two characteristic vetors.

intstab(choice)[source]

Computes the independence degree of a choice.

irreflex(mat)[source]

Puts diagonal entries of mat to valuationdomain[‘min’]

isComplete(Debug=False)[source]

checks the completeness property of self.relation by checking for the absence of a link between two actions!!

Warning

The reflexive links are ignored !!

isCyclic(Debug=False)[source]

checks the cyclicity of self.relation by checking for a reflexive loop in its transitive closure !! self.relation is supposed to be irreflexive !!

isWeaklyComplete(Debug=False)[source]

checks the weakly completeness property of self.relation by checking for the absence of a link between two actions!!

Warning

The reflexive links are ignored !!

iterateRankingByChoosing(Odd=False, CoDual=False, Comments=True, Debug=False, Limited=None)[source]

Renders a ranking by choosing result when progressively eliminating all chordless (odd only) circuits with rising valuation cut levels.

Parameters
CoDual = False (default)/True Limited = proportion (in [0,1]) * (max - med) valuationdomain
kChoices(A, k)[source]

Renders all choices of length k from set A

matmult2(m, v)[source]

Parameters: digraph relation and choice characteristic vector matrix multiply vector by inner production

meanDegree()[source]

Renders the mean degree of self. !!! self.size must be set previously !!!

meanLength(Oriented=False)[source]

Renders the (by default non-oriented) mean neighbourhoor depth of self. !!! self.order must be set previously !!!

minimalChoices(S)[source]

Generates all dominant or absorbent choices of a bipolar valued digraph.

minimalValuationLevelForCircuitsElimination(Odd=True, Debug=False, Comments=False)[source]

renders the minimal valuation level <lambda> that eliminates all self.circuitsList stored odd chordless circuits from self.

Warning

The <lambda> level polarised may still contain newly appearing chordless odd circuits !

neighbourhoodCollection(Oriented=False, Potential=False)[source]

Renders the neighbourhood.

neighbourhoodDepthDistribution(Oriented=False)[source]

Renders the distribtion of neighbourhood depths.

notGammaSets()[source]

Renders the dictionary of neighborhoods {node: (dx,ax)} with set dx gathering the not dominated, and set ax gathering the not absorbed neighborhood.

notaneighbors(node)[source]

Renders the set of absorbed not in-neighbors of a node.

notdneighbors(node)[source]

Renders the set of not dominated out-neighbors of a node.

omax(L, Debug=False)[source]

Epistemic disjunction for bipolar outranking characteristics computation.

omin(L, Debug=False)[source]

Epistemic conjunction for bipolar outranking characteristics computation.

outDegrees()[source]

renders the median cut outdegrees

outDegreesDistribution()[source]

Renders the distribution of outdegrees.

plusirredundant(U)[source]

Generates all +irredundant choices of a digraph.

powerset(U)[source]

Generates all subsets of a set.

readPerrinMisset(file)[source]

read method for 0-1-char-coded MISs from perrinMIS.c curd.dat file.

readPerrinMissetOpt(file)[source]

read method for 0-1-char-coded MISs from perrinMIS.c curd.dat file.

readabsvector(x, relation)[source]

Parameter: action x absorbent in vector.

readdomvector(x, relation)[source]

Parameter: action x dominant out vector.

recodeValuation(newMin=-1.0, newMax=1.0, Debug=False)[source]

Recodes the characteristic valuation domain according to the parameters given.

Note

Default values gives a normalized valuation domain

relationFct(x, y)[source]

wrapper for self.relation dictionary access to ensure interoperability with the sparse and big outranking digraph implementation model.

save(fileName='tempdigraph', option=None, DecimalValuation=True, decDigits=2)[source]

Persistent storage of a Digraph class instance in the form of a python source code file

saveCSV(fileName='tempdigraph', Normalized=False, Dual=False, Converse=False, Diagonal=False, Debug=False)[source]

Persistent storage of a Digraph class instance in the form of a csv file.

saveXMCDA(fileName='temp', relationName='R', category='random', subcategory='valued', author='digraphs Module (RB)', reference='saved from Python', valuationType='standard', servingD3=False)[source]

save digraph in XMCDA format.

saveXMCDA2(fileName='temp', fileExt='xmcda2', Comments=True, relationName='R', relationType='binary', category='random', subcategory='valued', author='digraphs Module (RB)', reference='saved from Python', valuationType='standard', digits=2, servingD3=False)[source]

save digraph in XMCDA format.

saveXML(name='temp', category='general', subcategory='general', author='digraphs Module (RB)', reference='saved from Python')[source]

save digraph in XML format.

savedre(name='temp')[source]

save digraph in nauty format.

sharp(x, y)[source]

Paramaters: choice characteristic values. Renders the sharpest of two characteristic values x and y.

sharpvec(v, w)[source]

Paramaters: choice characteristic vectors. Renders the sharpest of two characteristic vectors v and w.

showActions()[source]

presentation methods for digraphs actions

showAll()[source]
showAutomorphismGenerators()[source]

Renders the generators of the automorphism group.

showBadChoices(Recompute=True)[source]

Characteristic values for potentially bad choices.

showChoiceVector(ch, ChoiceVector=True)[source]

Show procedure for annotated bipolar choices.

showChordlessCircuits()[source]

show methods for (chordless) circuits in a Digraph. Dummy for showCircuits().

showCircuits()[source]

show methods for circuits observed in a Digraph instance.

showComponents()[source]
showGoodChoices(Recompute=True)[source]

Characteristic values for potentially good choices.

showHTMLRelationMap(actionsList=None, rankingRule='Copeland', Colored=True, tableTitle='Relation Map', relationName='r(x S y)', symbols=['+', '&middot;', '&nbsp;', '&#150;', '&#151'])[source]

Launches a browser window with the colored relation map of self. See corresponding Digraph.showRelationMap() method.

Example:

>>> from outrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=25,seed=1)
>>> g = BipolarOutrankingDigraph(t,Normalized=True)
>>> gcd = ~(-g)  # strict outranking relation
>>> gcd.showHTMLRelationMap(rankingRule="netFlows")
Browser view of a relation map
showHTMLRelationTable(actionsList=None, IntegerValues=False, Colored=True, tableTitle='Valued Adjacency Matrix', relationName='r(x S y)')[source]

Launches a browser window with the colored relation table of self.

showInteractiveGraph()[source]

Save the graph and all needed files for the visualization of an interactive graph generated by the exportD3() function. For best experience make sure to use Firefox, because other browser restrict the loading of local files.

showMIS(withListing=True)[source]
Prints all maximal independent choices:
Result in self.misset.
showMIS_AH(withListing=True)[source]

Prints all MIS using the Hertz method.

Result saved in self.hertzmisset.

showMIS_HB2(withListing=True)[source]

Prints all MIS using the Hertz-Bisdorff method.

Result saved in self.newmisset.

showMIS_RB(withListing=True)[source]

Prints all MIS using the Bisdorff method.

Result saved in self.newmisset.

showMIS_UD(withListing=True)[source]

Prints all MIS using the Hertz-Bisdorff method.

Result saved in self.newmisset.

showMaxAbsIrred(withListing=True)[source]
Computing maximal -irredundant choices:
Result in self.absirset.
showMaxDomIrred(withListing=True)[source]
Computing maximal +irredundant choices:
Result in self.domirset.
showMinAbs(withListing=True)[source]
Prints minimal absorbent choices:
Result in self.absset.
showMinDom(withListing=True)[source]
Prints all minimal dominant choices:
Result in self.domset.
showNeighborhoods()[source]

Lists the gamma and the notGamma function of self.

showOrbits(InChoices, withListing=True)[source]

Prints the orbits of Choices along the automorphisms of the digraph self.

showOrbitsFromFile(InFile, withListing=True)[source]

Prints the orbits of Choices along the automorphisms of the digraph self by reading in the 0-1 misset file format.

showPreKernels(withListing=True)[source]
Printing dominant and absorbent preKernels:
Result in self.dompreKernels and self.abspreKernels
showRankingByBestChoosing(rankingByBestChoosing=None)[source]

A show method for self.rankinByBestChoosing result.

Warning

The self.computeRankingByBestChoosing(CoDual=False/True) method instantiating the self.rankingByBestChoosing slot is pre-required !

showRankingByChoosing(rankingByChoosing=None)[source]

A show method for self.rankinByChoosing result.

Warning

The self.computeRankingByChoosing(CoDual=False/True) method instantiating the self.rankingByChoosing slot is pre-required !

showRankingByLastChoosing(rankingByLastChoosing=None, Debug=None)[source]

A show method for self.rankinByChoosing result.

Warning

The self.computeRankingByLastChoosing(CoDual=False/True) method instantiating the self.rankingByChoosing slot is pre-required !

showRelation()[source]

prints the relation valuation in ##.## format.

showRelationMap(symbols=None, rankingRule='Copeland')[source]

Prints on the console, in text map format, the location of certainly validated and certainly invalidated outranking situations.

By default, symbols = {‘max’:’┬’,’positive’: ‘+’, ‘median’: ‘ ‘,
‘negative’: ‘-‘, ‘min’: ‘┴’}

The default ordering of the output is following the Copeland ranking rule from best to worst actions. Further available ranking rules are net flows (rankingRule=”netFlows”), Kohler’s (rankingRule=”kohler”), and Tideman’s ranked pairs rule (rankingRule=”rankedPairs”).

Example:

>>> from outrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=25,seed=1)
>>> g = BipolarOutrankingDigraph(t,Normalized=True)
>>> gcd = ~(-g)  # strict outranking relation
>>> gcd.showRelationMap(rankingRule="netFlows")
 -   ++++++++  +++++┬+┬┬+
- -   + +++++ ++┬+┬+++┬++
┴+  ┴ + ++  ++++┬+┬┬++┬++
-   ++ - ++++-++++++┬++┬+
   - - - ++- ┬- + -+┬+-┬┬
-----  -      -┬┬┬-+  -┬┬
----    --+-+++++++++++++
-- --+- --++ ++ +++-┬+-┬┬
----  -  -+-- ++--+++++ +
----- ++- --- +---++++┬ +
-- -- ---+ -++-+++-+ +-++
-- --┴---+  + +-++-+ -  +
---- ┴---+-- ++--++++ - +
  --┴┴--  --- -  --+ --┬┬
 ---------+--+ ----- +-┬┬
-┴---┴- ---+- + ---+++┬ +
-┴┴--┴---+--- ++ -++--+++
-----┴--- ---+-+- ++---+ 
-┴┴--------------- --++┬ 
--┴---------------- --+┬ 
┴--┴┴ -┴--┴┴-┴ --++  ++-+
----┴┴--------------- -  
┴┴┴----+-┴+┴---┴-+---+ ┴+
┴┴-┴┴┴-┴- - -┴┴---┴┴+ ┬ -
----┴┴-┴-----┴┴---  - -- 
Ranking rule: netFlows
>>> 
showRelationTable(Sorted=True, IntegerValues=False, actionsSubset=None, relation=None, ndigits=2, ReflexiveTerms=True)[source]

prints the relation valuation in actions X actions table format.

showRubisBestChoiceRecommendation(Comments=False, ChoiceVector=False, CoDual=True, Debug=False, _OldCoca=False, BrokenCocs=True, Cpp=False)[source]

Renders the RuBis best choice recommendation.

Note

Computes by default the Rubis best choice recommendation on the corresponding strict (codual) outranking digraph.

In case of chordless circuits, if supporting arcs are more credible than the reversed negating arcs, we collapse the circuits into hyper nodes. Inversely, if supporting arcs are not more credible than the reversed negating arcs, we brake the circuits on their weakest arc.

Usage example:

>>> from outrankingDigraphs import *
>>> t = Random3ObjectivesPerformanceTableau(seed=5)
>>> g = BipolarOutrankingDigraph(t)
>>> g.showRubisBestChoiceRecommendation()
***********************
RuBis Best Choice Recommendation (BCR)
(in decreasing order of determinateness)   
Credibility domain:  [-100.0, 100.0]
=== >> potential vest choices
* choice              : ['a04', 'a14', 'a19', 'a20']
   +-irredundancy      : 1.19
   independence        : 1.19
   dominance           : 4.76
   absorbency          : -59.52
   covering (%)        : 75.00
   determinateness (%) : 57.86
   - most credible action(s) = { 'a14': 23.81, 'a19': 11.90, 'a04': 2.38, 'a20': 1.19, }  
=== >> potential worst choices 
* choice              : ['a03', 'a12', 'a17']
   +-irredundancy      : 4.76
  independence        : 4.76
  dominance           : -76.19
  absorbency          : 4.76
  covering (%)        : 0.00
  determinateness (%) : 65.39
  - most credible action(s) = { 'a03': 38.10, 'a12': 13.10, 'a17': 4.76, }
Execution time: 0.024 seconds
*****************************
showRubyChoice(Comments=False, _OldCoca=True)[source]

dummy for showRubisBestChoiceRecommendation() older versions compatibility

showShort()[source]

concise presentation method for genuine digraphs.

showSingletonRanking(Comments=True, Debug=False)[source]

Calls self.computeSingletonRanking(comments=True,Debug = False). Renders and prints the sorted bipolar net determinatation of outrankingness minus outrankedness credibilities of all singleton choices.

res = ((netdet,sigleton,dom,absorb)+)

showStatistics()[source]

Computes digraph statistics like order, size and arc-density.

showdre()[source]

Shows relation in nauty format.

singletons()[source]

list of singletons and neighborhoods [(singx1, +nx1, -nx1, not(+nx1 or -nx1)),.... ]

sizeSubGraph(choice)[source]

Output: (size, undeterm,arcDensity). Renders the arc density of the induced subgraph.

strongComponents(setPotential=False)[source]

Renders the set of strong components of self.

symDegreesDistribution()[source]

Renders the distribution of symmetric degrees.

topologicalSort(Debug=False)[source]

If self is acyclic, adds topological sort number to each node of self and renders ordered list of nodes. Otherwise renders None. Source: M. Golumbic Algorithmic Graph heory and Perfect Graphs, Annals Of Discrete Mathematics 57 2nd Ed. , Elsevier 2004, Algorithm 2.4 p.44.

weakAneighbors(node)[source]

Renders the set of absorbed in-neighbors of a node.

weakCondorcetWinners()[source]

Renders the set of decision actions x such that self.relation[x][y] >= self.valuationdomain[‘med’] for all y != x.

weakDneighbors(node)[source]

Renders the set of dominated out-neighbors of a node.

weakGammaSets()[source]

Renders the dictionary of neighborhoods {node: (dx,ax)}

worstRanks()[source]

renders worst possible ranks from outdegrees account

zoomValuation(zoomFactor=1.0)[source]

Zooms in or out, depending on the value of the zoomFactor provided, the bipolar valuation of a digraph.

class digraphs.DualDigraph(other)[source]

Bases: digraphs.Digraph

Instantiates the dual ( = negated valuation) Digraph object from a deep copy of a given other Digraph instance.

The relation constructor returns the dual of self.relation with generic formula:
relationOut[a][b] = Max - self.relation[a][b] + Min where Max (resp. Min) equals valuation maximum (resp. minimum).

Note

In a bipolar valuation, the dual operator correspond to a simple changing of signs.

class digraphs.EmptyDigraph(order=5, valuationdomain=(-1.0, 1.0))[source]

Bases: digraphs.Digraph

Parameters:
order > 0 (default=5); valuationdomain =(Min,Max).

Specialization of the general Digraph class for generating temporary empty graphs of given order in {-1,0,1}.

class digraphs.EquivalenceDigraph(d1, d2, Debug=False)[source]

Bases: digraphs.Digraph

Instantiates the logical equivalence digraph of two bipolar digraphs d1 and d2 of same order. Returns None if d1 and d2 are of different order

computeCorrelation()[source]

Renders the global bipolar correlation index resulting from the pairwise equivalence valuations.

class digraphs.FusionDigraph(dg1, dg2, operator='o-min')[source]

Bases: digraphs.Digraph

Instantiates the epistemic fusion of two given Digraph instances called dg1 and dg2.

Parameter:

  • operator = “o-min” | “o-max” (epistemic conjunctive or dijunctive fusion)
class digraphs.FusionLDigraph(L, operator='o-min')[source]

Bases: digraphs.Digraph

Instantiates the epistemic fusion a list L of Digraph instances.

Parameter:

  • operator = “o-min” | “o-max” (epistemic conjunctive or dijunctive fusion)
class digraphs.GridDigraph(n=5, m=5, valuationdomain={'min': -1.0, 'max': 1.0}, hasRandomOrientation=False, hasMedianSplitOrientation=False)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary Grid digraphs of dimension n times m.

Parameters:
n,m > 0; valuationdomain ={‘min’:m, ‘max’:M}.
Default instantiation (5 times 5 Grid Digraph):
n = 5, m=5, valuationdomain = {‘min’:-1.0,’max’:1.0}.

Randomly orientable with hasRandomOrientation=True (default=False).

showShort()[source]
class digraphs.IndeterminateDigraph(other=None, order=5, valuationdomain=(-1.0, 1.0))[source]

Bases: digraphs.Digraph

Parameters: order > 0; valuationdomain =(Min,Max). Specialization of the general Digraph class for generating temporary empty graphs of order 5 in {-1,0,1}.

class digraphs.KneserDigraph(n=5, j=2, valuationdomain={'min': -1.0, 'max': 1.0})[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary Kneser digraphs

Parameters:
n > 0; n > j > 0;
valuationdomain ={‘min’:m, ‘max’:M}.
Default instantiation as Petersen graph:
n = 5, j = 2, valuationdomain = {‘min’:-1.0,’max’:1.0}.
showShort()[source]
class digraphs.PolarisedDigraph(digraph=None, level=None, KeepValues=True, AlphaCut=False, StrictCut=False)[source]

Bases: digraphs.Digraph

Renders the polarised valuation of a Digraph class instance:

Parameters:
  • If level = None, a default 75% cut level (0.5 in a normalized [-1,+1] valuation domain) is used.
  • If KeepValues = False, the polarisation results in a three valued crisp result.
  • If AlphaCut = True a genuine one-sided True-oriented cut is operated.
  • If StrictCut = True, the cut level value is excluded resulting in an open polarised valuation domain. By default the polarised valuation domain is closed and the complementary indeterminate domain is open.
class digraphs.Preorder(other, direction='best', ranking=None)[source]

Bases: digraphs.Digraph

Instantiates the associated preorder from a given Digraph called other.

Instantiates as other.__class__ !

Copies the case given the description, the criteria and the evaluation dictionary into self.

class digraphs.RandomTree(numberOfNodes=5, ndigits=2, hasIntegerValuation=True)[source]

Bases: digraphs.Digraph

Warning

Obsolete version! Will be removed in the future. Instead, use the new graphs.RandomTree constructor.

prufer_to_tree(a)[source]
class digraphs.RedhefferDigraph(order=5, valuationdomain=(-1.0, 1.0))[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary Redheffer digraphs.

https://en.wikipedia.org/wiki/Redheffer_matrix

Parameters:
order > 0; valuationdomain=(Min,Max).
class digraphs.StrongComponentsCollapsedDigraph(digraph=None)[source]

Bases: digraphs.Digraph

Reduction of Digraph object to its strong components.

showComponents()[source]
class digraphs.SymmetricPartialDigraph(digraph)[source]

Bases: digraphs.Digraph

Renders the symmetric part of a Digraph instance.

Note

  • The not symmetric and the reflexive links are all put to the median indeterminate characteristics value!.
  • The constructor makes a deep copy of the given Digraph instance!
class digraphs.XMCDA2Digraph(fileName='temp')[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for reading stored XMCDA-2.0 formatted digraphs. Using the inbuilt module xml.etree (for Python 2.5+).

Param:
fileName (without the extension .xmcda).
showAll()[source]
class digraphs.XMCDADigraph(fileName='temp')[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for reading stored XMCDA formatted digraphs. Using the inbuilt module xml.etree (for Python 2.5+).

Param:
fileName (without the extension .xmcda).
showAll()[source]
class digraphs.XMLDigraph(fileName='testsaveXML')[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for reading stored XML formatted digraphs. Using the inbuilt module xml.etree (for Python 2.5+).

Param:
fileName (without the extension .xml).
class digraphs.XMLDigraph24(fileName='testsaveXML')[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for reading stored XML formatted digraphs.

showAll()[source]
class digraphs.XORDigraph(d1, d2, Debug=False)[source]

Bases: digraphs.Digraph

Instantiates the XOR digraph of two bipolar digraphs d1 and d2 of same order.

class digraphs.kChoicesDigraph(digraph=None, k=3)[source]

Bases: digraphs.Digraph

Specialization of general Digraph class for instantiation a digraph of all k-choices collapsed actions.

Parameters:
digraph := Stored or memory resident digraph instance
k := cardinality of the choices

Back to the Installation

randomDigraphs module

class randomDigraphs.RandomDigraph(order=9, arcProbability=0.5, hasIntegerValuation=True, Bipolar=True, seed=None)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary crisp (irreflexive) random crisp digraphs.

Parameters:
  • order (default = 10);
  • arc_probability (in [0.,1.], default=0.5)
  • If Bipolar=True, valuation domain = {-1,1} otherwise = {0,1}
  • Is seed != None, the random generator is seeded
class randomDigraphs.RandomFixedDegreeSequenceDigraph(order=7, degreeSequence=[3, 3, 2, 2, 1, 1, 0], seed=None)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary random crisp graphs (symmetric digraphs) with a fixed sequence of degrees.

Parameters:
order=n and degreeSequence=[degree_1, ... ,degree_n]>

Warning

The implementation is not guaranteeing a uniform choice among all potential valid graph instances.

class randomDigraphs.RandomFixedSizeDigraph(order=7, size=14, seed=None)[source]

Bases: digraphs.Digraph

Generates a random crisp digraph with a fixed size, by instantiating a fixed numbers of arcs from random choices in the set of potential oriented pairs of nodes numbered from 1 to order.

class randomDigraphs.RandomGridDigraph(n=5, m=5, valuationdomain={'min': -1.0, 'max': 1.0}, seed=None, Debug=False)[source]

Bases: digraphs.GridDigraph

Specialization of the general Digraph class for generating temporary randomly oriented Grid digraphs of dimension n time m (default 5x5).

Parameters:
  • n,m > 0;
  • valuationdomain ={‘min’:-1 (default),’max’: 1 (default)}.
class randomDigraphs.RandomRegularDigraph(order=7, degree=2, seed=None)[source]

Bases: digraphs.Digraph

Parameters:
order and degree.

Specialization of Digraph class for random regular symmetric instances.

class randomDigraphs.RandomTournament(order=10, ndigits=2, isCrisp=True, valuationDomain=[-1, 1], seed=None)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary weak tournaments

Parameter:
  • order = n > 0
  • If valuationDomain = None, valuation is normalized (in [-1.0,1.0])
  • If is Crips = True, valuation is polarized to min and max values
class randomDigraphs.RandomValuationDigraph(order=9, ndigits=2, Normalized=False, hasIntegerValuation=False, seed=None)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary uniformly valuated random digraphs.

Parameters:
  • order > 0, number of arcs;
  • ndigits > 0, number of digits if hasIntegerValuation = True; Otherwise, decimal precision.
  • Normalized = True (r in [-1,1], r in [0,1] if False/default);
  • hasIntegerValuation = False (default)
  • If seed != none, the random generator is seeded
Example python3 session:
>>> from digraphs import RandomValuationDigraph
>>> dg = RandomValuationDigraph(order=5,Normalized=True)
>>> dg.showAll()
*----- show detail -------------*
Digraph          : randomValuationDigraph
*---- Actions ----*
['1', '2', '3', '4', '5']
*---- Characteristic valuation domain ----*
{'max': Decimal('1.0'), 'min': Decimal('-1.0'),
 'med': Decimal('0.0'), 'hasIntegerValuation': False}
* ---- Relation Table -----
  S   |  '1'    '2'    '3'    '4'     '5'     
 -----|-----------------------------------
  '1' |  0.00   0.28   0.46  -0.66   0.90    
  '2' | -0.08   0.00  -0.46  -0.42   0.52    
  '3' |  0.84  -0.10   0.00  -0.54   0.58    
  '4' |  0.90   0.88   0.90   0.00  -0.38    
  '5' | -0.50   0.64   0.42  -0.94   0.00    
*--- Connected Components ---*
1: ['1', '2', '3', '4', '5']
Neighborhoods:
  Gamma     :
'4': in => set(), out => {'1', '2', '3'}
'5': in => {'1', '2', '3'}, out => {'2', '3'}
'1': in => {'4', '3'}, out => {'5', '2', '3'}
'2': in => {'4', '5', '1'}, out => {'5'}
'3': in => {'4', '5', '1'}, out => {'5', '1'}
  Not Gamma :
'4': in => {'5', '1', '2', '3'}, out => {'5'}
'5': in => {'4'}, out => {'4', '1'}
'1': in => {'5', '2'}, out => {'4'}
'2': in => {'3'}, out => {'4', '1', '3'}
'3': in => {'2'}, out => {'4', '2'}
>>> dg.exportGraphViz()
_images/randomValuationDigraph.png
class randomDigraphs.RandomWeakTournament(order=10, ndigits=2, hasIntegerValuation=False, weaknessDegree=0.25, seed=None, Comments=False)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating temporary bipolar-valued weak tournaments

Parameters:
  • order = n > 0
  • weaknessDegree in [0.0,1.0]: proportion of indeterminate links (default = 0.25)
  • If hasIntegerValuation = True, valuation domain = [-pow(10,ndigits); + pow(10,ndigits)] else valuation domain = [-1.0,1.0]
  • If seed != None, the random number generator is seeded

Back to the Installation

graphs module

A tutorial with coding examples is available here: Working with the graphs module

class graphs.BestDeterminedSpanningForest(g, seed=None, Debug=False)[source]

Bases: graphs.RandomTree

Constructing the most determined spanning tree (or forest if not connected) using Kruskal’s greedy algorithm on the dual valuation.

Example Python session:
>>> from graphs import *
>>> g = RandomValuationGraph(seed=2)
>>> g.showShort()
*---- short description of the graph ----*
Name             : 'randomGraph'
Vertices         :  ['v1', 'v2', 'v3', 'v4', 'v5']
Valuation domain :  {'med': Decimal('0'), 'min': Decimal('-1'), 'max': Decimal('1')}
Gamma function   : 
v1 -> ['v2', 'v3']
v2 -> ['v4', 'v1', 'v5', 'v3']
v3 -> ['v1', 'v5', 'v2']
v4 -> ['v5', 'v2']
v5 -> ['v4', 'v2', 'v3']
>>> mt = BestDeterminedSpanningForest(g)
>>> mt.exportGraphViz('spanningTree',withSpanningTree=True)
*---- exporting a dot file for GraphViz tools ---------*
Exporting to spanningTree.dot
[['v4', 'v2', 'v1', 'v3', 'v1', 'v2', 'v5', 'v2', 'v4']]
neato -Tpng spanningTree.dot -o spanningTree.png
7-cycle instance
class graphs.CompleteGraph(order=5, seed=None)[source]

Bases: graphs.Graph

Instances of complete graphs bipolarly valuated in {-1,0,+1}. Each vertex x is positively linked to all the other vertices (edges[{x,y}] = +1)

Parameter:
  • order (positive integer)
class graphs.CycleGraph(order=5, seed=None, Debug=False)[source]

Bases: graphs.Graph

Instances of cycle graph characterized in [-1,1].

Parameter:
  • order (positive integer)

Example of 7-cycle graph instance:

7-cycle instance
class graphs.DualGraph(other)[source]

Bases: graphs.Graph

Instantiates the dual Graph object of a given other Graph instance.

The relation constructor returns the dual of self.relation with formula:
relationOut[a][b] = Max - self.relation[a][b] + Min where Max (resp. Min) equals valuation maximum (resp. minimum).
class graphs.EmptyGraph(order=5, seed=None)[source]

Bases: graphs.Graph

Intantiates graph of given order without any positively valued edge.

Parameter:
  • order (positive integer)
class graphs.Graph(fileName=None, Empty=False, numberOfVertices=7, edgeProbability=0.5)[source]

Bases: object

In the graphs module, the root graphs.Graph class provides a generic graph model. A given object consists in:

  1. a vertices dictionary
  2. a characteristic valuation domain, {-1,0,+1} by default
  3. an edges dictionary, characterising each edge in the given valuation domain
  4. a gamma function dictionary, holding the neighborhood vertices of each vertex

General structure:

vertices = {'v1': {'name': ...,'shortName': ...},
            'v2': {'name': ...,'shortName': ...},
            'v3': {'name': ...,'shortName': ...},
            ... }
valuationDomain = {'min': -1, 'med': 0, 'max': 1}
edges = {frozenset({'v1','v2'}): 1,
         frozenset({'v1','v3'}): 1,
         frozenset({'v2','v3'}): -1,
           ...}
## links from each vertex to its neighbors
gamma = {'v1': {'v2',v3'}, 'v2': {'v1'}, 'v3': {'v1'}, ... }
Example python3 session:
>>> from graphs import Graph
>>> g = Graph(numberOfVertices=5,edgeProbability=0.5) # random instance
>>> g.showShort()
*----- show short --------------*
*---- short description of the graph ----*
Name             :  'random'
Vertices         :  ['v1', 'v2', 'v3', 'v4', 'v5']
Valuation domain :  {'med': 0, 'max': 1, 'min': -1}
Gamma function   :
v1 -> ['v4']
v2 -> []
v3 -> ['v4']
v4 -> ['v1', 'v3']
v5 -> []
computeChordlessCycles(Cycle3=False, Comments=False, Debug=False)[source]

Renders the set of all chordless cycles observed in a Graph intance. Inspired from Dias, Castonguay, Longo & Jradi, Algorithmica 2015.

Note

By default, a chordless cycle must have at least length 4.If the Cycle3 flag is set to True, the cyclicly closed triplets will be inserted as 3-cycles in the result.

computeCliques(Comments=False)[source]

Computes all cliques, ie maximal complete subgraphs in self:

Note

  • Computes the maximal independent vertex sets in the dual of self.
  • Result is stored in self.cliques.
computeComponents()[source]

Computes the connected components of a graph instance. Returns a partition of the vertices as a list

computeDegreeDistribution(Comments=False)[source]

Renders the distribution of vertex degrees.

computeDiameter(Oriented=False)[source]

Renders the diameter (maximal neighbourhood depth) of the digraph instance.

Note

The diameter of a disconnected graph is considered to be infinite (results in a value -1) !

computeMIS(Comments=False)[source]

Prints all maximal independent vertex sets:

Note

  • Result is stored in self.misset !
computeNeighbourhoodDepth(vertex, Debug=False)[source]

Renders the distribtion of neighbourhood depths.

computeNeighbourhoodDepthDistribution(Comments=False, Debug=False)[source]

Renders the distribtion of neighbourhood depths.

computeSize()[source]

Renders the number of positively characterised edges of this graph instance (result is stored in self.size).

depthFirstSearch(Debug=False)[source]

Depth first search through a graph in lexicographical order of the vertex keys.

exportGraphViz(fileName=None, verticesSubset=None, noSilent=True, graphType='png', graphSize='7, 7', withSpanningTree=False, layout=None, arcColor='black', lineWidth=1)[source]

Exports GraphViz dot file for graph drawing filtering.

Example:
>>> g = Graph(numberOfVertices=5,edgeProbability=0.3)
>>> g.exportGraphViz('randomGraph'))
Random graph
gammaSets(Debug=False)[source]

renders the gamma function as dictionary

generateIndependent(U)[source]

Generator for all independent vertices sets with neighborhoods of a graph instance:

Note

  • Initiate with U = self._singletons().
  • Yields [independent set, covered set, all vertices - covered set)].
  • If independent set == (all vertices - covered set), the given independent set is maximal !
graph2Digraph()[source]

Converts a Graph object into a symmetric Digraph object.

isConnected()[source]

Cheks if self is a connected graph instance.

isTree()[source]

Checks if self is a tree by verifing the required number of edges: order-1; and the existence of leaves.

randomDepthFirstSearch(seed=None, Debug=False)[source]

Depth first search through a graph in random order of the vertex keys.

Note

The resulting spanning tree (or forest) is by far not uniformly selected among all possible trees. Spanning stars will indeed be much less probably selected then streight walks !

recodeValuation(newMin=-1, newMax=1, Debug=False)[source]

Recodes the characteristic valuation domain according to the parameters given.

Note

Default values gives a normalized valuation domain

save(fileName='tempGraph', Debug=False)[source]

Persistent storage of a Graph class instance in the form of a python source code file.

setEdgeValue(edge, value, Comments=False)[source]

Wrapper for updating the charactreistic valuation of a Graph instance. The egde parameter consists in a pair of vertices; edge = (‘v1’,’v2’) for instance. The new value must be in the limits of the valuation domain.

showCliques()[source]
showMIS()[source]
showMore()[source]

Generic show method for Graph instances.

showShort()[source]

Generic show method for Graph instances.

class graphs.GridGraph(n=5, m=5, valuationMin=-1, valuationMax=1)[source]

Bases: graphs.Graph

Specialization of the general Graph class for generating temporary Grid graphs of dimension n times m.

Parameters:
  • n,m > 0
  • valuationDomain ={‘min’:-1, ‘med’:0, ‘max’:+1}
Default instantiation (5 times 5 Grid Digraph):
  • n = 5,
  • m=5,
  • valuationDomain = {‘min’:-1.0,’max’:1.0}.

Example of 5x5 GridGraph instance:

5x5 grid instance
showShort()[source]
class graphs.IsingModel(g, beta=0, nSim=None, Debug=False)[source]

Bases: graphs.Graph

Specialisation of a Gibbs Sampler for the Ising model

Example:
>>> from graphs import GridGraph, IsingModel
>>> g = GridGraph(n=15,m=15)
>>> g.showShort()
*----- show short --------------*
Grid graph    :  grid-6-6
n             :  6
m             :  6
order         :  36
>>> im = IsingModel(g,beta=0.3,nSim=100000,Debug=False)
Running a Gibbs Sampler for 100000 step !
>>> im.exportGraphViz(colors=['lightblue','lightcoral'])
*---- exporting a dot file for GraphViz tools ---------*
Exporting to grid-15-15-ising.dot
fdp -Tpng grid-15-15-ising.dot -o grid-15-15-ising.png
ising configuration of a 15x15 grid with beta=0.3
computeSpinEnergy()[source]

Spin energy H(c) of a spin configuration is H(c) = -sum_{{x,y} in self.edges}[spin_c(x)*spin_c(y)]

exportGraphViz(fileName=None, noSilent=True, graphType='png', graphSize='7,7', edgeColor='black', colors=['gold', 'lightblue'])[source]

Exports GraphViz dot file for Ising models drawing filtering.

generateSpinConfiguration(beta=0, nSim=None, Debug=False)[source]
class graphs.MISModel(g, nSim=None, maxIter=20, seed=None, Debug=False)[source]

Bases: graphs.Graph

Specialisation of a Gibbs Sampler for the hard code model, that is a random MIS generator.

Example:
>>> from graphs import MISModel
>>> from digraphs import CirculantDigraph        
>>> dg = CirculantDigraph(order=15)
>>> g = dg.digraph2Graph()
>>> g.showShort()
*---- short description of the graph ----*
Name             : 'c15'
Vertices         :  ['1', '10', '11', '12', '13', '14',
                     '15', '2', '3', '4', '5', '6', '7',
                     '8', '9']
Valuation domain :  {'med': 0, 'min': -1, 'max': 1}
Gamma function   : 
1 -> ['2', '15']
10 -> ['11', '9']
11 -> ['10', '12']
12 -> ['13', '11']
13 -> ['12', '14']
14 -> ['15', '13']
15 -> ['1', '14']
2 -> ['1', '3']
3 -> ['2', '4']
4 -> ['3', '5']
5 -> ['6', '4']
6 -> ['7', '5']
7 -> ['6', '8']
8 -> ['7', '9']
9 -> ['10', '8']
>>> mis = MISModel(g)
Running a Gibbs Sampler for 1050 step !
>>> mis.checkMIS()
{'2','4','7','9','11','13','15'}  is maximal !
>>> mis.exportGraphViz()
*---- exporting a dot file for GraphViz tools ---------*
Exporting to c15-mis.dot
fdp -Tpng c15-mis.dot -o c15-mis.png
15-cycle with colored MIS
checkMIS(Comments=True)[source]

Verify maximality of independent set.

Note

Returns three sets: an independent choice, the covered vertices, and the remaining uncovered vertices. When the last set is empty, the independent choice is maximal.

exportGraphViz(fileName=None, noSilent=True, graphType='png', graphSize='7, 7', misColor='lightblue')[source]

Exports GraphViz dot file for MIS models drawing filtering.

generateMIS(Reset=True, nSim=None, seed=None, Comments=True, Debug=False)[source]
class graphs.MetropolisChain(g, probs=None)[source]

Bases: graphs.Graph

Specialisation of the graph class for implementing a generic Metropolis Markov Chain Monte Carlo sampler with a given probability distribution probs = {‘v1’: x, ‘v2’: y, ...}

Usage example:
>>> from graphs import *
>>> g = Graph(numberOfVertices=5,edgeProbability=0.5)
>>> g.showShort()
*---- short description of the graph ----*
Name             : 'randomGraph'
Vertices         :  ['v1', 'v2', 'v3', 'v4', 'v5']
Valuation domain :  {'max': 1, 'med': 0, 'min': -1}
Gamma function   : 
v1 -> ['v2', 'v3', 'v4']
v2 -> ['v1', 'v4']
v3 -> ['v5', 'v1']
v4 -> ['v2', 'v5', 'v1']
v5 -> ['v3', 'v4']        
>>> probs = {}
>>> n = g.order
>>> i = 0
>>> verticesList = [x for x in g.vertices]
>>> verticesList.sort()
>>> for v in verticesList:
...     probs[v] = (n - i)/(n*(n+1)/2)
...     i += 1
>>> met = MetropolisChain(g,probs)
>>> frequency = met.checkSampling(verticesList[0],nSim=30000)
>>> for v in verticesList:
...     print(v,probs[v],frequency[v])
v1 0.3333 0.3343
v2 0.2666 0.2680
v3 0.2    0.2030 
v4 0.1333 0.1311
v5 0.0666 0.0635
>>> met.showTransitionMatrix()
* ---- Transition Matrix -----
  Pij  | 'v1'    'v2'    'v3'    'v4'    'v5'     
  -----|-------------------------------------
  'v1' |  0.23   0.33    0.30    0.13    0.00    
  'v2' |  0.42   0.42    0.00    0.17    0.00    
  'v3' |  0.50   0.00    0.33    0.00    0.17    
  'v4' |  0.33   0.33    0.00    0.08    0.25    
  'v5' |  0.00   0.00    0.50    0.50    0.00    
MCMCtransition(si, Debug=False)[source]
checkSampling(si, nSim)[source]
computeTransitionMatrix()[source]
saveCSVTransition(fileName='transition', Debug=False)[source]

Persistent storage of the transition matrix in the form of a csv file.

showTransitionMatrix(Sorted=True, IntegerValues=False, vertices=None, relation=None, ndigits=2, ReflexiveTerms=True)[source]

Prints on stdout the transition probabilities in vertices X vertices table format.

class graphs.Q_Coloring(g, colors=['gold', 'lightcoral', 'lightblue'], nSim=None, maxIter=20, seed=None, Comments=True, Debug=False)[source]

Bases: graphs.Graph

Generate a q-coloring of a Graph instance via a Gibbs MCMC sampler in nSim simulation steps (default = len(graph.edges)).

Example 3-coloring of a grid 6x6 :
>>> from graphs import *
>>> g = GridGraph(n=6,m=6)
>>> g.showShort()
>>> g.exportGraphViz()
*----- show short --------------*
Grid graph    :  grid-6-6
n             :  6
m             :  6
order         :  36
>>> qc = Q_Coloring(g,colors=['gold','lightblue','lightcoral'])
Running a Gibbs Sampler for 630 step !
>>> qc.checkFeasibility()
The q-coloring with 3 colors is feasible !!
>>> qc.exportGraphViz()
*---- exporting a dot file for GraphViz tools ---------*
Exporting to grid-6-6-qcoloring.dot
fdp -Tpng grid-6-6-qcoloring.dot -o grid-6-6-qcoloring.png
3 coloring of a 6x6 grid
checkFeasibility(Comments=True, Debug=False)[source]
exportGraphViz(fileName=None, noSilent=True, graphType='png', graphSize='7, 7', layout=None)[source]

Exports GraphViz dot file for q-coloring drawing filtering.

The graph drawing layout is depending on the graph type, but can be forced to either ‘fdp’, ‘circo’ or ‘neato’ with the layout parameter.

Example:
>>> g = Graph(numberOfVertices=10,edgeProbability=0.4)
>>> g.showShort()
*---- short description of the graph ----*
Name : 'randomGraph'
Vertices :  ['v1','v10','v2','v3','v4','v5','v6','v7','v8','v9']
Valuation domain :  {'max': 1, 'min': -1, 'med': 0}
Gamma function   : 
v1 -> ['v7', 'v2', 'v3', 'v5']
v10 -> ['v4']
v2 -> ['v1', 'v7', 'v8']
v3 -> ['v1', 'v7', 'v9']
v4 -> ['v5', 'v10']
v5 -> ['v6', 'v7', 'v1', 'v8', 'v4']
v6 -> ['v5', 'v8']
v7 -> ['v1', 'v5', 'v8', 'v2', 'v3']
v8 -> ['v6', 'v7', 'v2', 'v5']
v9 -> ['v3']
>>> qc = Q_Coloring(g,nSim=1000)
Running a Gibbs Sampler for 1000 step !
>>> qc.checkFeasibility()
The q-coloring with 3 colors is feasible !!
>>> qc.exportGraphViz()
*---- exporting a dot file for GraphViz tools ---------*
Exporting to randomGraph-qcoloring.dot
fdp -Tpng randomGraph-qcoloring.dot -o randomGraph-qcoloring.png
3-coloring of a random graph
generateFeasibleConfiguration(Reset=True, nSim=None, seed=None, Debug=False)[source]
showConfiguration()[source]
class graphs.RandomFixedDegreeSequenceGraph(order=7, degreeSequence=[3, 3, 2, 2, 1, 1, 0], seed=None)[source]

Bases: graphs.Graph

Specialization of the general Graph class for generating temporary random graphs with a fixed sequence of degrees.

Warning

The implementation is not guaranteeing a uniform choice among all potential valid graph instances.

class graphs.RandomFixedSizeGraph(order=7, size=14, seed=None, Debug=False)[source]

Bases: graphs.Graph

Generates a random graph with a fixed size (number of edges), by instantiating a fixed numbers of arcs from random choices in the set of potential pairs of vertices numbered from 1 to order.

class graphs.RandomGraph(order=5, edgeProbability=0.4, seed=None)[source]

Bases: graphs.Graph

Random instances of the Graph class

Parameters:
  • order (positive integer)
  • edgeProbability (in [0,1])
class graphs.RandomRegularGraph(order=7, degree=2, seed=None)[source]

Bases: graphs.Graph

Specialization of the general Graph class for generating temporary random regular graphs of fixed degrees.

class graphs.RandomSpanningForest(g, seed=None, Debug=False)[source]

Bases: graphs.RandomTree

Random instance of a spanning forest (one or more trees) generated from a random depth first search graph g traversal.

randomSpanningForest instance
class graphs.RandomSpanningTree(g, seed=None, Debug=False)[source]

Bases: graphs.RandomTree

Uniform random instance of a spanning tree generated with Wilson’s algorithm from a connected Graph g instance.

Note

Wilson’s algorithm only works for connecte graphs.

randomSpanningTree instance
class graphs.RandomTree(order=None, vertices=None, prueferCode=None, seed=None, Debug=False)[source]

Bases: graphs.Graph

Instance of a tree generated from a random (or a given) Prüfer code.

radomTree instance
tree2Pruefer(vertices=None, Debug=False)[source]

Renders the Pruefer code of a given tree.

class graphs.RandomValuationGraph(order=5, ndigits=2, seed=None)[source]

Bases: graphs.Graph

Specialization of the genuine Graph class for generating temporary randomly valuated graphs in the range [-1.0;1.0].

Parameter:
  • order (positive integer)
  • ndigits (decimal precision)
class graphs.SnakeGraph(p, q)[source]

Bases: graphs.GridGraph

Snake graphs S(p/q) are made up of all the integer grid squares between the lower and upper Christofel paths of the rational number p/q, where p and q are two coprime integers such that 0 <= p <= q, i.e. p/q gives an irreducible ratio between 0 and 1.

Reference: M. Aigner, Markov’s Theorem and 100 Years of the Uniqueness Conjecture, Springer, 2013, p. 141-149

S(4/7) snake graph instance:

>>> from graphs import SnakeGraph
>>> s4_7 = SnakeGraph(p=4,q=7)
>>> s4_7.showShort()
*---- short description of the snake graph ----*
Name             : 'snakeGraph'
Rational p/q     : 4/7
Christoffel words:
Upper word       :  BBABABA
Lower word       :  ABABABB
>>> s4_7.exportGraphViz('4_7_snake',lineWidth=3,arcColor='red')
4/7 snake graph instance
showShort(WithVertices=False)[source]

Show method for SnakeGraph instances.

class graphs.TriangulatedGrid(n=5, m=5, valuationMin=-1, valuationMax=1)[source]

Bases: graphs.Graph

Specialization of the general Graph class for generating temporary triangulated grids of dimension n times m.

Parameters:
  • n,m > 0
  • valuationDomain = {‘min’:m, ‘max’:M}

Example of 5x5 triangulated grid instance:

triangulated 5x5 grid
showShort()[source]

Back to the Installation

perfTabs module

class perfTabs.ConstantPerformanceTableau(inPerfTab, actionsSubset=None, criteriaSubset=None, position=0.5)[source]

Bases: perfTabs.PerformanceTableau

Constructor for (partially) constant performance tableaux.

Parameter:

  • actionsSubset selects the actions to be set at equal constant performances,
  • criteriaSubset select the concerned subset of criteria,
  • The position parameter (default = median performance) selects the constant performance in the respective scale of each performance criterion.
class perfTabs.NormalizedPerformanceTableau(argPerfTab=None, lowValue=0, highValue=100, coalition=None, Debug=False)[source]

Bases: perfTabs.PerformanceTableau

specialsation of the PerformanceTableau class for constructing normalized, 0 - 100, valued PerformanceTableau instances from a given argPerfTab instance.

class perfTabs.OldXMCDAPerformanceTableau(fileName='temp')[source]

Bases: perfTabs.PerformanceTableau

Specialization of the general PerformanceTableau class for reading stored XMCDA formatted instances. Using the inbuilt module xml.etree (for Python 2.5+).

Param: fileName (without the extension .xml or .xmcda).

class perfTabs.PartialPerformanceTableau(inPerfTab, actionsSubset=None, criteriaSubset=None, objectivesSubset=None)[source]

Bases: perfTabs.PerformanceTableau

Constructor for partial performance tableaux concerning a subset of actions and/or criteria and/or objectives

class perfTabs.PerformanceTableau(filePerfTab=None, isEmpty=False)[source]

Bases: object

In this Digraph3 module, the root perfTabs.PerformanceTableau class provides a generic performance table model. A given object of this class consists in:

  1. a set of potential decision actions : an ordered dictionary describing the potential decision actions or alternatives with ‘name’ and ‘comment’ attributes,
  2. an optional set of decision objectives: an ordered dictionary with name, comment, weight and list of concerned criteria per objective,
  3. a coherent family of criteria: a ordered dictionary of criteria functions used for measuring the performance of each potential decision action with respect to the preference dimension captured by each criterion,
  4. the evaluations: a dictionary of performance evaluations for each decision action or alternative on each criterion function.

Structure:

actions = OrderedDict([('a1', {'name': ..., 'comment': ...}),
           ('a2', {'name': ..., 'comment': ...}),
           ...])
objectives = OrderedDict([
            ('obj1', {'name': ..., 'comment': ..., 'weight': ..., 'criteria': ['g1', ...]}),
            ('obj2', {'name': ..., 'comment', ..., 'weight': ..., 'criteria': ['g2', ...]}),
            ...])
criteria = OrderedDict([
     ('g1', {'weight':Decimal("3.00"),
             'scale': (Decimal("0.00"),Decimal("100.00")),
             'thresholds' : {'pref': (Decimal('20.0'), Decimal('0.0')),
                             'ind': (Decimal('10.0'), Decimal('0.0')),
                             'veto': (Decimal('80.0'), Decimal('0.0'))},
             'objective': 'obj1',
             }),
     ('g2', {'weight':Decimal("5.00"),
             'scale': (Decimal("0.00"),Decimal("100.00")),
             'thresholds' : {'pref': (Decimal('20.0'), Decimal('0.0')),
                                   'ind': (Decimal('10.0'), Decimal('0.0')),
                                   'veto': (Decimal('80.0'), Decimal('0.0'))},
             'objective': 'obj2',
             }),
     ...])
evaluation = {'g1': {'a1':Decimal("57.28"),'a2':Decimal("99.85"), ...},
              'g2': {'a1':Decimal("88.12"),'a2':Decimal("33.25"), ...},
              ...}
With the help of the perfTabs.RandomPerformanceTableau class let us generate for illustration a random performance tableau concerning 7 decision actions or alternatives denoted a01, a02, ..., a07:
>>> from randomPerfTabs import RandomPerformanceTableau
>>> rt = RandomPerformanceTableau(seed=100)
>>> rt.showActions()
    *----- show decision action --------------*
    key:  a01
      short name: a01
      name:       random decision action
      comment:    RandomPerformanceTableau() generated.
    key:  a02
      short name: a02
      name:       random decision action
      comment:    RandomPerformanceTableau() generated.
    key:  a03
      short name: a03
      name:       random decision action
      comment:    RandomPerformanceTableau() generated.
    ...
    ...
    key:  a07
    name:       random decision action
    comment:    RandomPerformanceTableau() generated.
>>> ...
In this example we consider furthermore a family of seven equisignificant cardinal criteria functions g01, g02, ..., g07, measuring the performance of each alternative on a rational scale form 0.0 to 100.00. In order to capture the evaluation’s uncertainty and imprecision, each criterion function g1 to g7 admits three performance discrimination thresholds of 10, 20 and 80 pts for warranting respectively any indifference, preference and veto situations:
>>> rt.showCriteria(IntegerWeights=True)
    *----  criteria -----*
    g1 'RandomPerformanceTableau() instance'
      Scale = (0.0, 100.0)
      Weight = 1 
      Threshold ind : 10.00 + 0.00x ; percentile:  0.20
      Threshold veto : 80.00 + 0.00x ; percentile:  0.93
      Threshold pref : 20.00 + 0.00x ; percentile:  0.28
    g2 'RandomPerformanceTableau() instance'
      Scale = (0.0, 100.0)
      Weight = 1 
      Threshold ind : 10.00 + 0.00x ; percentile:  0.18
      Threshold veto : 80.00 + 0.00x ; percentile:  1.0
      Threshold pref : 20.00 + 0.00x ; percentile:  0.37
    g3 'RandomPerformanceTableau() instance'
      Scale = (0.0, 100.0)
      Weight = 1 
      Threshold ind : 10.00 + 0.00x ; percentile:  0.15
      Threshold veto : 80.00 + 0.00x ; percentile:  0.96
      Threshold pref : 20.00 + 0.00x ; percentile:  0.29
    ...
    ...
    g7 'RandomPerformanceTableau() instance'
      Scale = (0.0, 100.0)
      Weight = 1 
      Threshold ind : 10.00 + 0.00x ; percentile:  0.17
      Threshold veto : 80.00 + 0.00x ; percentile:  0.97
      Threshold pref : 20.00 + 0.00x ; percentile:  0.37
>>> ...
The performance evaluations of each decision alternative on each criterion are gathered in a performance tableau:
>>> rt.showPerformanceTableau()
    *----  performance tableau -----*
    criteria | weights |   'a01'   'a02'   'a03'    ...   'a12'   'a13'   
    ---------|----------------------------------------------------------------
       'g1'  |   1     |   14.57   45.49   77.08    ...   93.30   94.71  
       'g2'  |   1     |   33.54   30.94   76.80    ...   55.54   90.12  
       'g3'  |   1     |   81.80   16.04   64.85    ...   23.72   44.82  
       'g4'  |   1     |   63.78   90.23   12.66    ...   52.82   34.33  
       'g5'  |   1     |   85.42   36.30   48.36    ...   76.70   51.36  
       'g6'  |   1     |   49.35   58.27   14.72    ...   21.91   30.99  
       'g7'  |   1     |   62.12   65.08   74.87    ...   38.98   93.64  
>>> ...
computeActionCriterionPerformanceDifferences(refAction, refCriterion, comments=False, Debug=False)[source]

computes the performances differences observed between the reference action and the others on the given criterion

computeActionCriterionQuantile(action, criterion, Debug=False)[source]

renders the quantile of the performance of action on criterion

computeActionQuantile(action, Debug=True)[source]

renders the overall performance quantile of action

computeAllQuantiles(Sorted=True, Comments=False)[source]

renders a html string showing the table of the quantiles matrix action x criterion

computeCriterionPerformanceDifferences(c, Comments=False, Debug=False)[source]

Renders the ordered list of all observed performance differences on the given criterion.

computeDefaultDiscriminationThresholds(criteriaList=None, quantile={'ind': 10, 'weakVeto': 60, 'veto': 80, 'pref': 20}, Debug=False, Comments=False)[source]

updates the discrimination thresholds with the percentiles from the performance differences. Parameters: quantile = {‘ind’: 10, ‘pref’: 20, ‘weakVeto’: 60, ‘veto: 80}.

computeMCSRPerformanceHeatmap(criteriaList=None, actionsList=None, ndigits=2, colorLevels=7, Ranked=True, title='Performance Heatmap', Correlations=False, Threading=False, Debug=False)[source]

Computes the Brewer RdYlGn colored heatmap of the performance table actions x criteria in ordered dictionary format. Three color levels (5,7 or 9) are provided. Used by the Web API.

For a performance tableau with 5 criteria, colorLevels=5 and Correlations = True, one obtains for instance the following ordered dictionary in return:

OrderedDict([
    ('title', 'Performance Heatmap'),
    ('precision', 2),
    ('colorPalette', OrderedDict([
                      ('0',{'quantile':Decimal('0.2'),'quantileClass':'q5_1'}),
                      ('1',{'quantile':Decimal('0.4'),'quantileClass':'q5_2'}),
                      ('2',{'quantile':Decimal('0.6'),'quantileClass':'q5_3'}),
                      ('3',{'quantile':Decimal('0.8'),'quantileClass':'q5_4'}),
                      ('4',{'quantile':Decimal('1.0'),'quantileClass':'q5_5'})
    ])),
    ('criteriaList', OrderedDict([('0','g5'), ('1','g2'), ('2','g4'), ('3','g1'), ('4','g3')]),
    ('criteriaCorrelations', OrderedDict([
                                         ('0',Decimal('0.71428')),
                                         ('1',Decimal('0.48571')),
                                         ('2',Decimal('0.40952')),
                                         ('3',Decimal('0.35238')),
                                         ('4',Decimal('0.16190'))
    ])),
    ('quantiles', OrderedDict([
                               ('0',{'a1':OrderedDict([
                                                 ('0',{'quantile':Decimal('3'), 'qantileClass':'q5-2'}),
                                                 ('1',{'quantile':Decimal('-17.92'), 'qantileClass':'q5-5'}),
                                                 ('2',{'quantile':Decimal('26.68'), 'qantileClass':'q5-2'}),
                                                 ('3',{'quantile':Decimal('1'), 'qantileClass':'q5-1'}),
                                                 ('4',{'quantile':Decimal('-33.99'), 'qantileClass':'q5-3'})
                               ])}),
                               ('1',{'a2':OrderedDict([
                                                 ('0',{'quantile':Decimal('6'), 'qantileClass':'q5-3'}),
                                                 ('1',{'quantile':Decimal('-30.71'), 'qantileClass':'q5-5'}),
                                                 ('2',{'quantile':Decimal('66.35'), 'qantileClass':'q5-4'}),
                                                 ('3',{'quantile':Decimal('8'), 'qantileClass':'q5-5'}),
                                                 ('4',{'quantile':Decimal('-77.77'), 'qantileClass':'q5-3'})
                               ])}),
                               ('2', ...
    ]))...
]))
computeMCSRPerformanceTableau(isSorted=True, ndigits=2, title='Min/Max Performance Tableau', Debug=False)[source]

Computes the performance table in a JSON compatible format with minima and maxima. Used by the Web API.

For a performance tableau with 5 criteria one obtains for instance the following ordered dictionary in return:

OrderedDict([
    ('title', 'Min/Max Performance Tableau'),
    ('precision', 2),
    ('criteriaList', OrderedDict([('0','g5'), ('1','g2'), ('2','g4'), ('3','g1'), ('4','g3')]),
    ('quantiles', OrderedDict([
                               ('0',{'a1':OrderedDict([
                                                 ('0',{'quantile':Decimal('3'), 'qantileClass':'minimum'}),
                                                 ('1',{'quantile':Decimal('-17.92'), 'qantileClass':'default'}),
                                                 ('2',{'quantile':Decimal('26.68'), 'qantileClass':'maximum'}),
                                                 ('3',{'quantile':'NaN, 'qantileClass':'NaN'}),
                                                 ('4',{'quantile':Decimal('-33.99'), 'qantileClass':'default'})
                               ])}),
                               ('1',{'a2':OrderedDict([
                                                 ('0',{'quantile':Decimal('6'), 'qantileClass':'minimum'}),
                                                 ('1',{'quantile':Decimal('-30.71'), 'qantileClass':'default'}),
                                                 ('2',{'quantile':'NaN', 'qantileClass':'NaN'}),
                                                 ('3',{'quantile':Decimal('8'), 'qantileClass':'maximum'}),
                                                 ('4',{'quantile':Decimal('-77.77'), 'qantileClass':'default'})
                               ])}),
                               ('2', ...
    ]))...
]))
computeMinMaxEvaluations(criteria=None, actions=None)[source]

renders minimum and maximum performances on each criterion in dictionary form: {‘g’: {‘minimum’: x, ‘maximum’: x}}

computeNormalizedDiffEvaluations(lowValue=0.0, highValue=100.0, withOutput=False, Debug=False)[source]

renders and csv stores (withOutput=True) the list of normalized evaluation differences observed on the family of criteria Is only adequate if all criteria have the same evaluation scale. Therefore the performance tableau is normalized to 0.0-100.0 scales.

computePerformanceDifferences(Comments=False, Debug=False, NotPermanentDiffs=True, WithMaxMin=False)[source]

Adds to the criteria dictionary the ordered list of all observed performance differences.

computeQuantileOrder(q0=3, q1=0, Threading=False, nbrOfCPUs=1, Comments=False)[source]

Renders a linear ordering of the decision actions from a simulation of pre-ranked outranking digraphs.

The pre-ranking simulations range by default from quantiles=q0 to quantiles=min( 100, max(10,len(self.actions)/10]) ).

The actions are ordered along a decreasing Borda score of their ranking results.

computeQuantilePreorder(Comments=True, Debug=False)[source]

computes the preorder of the actions obtained from decreasing majority quantiles. The quantiles are recomputed with a call to the self.computeQuantileSort() method.

computeQuantileRanking(q0=3, q1=0, Threading=False, nbrOfCPUs=1, Comments=False)[source]

Renders a linear ranking of the decision actions from a simulation of pre-ranked outranking digraphs.

The pre-ranking simulations range by default from quantiles=q0 to qantiles=min( 100, max(10,len(self.actions)/10) ).

The actions are ordered along an increasing Borda score of their ranking results.

computeQuantileSort()[source]

shows a sorting of the actions from decreasing majority quantiles

computeQuantiles(Debug=False)[source]

renders a quantiles matrix action x criterion with the performance quantile of action on criterion

computeThresholdPercentile(criterion, threshold, Debug=False)[source]

computes for a given criterion the quantile of the performance differences of a given constant threshold.

computeVariableThresholdPercentile(criterion, threshold, Debug=False)[source]

computes for a given criterion the quantile of the performance differences of a given threshold.

computeWeightPreorder()[source]

renders the weight preorder following from the given criteria weights in a list of increasing equivalence lists of criteria.

computeWeightedAveragePerformances(isNormalized=False, lowValue=0.0, highValue=100.0, isListRanked=False)[source]

Compute normalized weighted average scores Normalization transforms by default all the scores into a common 0-100 scale. A lowValue and highValue parameter can be provided for a specific normalisation.

convertBigData2Standard()[source]

convert cRandPerfTabs generated objects into standard PerformanceTableau instances.

convertDiscriminationThresholds2Decimal()[source]
convertDiscriminationThresholds2Float()[source]
convertEvaluation2Float()[source]

Convert evaluations from decimal format to float

convertEvaluationFloatToDecimal()[source]

Convert evaluations from obsolete float format to decimal format

convertStandard2BigData()[source]

convert standard PerformanceTableau to cPerformanceTableau instances, by converting the action keys to integers and evaluations to floats, including the discrimination thresholds the case given.

convertWeight2Integer()[source]

Convert significance weights from Decimal format to int format.

convertWeightFloatToDecimal()[source]

Convert significance weights from obsolete float format to decimal format.

csvAllQuantiles(fileName='quantiles')[source]

save quantiles matrix criterionxaction in CSV format

hasOddWeightAlgebra(Debug=False)[source]

Verify if the given criteria[self][‘weight’] are odd or not. Return a Boolen value.

htmlPerformanceHeatmap(argCriteriaList=None, argActionsList=None, SparseModel=True, minimalComponentSize=1, RankingRule='Copeland', quantiles=None, strategy='average', ndigits=2, contentCentered=True, colorLevels=None, pageTitle='Performance Heatmap', Correlations=False, Threading=False, nbrOfCPUs=1, Debug=False)[source]

Renders the Brewer RdYlGn 5,7, or 9 levels colored heatmap of the performance table actions x criteria in html format.

See the corresponding perfTabs.showHTMLPerformanceHeatMap() method.

htmlPerformanceTable(actions=None, isSorted=False, Transposed=False, ndigits=2, ContentCentered=True, title=None)[source]

Renders the performance table citerion x actions in html format.

mpComputePerformanceDifferences(NotPermanentDiffs=True, nbrCores=None, Debug=False)[source]

Adds to the criteria dictionary the ordered list of all observed performance differences.

normalizeEvaluations(lowValue=0.0, highValue=100.0, Debug=False)[source]

recode the evaluations between lowValue and highValue on all criteria

restoreOriginalEvaluations(lowValue=0.0, highValue=100.0, Debug=False)[source]

recode the evaluations to their original values on all criteria

save(fileName='tempperftab', isDecimal=True, valueDigits=2)[source]

Persistant storage of Performance Tableaux.

saveCSV(fileName='tempPerfTab', Sorted=True, actionsList=None, ndigits=2, Debug=False)[source]

1 Store the performance Tableau self Actions x Criteria in CSV format.

saveXMCDA(fileName='temp', category='New XMCDA Rubis format', user='digraphs Module (RB)', version='saved from Python session', variant='Rubis', valuationType='standard', servingD3=True)[source]

save performance tableau object self in XMCDA format.

saveXMCDA2(fileName='temp', category='XMCDA 2.0 Extended format', user='digraphs Module (RB)', version='saved from Python session', title='Performance Tableau in XMCDA-2.0 format.', variant='Rubis', valuationType='bipolar', servingD3=False, isStringIO=False, stringNA='NA', comment='produced by saveXMCDA2()', hasVeto=True)[source]

save performance tableau object self in XMCDA 2.0 format including decision objectives, the case given.

saveXMCDA2String(fileName='temp', category='XMCDA 2.0 format', user='digraphs Module (RB)', version='saved from Python session', title='Performance Tableau in XMCDA-2.0 format.', variant='Rubis', valuationType='bipolar', servingD3=True, comment='produced by stringIO()', stringNA='NA')[source]

save performance tableau object self in XMCDA 2.0 format. !!! obsolete: replaced by the isStringIO in the saveXMCDA2 method !!!

saveXML(name='temp', category='standard', subcategory='standard', author='digraphs Module (RB)', reference='saved from Python')[source]

save temporary performance tableau self in XML format.

saveXMLRubis(name='temp', category='Rubis', subcategory='new D2 version', author='digraphs Module (RB)', reference='saved from Python')[source]

save temporary performance tableau self in XML Rubis format.

showActions(Alphabetic=False)[source]

presentation methods for decision actions or alternatives

showAll()[source]

Show fonction for performance tableau

showAllQuantiles(Sorted=True)[source]

prints the performance quantiles tableau in the session console.

showCriteria(IntegerWeights=False, Alphabetic=False, ByObjectives=False, Debug=False)[source]

print Criteria with thresholds and weights.

showEvaluationStatistics()[source]

renders the variance and standard deviation of the values observed in the performance Tableau.

showHTMLMCSRPerformanceTableau(ndigits=2, title='Min/Max Performance Tableau')[source]

Ask the server for an HTML representation of the performance tableau.

showHTMLPerformanceHeatmap(actionsList=None, criteriaList=None, colorLevels=7, pageTitle=None, ndigits=2, SparseModel=False, minimalComponentSize=1, RankingRule='Copeland', quantiles=None, strategy='average', Correlations=False, Threading=False, nbrOfCPUs=None, Debug=False)[source]

shows the html heatmap version of the performance tableau in a browser window (see perfTabs.htmlPerformanceHeatMap() method ).

Parameters:

  • actionsList and criteriaList, if provided, give the possibility to show the decision alternatives, resp. criteria, in a given ordering.
  • ndigits = 0 may be used to show integer evaluation values.
  • If no actionsList is provided, the decision actions are ordered from the best to the worst. This ranking is obtained by default with the Copeland rule applied on a standard BipolarOutrankingDigraph. When the SparseModel flag is put to True, a sparse PreRankedOutrankingDigraph construction is used instead.
  • The minimalComponentSize allows to control the fill rate of the pre-ranked model. If minimalComponentSize = n (the number of decision actions) both the pre-ranked model will be in fact equivalent to the standard model.
  • It may interesting in some cases to use RankingRule = ‘NetFlows’.
  • Quantiles used for the pre-ranked decomposition are put by default to n (the number of decision alternatives) for n < 50. For larger cardinalities up to 1000, quantiles = n /10. For bigger performance tableaux the quantiles parameter may be set to a much lower value not exceeding usually 1000.
  • The pre-ranking may be obtained with three ordering strategies for the quantiles equivalence classes: ‘average’ (default), ‘optimistic’ or ‘pessimistic’.
  • With Correlations = True and criteriaList = None, the criteria will be presented from left to right in decreasing order of the correlations between the marginal criterion based ranking and the global ranking used for presenting the decision alternatives.
  • For large performance Tableaux, multiprocessing techniques may be used by setting Threading = True in order to speed up the computations; especially when Correlations = True.
  • By default, the number of cores available, will be detected. It may be efficient in a HPC context to indicate the exact number of singled threaded cores in fact allocated to the job.
>>> from randomPerfTabs import RandomPerformanceTableau
>>> rt = RandomPerformanceTableau(seed=100)
>>> rt.showHTMLPerformanceHeatmap(colorLevels=5,Correlations=True)
HTML heat map of the performance tableau
showHTMLPerformanceQuantiles(Sorted=True)[source]

shows the performance quantiles tableau in a browser window.

showHTMLPerformanceTableau(actionsSubset=None, isSorted=True, Transposed=False, ndigits=2, ContentCentered=True, title=None)[source]

shows the html version of the performance tableau in a browser window.

showObjectives()[source]
showPairwiseComparison(a, b, hasSymetricThresholds=True, Debug=False, isReturningHTML=False, hasSymmetricThresholds=True)[source]

renders the pairwise comprison parameters on all criteria in html format

showPerformanceTableau(actionsSubset=None, sorted=None, ndigits=2)[source]

Print the performance Tableau.

showQuantileSort(Debug=False)[source]

Wrapper of computeQuantilePreorder() for the obsolete showQuantileSort() method.

showStatistics(Debug=False)[source]

show statistics concerning the evaluation distributions on each criteria.

to_JSON()[source]

Convert the performance table .__dict__ into a JSON string

class perfTabs.XMCDA2PerformanceTableau(fileName='temp', HasSeparatedWeights=False, HasSeparatedThresholds=False, stringInput=None, Debug=False)[source]

Bases: perfTabs.PerformanceTableau

Specialization of the general PerformanceTableau class for reading stored XMCDA 2.0 formatted instances with exact decimal numbers. Using the inbuilt module xml.etree (for Python 2.5+).

Parameters:
  • fileName is given without the extension .xml or .xmcda,
  • HasSeparatedWeights in XMCDA 2.0.0 encoding (default = False),
  • HasSeparatedThresholds in XMCDA 2.0.0 encoding (default = False),
  • stringInput: instantiates from an XMCDA 2.0 encoded string argument.
class OrderedDict

Bases: dict

Dictionary that remembers insertion order

clear() → None. Remove all items from od.
copy() → a shallow copy of od
fromkeys(S[, v]) → New ordered dictionary with keys from S.

If not specified, the value defaults to None.

items()
keys()
move_to_end()

Move an existing element to the end (or beginning if last==False).

Raises KeyError if the element does not exist. When last=True, acts like a fast version of self[key]=self.pop(key).

pop(k[, d]) → v, remove specified key and return the corresponding

value. If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() → (k, v), return and remove a (key, value) pair.

Pairs are returned in LIFO order if last is true or FIFO order if false.

setdefault(k[, d]) → od.get(k,d), also set od[k]=d if k not in od
update()
values()
class perfTabs.XMCDAPerformanceTableau(fileName='temp')[source]

Bases: perfTabs.PerformanceTableau

Specialization of the general PerformanceTableau class for reading stored XMCDA formatted instances with exact decimal numbers. Using the inbuilt module xml.etree (for Python 2.5+).

Param: fileName (without the extension .xml or .xmcda).

class perfTabs.XMLPerformanceTableau(fileName='testperftabXML')[source]

Bases: perfTabs.PerformanceTableau

Specialization of the general PerformanceTableau class for reading stored XML formatted instances.

class perfTabs.XMLRubisPerformanceTableau(fileName='rubisPerformanceTableau')[source]

Bases: perfTabs.PerformanceTableau

Specialization of the general PerformanceTableau class for reading stored XML formatted instances. Using the inbuilt module xml.etree (for Python 2.5+).

Param: fileName (without the extension .xml).

stripsplit(th)[source]

extract thresholds new Python 3 compatible version

Back to the Installation

randomPerfTabs module

A tutorial with coding examples is available here: Generating random performance tableaux

class randomPerfTabs.FullRandomPerformanceTableau(numberOfActions=None, numberOfCriteria=None, weightDistribution=None, weightScale=None, integerWeights=True, commonScale=None, commonThresholds=None, commonMode=None, valueDigits=2, seed=None, Debug=False)[source]

Bases: perfTabs.PerformanceTableau

Full automatic generation of random performance tableaux

showAll()[source]

Show fonction for performance tableau of full random outranking digraph.

class randomPerfTabs.Random3ObjectivesPerformanceGenerator(argPerfTab, actionNamePrefix='a', instanceCounter=0, seed=None, Debug=False)[source]

Bases: object

Generates and/or new decision actions with random evaluation for a given Random3ObjectivesPerformanceTableau instance.

randomAction()[source]

Returns a dictionary with following content:

{ ‘action’: { ‘key’: actionKey, ‘shortName’: ..., ‘name’: ..., ... }, ‘evaluation’: {‘g1’: Decimal(...), ‘g2’: Decimal(...), ... } }

randomUpdate(nbrOfRandomActions=1)[source]

Updates self.perfTab with n = nbrOfActions new random decision alternatives.

Note

The update will modify the generator’s given performance tableau instance by, either adding new actions with their random evaluations, or updating the performances of already existing decision actions.

class randomPerfTabs.Random3ObjectivesPerformanceTableau(numberOfActions=20, numberOfCriteria=13, weightDistribution='equiobjectives', weightScale=None, integerWeights=True, OrdinalScales=False, commonScale=None, commonThresholds=None, commonMode=None, valueDigits=2, vetoProbability=0.5, missingDataProbability=0.05, BigData=False, seed=None, Debug=False)[source]

Bases: perfTabs.PerformanceTableau

Specialization of the PerformanceTableau for 3 objectives: Eco, Soc and Env.

Each decision action is qualified at random as weak (-), fair (~) or good (+) on each of the three objectives.

Generator arguments:
  • numberOf Actions := 20 (default)

  • number of Criteria := 13 (default)

  • weightDistribution := ‘equiobjectives’ (default)
    ‘equisignificant’ (weights set all to 1)
    ‘random’ (in the range 1 to numberOfCriteria)
  • weightScale := [1,numerOfCriteria] (random default)

  • integerWeights := True (default) / False

  • OrdinalScales := True / False (default), if True commonScale is set to (0,10)

  • commonScale := (0.0, 100.0) (default if OrdinalScales == False)

  • commonThresholds := [(1.0,0.0),(2.001,0.0),(8.001,0.0)] if OrdinalScales == True, otherwise
    [(0.10001*span,0.0),(0.20001*span,0.0),(0.80001*span,0.0)] with span = commonScale[1] - commonScale[0].
  • commonMode := [‘triangular’,’variable’,0.50] (default), A constant mode may be provided.
    [‘uniform’,’variable’,None], a constant range may be provided.
    [‘beta’,’variable’,None] (three alpha, beta combinations (5.8661,2.62203)
    chosen by default for ‘good’, ‘fair’ and ‘weak’ evaluations. Constant parameters may be provided.
  • valueDigits := 2 (default, for cardinal scales only)

  • vetoProbability := x in ]0.0-1.0[ (0.5 default), probability that a cardinal criterion shows a veto preference discrimination threshold.

  • Debug := True / False (default)

showActions(Alphabetic=False)[source]
showObjectives()[source]
class randomPerfTabs.RandomCBPerformanceGenerator(argPerfTab, actionNamePrefix='a', instanceCounter=0, seed=None)[source]

Bases: object

Instantiates a generator of new decision actions with associated random evaluations using the model parameters provided by a given RandomCBPerformanceTableau instance.

randomAction()[source]

Returns a dictionary with following content:

{ 'action': { 'key': actionKey, 'shortName': ..., 'name': ...,  
         'type': 'neutral'|'advantageous'|'cheap'},
         'evaluation': {'g1': Decimal(...), 
                        'g2': Decimal(...), ... }}.
randomUpdate(nbrOfRandomActions=1)[source]

Updates self.perfTab with n = nbrOfActions new random decision alternatives.

Note

The update will modify the generator’s given performance tableau instance by, either adding new actions with their random evaluations, or updating the performances of already existing decision actions.

class randomPerfTabs.RandomCBPerformanceTableau(numberOfActions=13, numberOfCriteria=7, name='randomCBperftab', weightDistribution='equiobjectives', weightScale=None, integerWeights=True, commonScale=None, commonThresholds=None, commonPercentiles=None, samplingSize=100000, commonMode=None, valueDigits=2, missingDataProbability=0.01, BigData=False, seed=None, Threading=False, nbrCores=None, Debug=False, Comments=False)[source]

Bases: perfTabs.PerformanceTableau

Full automatic generation of random Cost versus Benefit oriented performance tableaux.

Parameters:

  • If numberOfActions == None, a uniform random number between 10 and 31 of cheap, neutral or advantageous actions (equal 1/3 probability each type) actions is instantiated
  • If numberOfCriteria == None, a uniform random number between 5 and 21 of cost or benefit criteria.
    Cost criteria have probability 1/3, whereas benefit criteria respectively 2/3 probability to be generated. However, at least one criterion of each kind is always instantiated.
  • weightDistribution := {‘equiobjectives’|’fixed’|’random’|’equisignificant’} By default, the sum of
    significance of the cost criteria is set equal to the sum of the significance of the benefit criteria.
  • default weightScale for ‘random’ weightDistribution is 1 - numberOfCriteria.
  • commonScale parameter is obsolete. The scale of cost criteria is cardinal or ordinal (0-10)
    with proabailities 1/4 respectively 3/4, whereas the scale of benefit criteria is ordinal or cardinal with probabilities 2/3, respectively 1/3.
  • All cardinal criteria are evaluated with decimals between 0.0 and 100.0 wheras all ordinal criteria
    are evaluated with integers between 0 and 10.
  • commonThresholds is obsolete. Preference discrimination is specified as percentiles of
    concerned performance differences (see below).
  • CommonPercentiles = {‘ind’:0.05, ‘pref’:0.10, [‘weakveto’:0.90,] ‘veto’:‘95} are expressed
    in centiless (reversed for vetoes) and only concern cardinal criteria.

Warning

Minimal number of decision actions required is 3 !

updateDiscriminationThresholds(Comments=False, Debug=False)[source]

Recomputes performance discrimination thresholds from commonPercentiles.

Note

Overwrites all previous criterion discrimination thresholds !

class randomPerfTabs.RandomCoalitionsPerformanceTableau(numberOfActions=None, numberOfCriteria=None, weightDistribution=None, weightScale=None, integerWeights=True, commonScale=None, commonThresholds=None, commonMode=None, valueDigits=2, Coalitions=True, VariableGenerators=True, OrdinalScales=False, Debug=False, RandomCoalitions=False, vetoProbability=None, BigData=False, seed=None, Electre3=True)[source]

Bases: perfTabs.PerformanceTableau

Full automatic generation of performance tableaux with random coalitions of criteria

Parameters:
numberOf Actions := 20 (default)
number of Criteria := 13 (default)
weightDistribution := ‘equisignificant’ (default with all weights = 1.0), ‘random’, ‘fixed’ (default w_1 = numberOfCriteria-1, w_{i!=1} = 1
weightScale := [1,numerOfCriteria] (random default), [w_1, w_{i!=1] (fixed)
integerWeights := True (default) / False
commonScale := (0.0, 100.0) (default)
commonThresholds := [(1.0,0.0),(2.001,0.0),(8.001,0.0)] if OrdinalSacles, [(0.10001*span,0),(0.20001*span,0.0),(0.80001*span,0.0)] with span = commonScale[1] - commonScale[0].
commonMode := [‘triangular’,50.0,0.50] (default), [‘uniform’,None,None], [‘beta’, None,None] (three alpha, beta combinations (5.8661,2.62203) chosen by default for high(‘+’), medium (‘~’) and low (‘-‘) evaluations.
valueDigits := 2 (default, for cardinal scales only)
Coalitions := True (default)/False, three coalitions if True
VariableGenerators := True (default) / False, variable high(‘+’), medium (‘~’) or low (‘-‘) law generated evaluations.
OrdinalScales := True / False (default)
Debug := True / False (default)
RandomCoalitions = True / False (default) zero or more than three coalitions if Coalitions == False.
vetoProbability := x in ]0.0-1.0[ / None (default), probability that a cardinal criterion shows a veto preference discrimination threshold.
Electre3 := True (default) / False, no weakveto if True (obsolete)
class randomPerfTabs.RandomPerformanceGenerator(argPerfTab, actionNamePrefix='a', instanceCounter=0, seed=None)[source]

Bases: object

Generates and/or new decision actions with random evaluation for a given RandomPerformanceTableau instance.

randomAction()[source]

Returns {'action': key, 'evaluation': {'g1': Decimal(...), 'g2': Decimal(...), ... }}

randomUpdate(nbrOfRandomActions=1)[source]

Updates self.perfTab with n = nbrOfActions new random decision alternatives.

Note

The update will modify the generator’s given performance tableau instance by, either adding new actions with their random evaluations, or updating the performances of already existing decision actions.

class randomPerfTabs.RandomPerformanceTableau(numberOfActions=13, actionNamePrefix='a', numberOfCriteria=7, weightDistribution='equisignificant', weightScale=None, integerWeights=True, commonScale=(0.0, 100.0), commonThresholds=((10.0, 0.0), (20.0, 0.0), (80.0, 0.0)), commonMode=None, valueDigits=2, missingDataProbability=0.0, BigData=False, seed=None, Debug=False)[source]

Bases: perfTabs.PerformanceTableau

Specialization of the generic perftabs.PerformanceTableau class for generating a temporary random performance tableau.

Parameters:
  • numberOfActions := nbr of decision actions.

  • numberOfCriteria := number performance criteria.

  • weightDistribution := ‘random’ (default) | ‘fixed’ | ‘equisignificant’.
    If ‘random’, weights are uniformly selected randomly
    form the given weight scale;
    If ‘fixed’, the weightScale must provided a corresponding weights
    distribution;
    If ‘equisignificant’, all criterion weights are put to unity.
  • weightScale := [Min,Max] (default =[1,numberOfCriteria].

  • IntegerWeights := True (default) | False (normalized to proportions of 1.0).

  • commonScale := [Min;Max]; common performance measuring scales (default = [0;100])

  • commonThresholds := [(q0,q1),(p0,p1),(v0,v1)]; common indifference(q), preference (p) and considerable performance difference discrimination thresholds.

  • commonMode := common random distribution of random performance measurements:
    (‘uniform’,Min,Max), uniformly distributed between min and max values.
    (‘normal’,mu,sigma), truncated Gaussion distribution.
    (‘triangular’,mode,repartition), generalized triangular distribution
    (‘beta’,alpha,beta).
  • valueDigits := <integer>, precision of performance measurements (2 decimal digits by default).

Code example:
>>> from randomPerfTabs import RandomPerformanceTableau
>>> t = RandomPerformanceTableau(numberOfActions=3,numberOfCriteria=1,seed=100)
>>> t.actions
    {'a1': {'comment': 'RandomPerformanceTableau() generated.', 'name': 'random decision action'},
     'a2': {'comment': 'RandomPerformanceTableau() generated.', 'name': 'random decision action'},
     'a3': {'comment': 'RandomPerformanceTableau() generated.', 'name': 'random decision action'}}
>>> t.criteria
    {'g1': {'thresholds': {'ind' : (Decimal('10.0'), Decimal('0.0')),
                           'veto': (Decimal('80.0'), Decimal('0.0')),
                           'pref': (Decimal('20.0'), Decimal('0.0'))},
            'scale': [0.0, 100.0],
            'weight': Decimal('1'),
            'name': 'digraphs.RandomPerformanceTableau() instance',
            'comment': 'Arguments: ; weightDistribution=random;
                weightScale=(1, 1); commonMode=None'}}
>>> t.evaluation
    {'g01': {'a01': Decimal('45.95'),
             'a02': Decimal('95.17'),
             'a03': Decimal('17.47')
            }
    }
class randomPerfTabs.RandomRankPerformanceTableau(numberOfActions=13, numberOfCriteria=7, weightDistribution='equisignificant', weightScale=None, commonThresholds=None, integerWeights=True, BigData=False, seed=None, Debug=False)[source]

Bases: perfTabs.PerformanceTableau

Specialization of the PerformanceTableau class for generating a temporary random performance tableau.

Random generator for multiple criteria ranked (without ties) performances of a given number of decision actions. On each criterion, all decision actions are hence lineraly ordered. The RandomRankPerformanceTableau class is matching the RandomLinearVotingProfiles class (see the votingDigraphs module)

Parameters:
  • number of actions,

  • number of performance criteria,

  • weightDistribution := equisignificant | random (default, see RandomPerformanceTableau)

  • weightScale := (1, 1 | numberOfCriteria (default when random))

  • integerWeights := Boolean (True = default)

  • commonThresholds (default) := {
    ‘ind’:(0,0),
    ‘pref’:(1,0),
    ‘veto’:(numberOfActions,0)
    } (default)
class randomPerfTabs.RandomS3PerformanceTableau(numberOfActions=None, numberOfCriteria=None, weightDistribution=None, weightScale=None, integerWeights=True, commonScale=None, commonThresholds=None, commonMode=None, valueDigits=2, Coalitions=True, VariableGenerators=True, OrdinalScales=False, Debug=False, RandomCoalitions=False, vetoProbability=None, BigData=False, seed=None, Electre3=True)[source]

Bases: randomPerfTabs.RandomCoalitionsPerformanceTableau

Obsolete dummy class for backports.

Back to the Installation

outrankingDigraphs module

A tutorial with coding examples is available here: Working with the outrankingDigraphs module

Python implementation of outranking digraphs.

Copyright (C) 2006-20017 Raymond Bisdorff

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

class outrankingDigraphs.BipolarIntegerOutrankingDigraph(argPerfTab=None, coalition=None, hasBipolarVeto=True, hasSymmetricThresholds=True)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)
optional, coalition (sublist of criteria)

Specialization of the standard OutrankingDigraph class for generating bipolar integer-valued outranking digraphs.

savePy2Gprolog(name='temp')[source]

save digraph in gprolog version

showRelation()[source]

prints the relation valuation in ##.## format.

class outrankingDigraphs.BipolarOutrankingDigraph(argPerfTab=None, coalition=None, actionsSubset=None, hasNoVeto=False, hasBipolarVeto=True, Normalized=False, CopyPerfTab=True, BigData=False, Threading=False, tempDir=None, WithConcordanceRelation=True, WithVetoCounts=True, nbrCores=None, Debug=False, Comments=False)[source]

Bases: outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Specialization of the abstract OutrankingDigraph root class for generating bipolarly-valued outranking digraphs.

Parameters:
  • argPerfTab: instance of PerformanceTableau class. If a file name string is given, the performance tableau will directly be loaded first.
  • coalition: subset of criteria to be used for contruction the outranking digraph.
  • hasNoVeto: veto desactivation flag (False by default).
  • hasBipolarVeto: bipolar versus electre veto activation (true by default).
  • Normalized: the valuation domain is set by default to [-100,+100] (bipolar percents). If True, the valuation domain is recoded to [-1.0,+1.0].
  • WithConcordanceRelation: True by default when not threading. The self.concordanceRelation contains the significance majority margin of the “at least as good relation as” without the large performance difference polarization.
  • WithVetoCounts: True by default when not threading. All vetos and countervetos are stored in self.vetos and self.negativeVetos slots, as well the counts of large performance differences in self.largePerformanceDifferencesCount slot.
  • Threading: False by default. Allows to profit from SMP machines via the Python multiprocessing module.
  • nbrCores: controls the maximal number of cores that will be used in the multiprocessing phases. If None is given, the os.cpu_count method is used in order to determine the number of availble cores on the SMP machine.

Warning

If Threading is True, WithConcordanceRelation and WithVetoCounts flags are automatically set both to False.

computeCriterionRelation(c, a, b, hasSymmetricThresholds=True)[source]

Compute the outranking characteristic for actions x and y on criterion c.

computeSingleCriteriaNetflows()[source]

renders the Promethee single criteria netflows matrix M

criterionCharacteristicFunction(c, a, b, hasSymmetricThresholds=True)[source]

Renders the characteristic value of the comparison of a and b on criterion c.

saveSingleCriterionNetflows(fileName='tempnetflows.prn', delimiter=' ', Comments=True)[source]

Delimited save of single criteria netflows matrix

class outrankingDigraphs.ConfidentBipolarOutrankingDigraph(argPerfTab=None, distribution='triangular', betaParameter=2, confidence=90.0, coalition=None, hasNoVeto=False, hasBipolarVeto=True, Normalized=True, Threading=False, nbrOfCPUs=1, Debug=False)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph

Confident bipolar outranking digraph based on multiple criteria of uncertain significance.

The digraph’s bipolar valuation represents the bipolar outranking relation based on a sufficient likelihood of the at least as good as relation that is outranking without veto and counterveto.

By default, each criterion i’ significance weight is supposed to be a triangular random variable of mode w_i in the range 0 to 2*w_i.

Parameters:

  • argPerfTab: PerformanceTableau instance or the name (without extension) of a stored one. If None, a random instance is generated.
  • distribution: {triangular|uniform|beta}, probability distribution used for generating random weights
  • betaParameter: a = b (default = 2)
  • confidence: required likelihood (in %) of the outranking relation
  • other standard parameters from the BipolarOutrankingDigraph class (see documentation).
computeCLTLikelihoods(distribution='triangular', betaParameter=None, Threading=False, nbrOfCPUs=1, Debug=False)[source]

Renders the pairwise CLT likelihood of the at least as good as relation neglecting all considerable large performance differences polarisations.

showRelationTable(IntegerValues=False, actionsSubset=None, Sorted=True, LikelihoodDenotation=True, hasLatexFormat=False, hasIntegerValuation=False, relation=None, Debug=False)[source]

prints the relation valuation in actions X actions table format.

class outrankingDigraphs.DissimilarityOutrankingDigraph(argPerfTab=None)[source]

Bases: outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the OutrankingDigraph class for generating temporary dissimilarity random graphs

showAll()[source]

specialize the general showAll method for the dissimilarity case

class outrankingDigraphs.Electre3OutrankingDigraph(argPerfTab=None, coalition=None, hasNoVeto=False)[source]

Bases: outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Specialization of the standard OutrankingDigraph class for generating classical Electre III outranking digraphs (with vetoes and no counter-vetoes).

Parameters:
performanceTableau (fileName of valid py code)
optional, coalition (sublist of criteria)
computeCriterionRelation(c, a, b, hasSymmetricThresholds=False)[source]

compute the outranking characteristic for actions x and y on criterion c.

computeVetos(cutLevel=None, realVetosOnly=False)[source]

prints all veto situations observed in the OutrankingDigraph instance.

showVetos(cutLevel=None, realVetosOnly=False, Comments=True)[source]

prints all veto situations observed in the OutrankingDigraph instance.

class outrankingDigraphs.EquiSignificanceMajorityOutrankingDigraph(argPerfTab=None, coalition=None, hasNoVeto=False)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the general OutrankingDigraph class for temporary outranking digraphs with equisignificant criteria.

class outrankingDigraphs.MultiCriteriaDissimilarityDigraph(perfTab=None, filePerfTab=None)[source]

Bases: outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the OutrankingDigraph class for generating temporary multiple criteria based dissimilarity graphs.

class outrankingDigraphs.NewRobustOutrankingDigraph(filePerfTab=None, Debug=False, hasNoVeto=True)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the general OutrankingDigraph class for new robustness anaylsis.

class outrankingDigraphs.OrdinalOutrankingDigraph(argPerfTab=None, coalition=None, hasNoVeto=False)[source]

Bases: outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the general OutrankingDigraph class for temporary ordinal outranking digraphs

class outrankingDigraphs.OutrankingDigraph(file=None, order=7)[source]

Bases: digraphs.Digraph, perfTabs.PerformanceTableau

Abstract root class for outranking digraphs inheritating methods both from the generic digraphs.Digraph and from the generic perfTabs.PerformanceTableau root classes. As such, our genuine outranking digraph model is a hybrid object appearing on the one side as digraph with a nodes set (the decision alternatives) and a binary relation (outranking situations) and, on the other side, as a performance tableau with a set of decision alternatives, performance criteria and a table of performance measurements.

Provides common methods to all specialized models of outranking digraphs, the standard outranking digraph model being provided by the outrankingDigraphs.BipolarOutrankingDigraph class.

A given object of this class consists at least in:

  1. a potential set of decision actions : an (ordered) dictionary describing the potential decision actions or alternatives with ‘name’ and ‘comment’ attributes,
  2. a coherent family of criteria: an (ordered) dictionary of criteria functions used for measuring the performance of each potential decision action with respect to the preference dimension captured by each criterion,
  3. the evaluations: a dictionary of performance evaluations for each decision action or alternative on each criterion function.
  4. the digraph valuationdomain, a dictionary with three entries: the minimum (-100, means certainly no link), the median (0, means missing information) and the maximum characteristic value (+100, means certainly a link),
  5. the outranking relation : a double dictionary defined on the Cartesian product of the set of decision alternatives capturing the credibility of the pairwise outranking situation computed on the basis of the performance differences observed between couples of decision alternatives on the given family if criteria functions.

Warning

Cannot be called directly ! No __init__(self,...) method defined.

computeAMPLData(OldValuation=False)[source]

renders the ampl data list

computeActionsCorrelations()[source]

renders the comparison correlations between the actions

computeCriteriaCorrelationDigraph()[source]

renders the ordinal criteria correlation digraph

computeCriteriaCorrelations()[source]

renders the comparison correlations between the criteria

computeCriterionCorrelation(criterion, Threading=False, nbrOfCPUs=None, Debug=False, Comments=False)[source]

Renders the ordinal correlation coefficient between the global outranking and the marginal criterion relation.

Uses the digraphs.computeOrdinalCorrelationMP().

Note

Renders a dictionary with the key ‘correlation’ containing the actual bipolar correlation index and the key ‘determination’ containing the minimal determination level D of the self outranking and the marginal criterion relation.

D = sum_{x != y} min(abs(self.relation(x,y)),abs(marginalCriterionRelation(x,y)) / n(n-1)

where n is the number of actions considered.

The correlation index with a completely indeterminate relation is by convention 0.0 at determination level 0.0 .

computeCriterionRelation(c, a, b)[source]

compute the outranking characteristic for actions x and y on criterion c.

computeMarginalCorrelation(args, Threading=False, nbrOfCPUs=None, Debug=False, Comments=False)[source]

Renders the ordinal correlation coefficient between the marginal criterion relation and a given normalized outranking relation.

args = (criterion,relation)

computeMarginalVersusGlobalOutrankingCorrelations(Sorted=True, Threading=False, nbrCores=None, Comments=False)[source]

Method for computing correlations between each individual criterion relation with the corresponding global outranking relation.

Returns a list of tuples (correlation,criterionKey) sorted by default in decreasing order of the correlation.

If Threading is True, a multiprocessing Pool class is used with a parallel equivalent of the built-in map function.

If nbrCores is not set, the os.cpu_count() function is used to determine the number of available cores.

computeMarginalVersusGlobalRankingCorrelations(ranking, Sorted=True, ValuedCorrelation=False, Threading=False, nbrCores=None, Comments=False)[source]

Method for computing correlations between each individual criterion relation with the corresponding global outranking relation.

Returns a list of tuples (correlation,criterionKey) sorted by default in decreasing order of the correlation.

If Threading is True, a multiprocessing Pool class is used with a parallel equivalent of the built-in map function.

If nbrCores is not set, the os.cpu_count() function is used to determine the number of available cores.

computePairwiseComparisons(hasSymmetricThresholds=True)[source]

renders pairwise comparison parameters for all pairs of actions

computePairwiseCompleteComparison(a, b, c)[source]

renders pairwise complete comparison parameters for actions a and b on criterion c.

computeQuantileSortRelation(Debug=False)[source]

Renders the bipolar-valued relation obtained from the self quantile sorting result.

computeSingletonRanking(Comments=False, Debug=False)[source]

Renders the sorted bipolar net determinatation of outrankingness minus outrankedness credibilities of all singleton choices.

res = ((netdet,singleton,dom,absorb)+)

computeVetoesStatistics(level=None)[source]

renders the cut level vetos in dictionary format: vetos = {‘all’: n0, ‘strong: n1, ‘weak’:n2}.

computeVetosShort()[source]

renders the number of vetoes and real vetoes in an OutrankingDigraph.

computeWeightsConcentrationIndex()[source]

Renders the Gini concentration index of the weight distribution

Based on the triangle summation formula.

defaultDiscriminationThresholds(quantile={'ind': 10, 'weakVeto': 60, 'veto': 80, 'pref': 20}, Debug=False, comments=False)[source]

updates the discrimination thresholds with the percentiles from the performance differences.

Parameters:
quantile = {‘ind’: 10, ‘pref’: 20, ‘weakVeto’: 60, ‘veto: 80}.
export3DplotOfActionsCorrelation(plotFileName='correlation', Type='pdf', Comments=False, bipolarFlag=False, dist=True, centeredFlag=False)[source]

use Calmat and R for producing a png plot of the principal components of the the actions ordinal correlation table.

export3DplotOfCriteriaCorrelation(plotFileName='correlation', Type='pdf', Comments=False, bipolarFlag=False, dist=True, centeredFlag=False)[source]

use Calmat and R for producing a plot of the principal components of the criteria ordinal correlation table.

saveActionsCorrelationTable(fileName='tempcorr.prn', delimiter=' ', Bipolar=True, Silent=False, Centered=False)[source]

Delimited save of correlation table

saveCriteriaCorrelationTable(fileName='tempcorr.prn', delimiter=' ', Bipolar=True, Silent=False, Centered=False)[source]

Delimited save of correlation table

saveXMCDA2RubisChoiceRecommendation(fileName='temp', category='Rubis', subcategory='Choice Recommendation', author='digraphs Module (RB)', reference='saved from Python', comment=True, servingD3=False, relationName='Stilde', graphValuationType='bipolar', variant='standard', instanceID='void', stringNA='NA', _OldCoca=True, Debug=False)[source]

save complete Rubis problem and result in XMCDA 2.0 format with unicode encoding.

saveXMCDAOutrankingDigraph(fileName='temp', category='Rubis', subcategory='Choice Recommendation', author='digraphs Module (RB)', reference='saved from Python', comment=True, servingD3=False, relationName='Stilde', valuationType='bipolar', variant='standard', instanceID='void')[source]

save complete Rubis problem and result in XMCDA format with unicode encoding.

saveXMLRubisOutrankingDigraph(name='temp', category='Rubis outranking digraph', subcategory='Choice recommendation', author='digraphs Module (RB)', reference='saved from Python', noSilent=False, servingD3=True)[source]

save complete Rubis problem and result in XML format with unicode encoding.

showAll()[source]

specialize the general showAll method with criteria and performance tableau output

showCriteriaCorrelationTable(isReturningHTML=False)[source]

prints the criteriaCorrelationIndex in table format

showCriteriaHierarchy()[source]

shows the Rubis clustering of the ordinal criteria correlation table

showCriterionRelationTable(criterion, actionsSubset=None)[source]

prints the relation valuation in actions X actions table format.

showMarginalVersusGlobalOutrankingCorrelation(Sorted=True, Threading=False, nbrOfCPUs=None, Comments=True)[source]

Show method for computeCriterionCorrelation results.

showPairwiseComparison(a, b, hasSymetricThresholds=True, Debug=False, isReturningHTML=False, hasSymmetricThresholds=True)[source]

renders the pairwise comprison parameters on all criteria in html format

showPairwiseComparisonsDistributions()[source]

show the lt,leq, eq, geq, gt distributions for all pairs

showPairwiseOutrankings(a, b, hasSymetricThresholds=True, Debug=False, isReturningHTML=False, hasSymmetricThresholds=True)[source]
showPerformanceTableau(actionsSubset=None)[source]

Print the performance Tableau.

showRelationTable(IntegerValues=False, actionsSubset=None, Sorted=True, hasLPDDenotation=False, hasLatexFormat=False, hasIntegerValuation=False, relation=None, ReflexiveTerms=True)[source]

prints the relation valuation in actions X actions table format.

showShort()[source]

specialize the general showShort method with the criteria.

showSingletonRanking(Comments=True, Debug=False)[source]

Calls self.computeSingletonRanking(comments=True,Debug = False). Renders and prints the sorted bipolar net determinatation of outrankingness minus outrankedness credibilities of all singleton choices. res = ((netdet,sigleton,dom,absorb)+)

showVetos(cutLevel=None, realVetosOnly=False)[source]

prints all veto situations observed in the OutrankingDigraph instance.

class outrankingDigraphs.PolarisedOutrankingDigraph(digraph=None, level=None, KeepValues=True, AlphaCut=False, StrictCut=False)[source]

Bases: digraphs.PolarisedDigraph, outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Specilised digraphs.PolarisedDigraph instance for Outranking Digraphs.

Warning

If called with argument digraph=None, a RandomBipolarOutrankingDigraph instance is generated first.

class outrankingDigraphs.RandomBipolarOutrankingDigraph(numberOfActions=7, numberOfCriteria=7, weightDistribution='random', weightScale=[1, 10], commonScale=[0.0, 100.0], commonThresholds=[(10.0, 0.0), (20.0, 0.0), (80.0, 0.0), (80.0, 0.0)], commonMode=('uniform', None, None), hasBipolarVeto=True, Normalized=False)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
n := nbr of actions, p := number criteria,
scale := [Min,Max], thresholds := [h,q,v]

Specialization of the OutrankingDigraph class for generating temporary Digraphs from random performance tableaux.

class outrankingDigraphs.RandomElectre3OutrankingDigraph(numberOfActions=7, numberOfCriteria=7, weightDistribution='random', weightScale=[1, 10], commonScale=[0.0, 100.0], commonThresholds=[(10.0, 0.0), (20.0, 0.0), (80.0, 0.0)], commonMode=['uniform', None, None])[source]

Bases: outrankingDigraphs.Electre3OutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
n := nbr of actions, p := number criteria, scale := [Min,Max],
thresholds := [h,q,v]

Specialization of the OutrankingDigraph class for generating temporary Digraphs from random performance tableaux.

class outrankingDigraphs.RandomOutrankingDigraph(numberOfActions=7, numberOfCriteria=7, weightDistribution='random', weightScale=[1, 10], commonScale=[0.0, 100.0], commonThresholds=[(10.0, 0.0), (20.0, 0.0), (80.0, 0.0), (80.0, 0.0)], commonMode=('uniform', None, None), hasBipolarVeto=True, Normalized=False)[source]

Bases: outrankingDigraphs.RandomBipolarOutrankingDigraph

Dummy for obsolete RandomOutrankingDigraph Class

class outrankingDigraphs.RobustOutrankingDigraph(filePerfTab=None, Debug=False, hasNoVeto=True)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the general OutrankingDigraph class for robustness anaylsis.

saveAMPLDataFile(name='temp', Unique=False, Comments=True)[source]

save the ampl reverse data for cplex

saveXMLRubisOutrankingDigraph(name='temp', category='Rubis outranking robustness digraph', subcategory='Choice recommendation', author='digraphs Module (RB)', reference='saved from Python', comment=True, servingD3=True)[source]

save complete robust Rubis problem and result in XML format with unicode encoding.

showRelationTable()[source]

specialisation for integer values

class outrankingDigraphs.RubisRestServer(host='http://leopold-loewenheim.uni.lu/cgi-bin/xmlrpc_cgi.py', Debug=False)[source]

Bases: xmlrpc.client.ServerProxy

xmlrpc-cgi Proxy Server for accessing on-line a Rubis Rest Solver.

Example Python3 session:

>>> from outrankingDigraphs import RubisRestServer
>>> solver = RubisRestServer()
>>> solver.ping()
*************************************************
* This is the Leopold-Loewenheim Apache Server  *
* of the University of Luxembourg.              *
* Welcome to the Rubis XMCDA 2.0 Web service    *
* R. Bisdorff (c) 2009-2013                     *
* November 2013, version REST/D4 1.1            *
*************************************************
>>> from perfTabs import RandomCBPerformanceTableau
>>> t = RandomCBPerformanceTableau(numberOfActions=5,numberOfCriteria=7)
>>> solver.submitProblem(t)
The problem submission was successful !
Server ticket: l4qfAP0RfBBvyjsL
>>> solver.showHTMLSolution()
Created new window in existing browser session.
>>> solver.saveXMCDA2Solution()
The solution request was successful.
Saving XMCDA 2.0 encoded solution in file Solutionl4qfAP0RfBBvyjsL.xml
>>> ...
ping(Debug=False)[source]
saveXMCDA2Solution(fileName=None, Debug=False)[source]

Save the solution in XMCDA 2.0 encoding.

showHTMLSolution(ticket=None, valuation=None)[source]

Show XMCDA 2.0 solution in a default browser window. The valuation parameter may set the correct style sheet.

Parameter:

  • valuation: ‘bipolar’ or ‘robust’. By default the valuation type is set automatically at problem submission.
submitProblem(perfTab, valuation='bipolar', hasVeto=True, argTitle='XMCDA 2.0 encoding', Debug=False)[source]

Submit PerformanceTableau class instances.

Parameters:

  • valuation: ‘bipolar’, ‘robust’, ‘integer’
  • hasVeto: Switch on or off vetoes
  • argTitle: set specific application title
submitXMCDA2Problem(fileName, valuation=None, Debug=False)[source]

Submit stored XMCDA 2.0 encoded performance tableau.

Warning

An <_.xml> file extension is assumed !

class outrankingDigraphs.StochasticBipolarOutrankingDigraph(argPerfTab=None, sampleSize=50, samplingSeed=None, distribution='triangular', spread=1.0, likelihood=0.9, coalition=None, hasNoVeto=False, hasBipolarVeto=True, Normalized=False, Debug=False, SeeSampleCounter=False)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph

Stochastic bipolar outranking digraph based on multiple criteria of uncertain significance.

The digraph’s bipolar valuation represents the median of sampled outranking relations with a sufficient likelihood (default = 90%) to remain positive, repectively negative, over the possible criteria significance ranges.

Each criterion i’ significance weight is supposed to be a triangular random variables of mode w_i in the range 0 to 2*w_i.

Parameters:

  • argPerfTab: PerformanceTableau instance or the name of a stored one. If None, a random instance is generated.
  • sampleSize: number of random weight vectors used for Monte Carlo simulation.
  • distribution: {triangular|extTriangular|uniform|beta(2,2)|beta(4,4)}, probability distribution used for generating random weights
  • spread: weight range = weight mode +- (weight mode * spread)
  • likelihood: 1.0 - frequency of valuations of opposite sign compared to the median valuation.
  • other standard parameters from the BipolarOutrankingDigraph class (see documentation).
computeCDF(x, y, rValue)[source]

computes by interpolation the likelihood of a given rValue with respect to the sampled r(x,y) valuations.

Parameters:

  • action key x
  • action key y
  • r(x,y)
computeCLTLikelihoods(distribution='triangular', Debug=False)[source]

Renders the pairwise CLT likelihood of the at least as good as relation neglecting all considerable large performance differences polarisations.

showRelationStatistics(argument='likelihoods', actionsSubset=None, hasLatexFormat=False, Bipolar=False)[source]

prints the relation statistics in actions X actions table format.

showRelationTable(IntegerValues=False, actionsSubset=None, hasLPDDenotation=False, hasLatexFormat=False, hasIntegerValuation=False, relation=None)[source]

specialising BipolarOutrankingDigraph.showRelationTable() for stochstic instances.

class outrankingDigraphs.UnanimousOutrankingDigraph(argPerfTab=None, coalition=None, hasNoVeto=False)[source]

Bases: outrankingDigraphs.OutrankingDigraph, perfTabs.PerformanceTableau

Parameters:
performanceTableau (fileName of valid py code)

Specialization of the general OutrankingDigraph class for temporary unanimous outranking digraphs

Back to the Installation

xmcda module

xmcda.saveRobustRubisChoiceXSL(fileName='xmcda2RubisRobustChoice.xsl')[source]

Save the robust version of the Rubis Best-Choice XMCDA 2.0 XSL style sheet in the current working directory This style sheet allows to browse an XMCDA 2.0 encoded robust Rubis Best-Choice recommendation.

Note

The XSL styles heet must be present in the same working directory as the XMCDA encoded data file.

xmcda.saveRubisChoiceXSL(fileName='xmcda2RubisChoice.xsl')[source]

Save the local Rubis Best-Choice XMCDA 2.0 XSL style sheet in the current working directory This style sheet allows to browse an XMCDA 2.0 encoded Rubis Best-Choice recommendation.

Note

The XSL styles heet must be present in the same working directory as the XMCDA encoded data file.

xmcda.saveRubisXSL(fileName='xmcda2Rubis.xsl', Extended=True)[source]

Save the standard Rubis XMCDA 2.0 XSL style sheet in the current working directory. This style sheet allows to visualize an XMCDA 2.0 encoded performance tableau in a browser.

Note

The XSL styles heet must be present in the same working directory as the XMCDA encoded data file.

xmcda.saveXMCDARubisBestChoiceRecommendation(problemFileName=None, tempDir='.', valuationType=None)[source]

Store an XMCDA2 encoded solution file of the Rubis best-choice recommendation.

The valuationType parameter allows to work:

  • on the standard bipolar outranking digraph (valuationType = ‘bipolar’, default),
  • on the normalized –[-1,1] valued– bipolar outranking digraph (valuationType = ‘normalized’),
  • on the robust –ordinal criteria weights– bipolar outranking digraph (valuationType = ‘robust’),
  • on the confident outranking digraph (valuationType = ‘confident’),
  • ignoring considerable performances differences (valuationType = ‘noVeto’).

Note

The method requires an Unix like OS like Ubuntu or Mac OSX and depends on:

  • the R statistics package for Principal Component Analysis graphic,
  • the C calmat matrix interpreter (On http://leopold-loewenheim.uni.lu/svn/repos/Calmat/ see README)
  • the xpdf ressources ( ...$ apt-get install xpdf on Ubuntu) for converting pdf files to ppm format, and ppm files to png format.
xmcda.showXMCDARubisBestChoiceRecommendation(problemFileName=None, valuationType=None)[source]

Launches a browser window with the XMCDA2 solution of the Rubis Solver computed from a stored XMCDA2 encoded performance tableau.

The valuationType parameter allows to work:

  • on the standard bipolar outranking digraph (valuationType = ‘bipolar’, default),
  • on the normalized –[-1,1] valued– bipolar outranking digraph (valuationType = ‘normalized’),
  • on the robust –ordinal criteria weights– bipolar outranking digraph (valuationType = ‘robust’),
  • on the confident outranking digraph (valuationType = ‘confident’),
  • ignoring considerable performances differences (valuationType = ‘noVeto’).

Example:

>>> import xmcda
>>> from randomPerfTabs import RandomCBPerformanceTableau
>>> t = RandomCBPerformanceTableau()
>>> t.saveXMCDA2('example')
>>> xmcda.showXMCDARubisBestChoiceRecommendation(problemFileName='example')

Back to the Installation

sparseOutrankingDigraphs module

Digraph3 collection of python3 modules for Algorithmic Decision Theory applications

Module for sparse pre-ranked outranking digraphs

Copyright (C) 2016 Raymond Bisdorff

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR ANY PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

class sparseOutrankingDigraphs.PreRankedConfidentOutrankingDigraph(argPerfTab, quantiles=None, quantilesOrderingStrategy='average', LowerClosed=False, componentRankingRule='Copeland', minimalComponentSize=1, distribution='triangular', betaParameter=2, confidence=90.0, Threading=False, tempDir=None, nbrOfCPUs=1, nbrOfThreads=1, save2File=None, CopyPerfTab=True, Comments=False, Debug=False)[source]

Bases: sparseOutrankingDigraphs.PreRankedOutrankingDigraph, perfTabs.PerformanceTableau

Main class for the multiprocessing implementation of pre-ranked sparse confident outranking digraphs.

The sparse outranking digraph instance is decomposed with a confident q-tiling sort into a partition of quantile equivalence classes which are linearly ordered by average quantile limits (default).

With each quantile equivalence class is associated a ConfidentBipolarOutrankingDigraph object which is restricted to the decision actions gathered in this quantile equivalence class.

By default, the number of quantiles is set to a tenth of the number of decision actions, i.e. quantiles = order//10. The effective number of quantiles can be much lower for large orders; for instance quantiles = 250 gives good results for a digraph of order 25000.

For other parameters settings, see the corresponding classes: sortingDigraphs.QuantilesSortingDigraph and outrankingDigraphs.ConfidentBipolarOutrankingDigraph .

computeCLTLikelihoods(distribution='triangular', betaParameter=None, Debug=False)[source]

Renders the pairwise CLT likelihood of the at least as good as relation neglecting all considerable large performance differences polarisations.

showRelationTable(IntegerValues=False, actionsSubset=None, Sorted=True, LikelihoodDenotation=True, hasLatexFormat=False, hasIntegerValuation=False, relation=None, Debug=False)[source]

prints the relation valuation in actions X actions table format.

class sparseOutrankingDigraphs.PreRankedOutrankingDigraph(argPerfTab, quantiles=None, quantilesOrderingStrategy='average', LowerClosed=False, componentRankingRule='Copeland', minimalComponentSize=1, Threading=False, tempDir=None, nbrOfCPUs=1, nbrOfThreads=1, save2File=None, CopyPerfTab=True, Comments=False, Debug=False)[source]

Bases: sparseOutrankingDigraphs.SparseOutrankingDigraph, perfTabs.PerformanceTableau

Main class for the multiprocessing implementation of pre-ranked sparse outranking digraphs.

The sparse outranking digraph instance is decomposed with a q-tiling sort into a partition of quantile equivalence classes which are linearly ordered by average quantile limits (default).

With each quantile equivalence class is associated a BipolarOutrankingDigraph object which is restricted to the decision actions gathered in this quantile equivalence class.

By default, the number of quantiles is set to a tenth of the number of decision actions, i.e. quantiles = order//10. The effective number of quantiles can be much lower for large orders; for instance quantiles = 250 gives good results for a digraph of order 25000.

For other parameters settings, see the corresponding sortingDigraphs.QuantilesSortingDigraph class.

actionOrder(action, ordering=None)[source]

Renders the order of a decision action in a given ordering

If ordering == None, the self.boostedOrder attribute is used.

actionRank(action, ranking=None)[source]

Renders the rank of a decision action in a given ranking

If ranking == None, the self.boostedRanking attribute is used.

computeActionCategories(action, Show=False, Debug=False, Comments=False, Threading=False, nbrOfCPUs=None)[source]

Renders the union of categories in which the given action is sorted positively or null into. Returns a tuple : action, lowest category key, highest category key, membership credibility !

computeBoostedOrdering(orderingRule='Copeland')[source]

Renders an ordred list of decision actions ranked in increasing preference direction following the orderingRule on each component.

computeBoostedRanking(rankingRule='Copeland')[source]

Renders an ordred list of decision actions ranked in decreasing preference direction following the rankingRule on each component.

computeCategoryContents(Reverse=False, Comments=False, StoreSorting=True, Threading=False, nbrOfCPUs=None)[source]

Computes the sorting results per category.

computeCriterion2RankingCorrelation(criterion, Threading=False, nbrOfCPUs=None, Debug=False, Comments=False)[source]

Renders the ordinal correlation coefficient between the global linar ranking and the marginal criterion relation.

computeMarginalVersusGlobalRankingCorrelations(Sorted=True, ValuedCorrelation=False, Threading=False, nbrCores=None, Comments=False)[source]

Method for computing correlations between each individual criterion relation with the corresponding global ranking relation.

Returns a list of tuples (correlation,criterionKey) sorted by default in decreasing order of the correlation.

If Threading is True, a multiprocessing Pool class is used with a parallel equivalent of the built-in map function.

If nbrCores is not set, the os.cpu_count() function is used to determine the number of available cores.

computeNewActionCategories(action, sorting, Debug=False, Comments=False)[source]

Renders the union of categories in which the given action is sorted positively or null into. Returns a tuple : action, lowest category key, highest category key, membership credibility !

computeNewSortingCharacteristics(actions, relation, Comments=False)[source]

Renders a bipolar-valued bi-dictionary relation representing the degree of credibility of the assertion that “actions x in A belongs to category c in C”, i.e. x outranks low category limit and does not outrank the high category limit (if LowerClosed).

htmlPerformanceHeatmap(argCriteriaList=None, argActionsList=None, SparseModel=True, minimalComponentSize=1, RankingRule='Copeland', quantiles=None, strategy='average', ndigits=2, contentCentered=True, colorLevels=None, pageTitle='Performance Heatmap', Correlations=False, Threading=False, nbrOfCPUs=None, Debug=False)[source]

Specialization of the generic perfTabs method for spare outranking digraphs.

Renders the Brewer RdYlGn 5,7, or 9 levels colored heatmap of the performance table actions x criteria in html format.

showActionSortingResult(action)[source]

shows the quantiles sorting result all (default) of a subset of the decision actions.

showActions()[source]

Prints out the actions disctionary.

showComponents(direction='increasing')[source]
showCriteria(IntegerWeights=False, Debug=False)[source]

print Criteria with thresholds and weights.

showCriteriaQuantiles()[source]
showDecomposition(direction='decreasing')[source]
showMarginalVersusGlobalRankingCorrelation(Sorted=True, Threading=False, nbrOfCPUs=None, Comments=True)[source]

Show method for computeCriterionCorrelation results.

showNewActionCategories(action, sorting)[source]

Prints the union of categories in which the given action is sorted positively or null into.

showNewActionsSortingResult(actions, sorting, Debug=False)[source]

shows the quantiles sorting result all (default) of a subset of the decision actions.

showRelationTable(compKeys=None)[source]

Specialized for showing the quantiles decomposed relation table. Components are stored in an ordered dictionary.

showShort(fileName=None, WithFileSize=True)[source]

Default (__repr__) presentation method for big outranking digraphs instances:

>>> from sparseOutrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=100,seed=1)
>>> g = PreRankedOutrankingDigraph(t,quantiles=10)
>>> print(g)
*----- show short --------------*
Instance name     : randomCBperftab_mp
# Actions         : 100
# Criteria        : 7
Sorting by        : 10-Tiling
Ordering strategy : average
Ranking rule      : Copeland
# Components      : 19
Minimal size      : 1
Maximal size      : 22
Median size       : 2
fill rate         : 0.116
----  Constructor run times (in sec.) ----
Total time        : 0.14958
QuantilesSorting  : 0.06847
Preordering       : 0.00071
Decomposing       : 0.07366
Ordering          : 0.00130
<class 'sparseOutrankingDigraphs.PreRankedOutrankingDigraph'> instance        
showSorting(Descending=True, isReturningHTML=False, Debug=False)[source]

Shows sorting results in decreasing or increasing (Reverse=False) order of the categories. If isReturningHTML is True (default = False) the method returns a htlm table with the sorting result.

class sparseOutrankingDigraphs.SparseOutrankingDigraph(argPerfTab=None, coalition=None, actionsSubset=None, hasNoVeto=False, hasBipolarVeto=True, Normalized=False, CopyPerfTab=True, BigData=False, Threading=False, tempDir=None, WithConcordanceRelation=True, WithVetoCounts=True, nbrCores=None, Debug=False, Comments=False)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph

Abstract root class for linearly decomposed sparse digraphs.

computeDecompositionSummaryStatistics()[source]

Returns the summary of the distribution of the length of the components as follows:

summary = {'max': maxLength,
           'median':medianLength,
           'mean':meanLength,
           'stdev': stdLength,
           'fillrate': fillrate,
                      (see computeFillRate()}
computeDeterminateness()[source]

Computes the Kendalll distance in % of self with the all median valued (indeterminate) digraph.

computeFillRate()[source]

Renders the sum of the squares (without diagonal) of the orders of the component’s subgraphs over the square (without diagonal) of the big digraph order.

computeOrderCorrelation(order, Debug=False)[source]

Renders the ordinal correlation K of a sparse digraph instance when compared with a given linear order (from worst to best) of its actions

K = sum_{x != y} [ min( max(-self.relation(x,y)),other.relation(x,y), max(self.relation(x,y),-other.relation(x,y)) ]

K /= sum_{x!=y} [ min(abs(self.relation(x,y),abs(other.relation(x,y)) ]

Note

Renders a dictionary with the key ‘correlation’ containing the actual bipolar correlation index and the key ‘determination’ containing the minimal determination level D of self and the other relation.

D = sum_{x != y} min(abs(self.relation(x,y)),abs(other.relation(x,y)) / n(n-1)

where n is the number of actions considered.

The correlation index with a completely indeterminate relation is by convention 0.0 at determination level 0.0 .

Warning

self must be a normalized outranking digraph instance !

computeOrdinalCorrelation(other, Debug=False)[source]

Renders the ordinal correlation K of a SpareOutrakingDigraph instance when compared with a given compatible (same actions set) other Digraph instance.

K = sum_{x != y} [ min( max(-self.relation(x,y)),other.relation(x,y), max(self.relation(x,y),-other.relation(x,y)) ]

K /= sum_{x!=y} [ min(abs(self.relation(x,y),abs(other.relation(x,y)) ]

Note

The global outranking relation of SparesOutrankingDigraph instances is contructed on the fly from the ordered dictionary of the components.

Renders a dictionary with a ‘correlation’ key containing the actual bipolar correlation index K and a ‘determination’ key containing the minimal determination level D of self and the other relation, where

D = sum_{x != y} min(abs(self.relation(x,y)),abs(other.relation(x,y)) / n(n-1)

and where n is the number of actions considered.

The correlation index K with a completely indeterminate relation is by convention 0.0 at determination level 0.0 .

exportGraphViz(fileName=None, actionsSubset=None, bestChoice=set(), worstChoice=set(), noSilent=True, graphType='png', graphSize='7, 7', relation=None)[source]

export GraphViz dot file for graph drawing filtering.

exportSortingGraphViz(fileName=None, actionsSubset=None, direction='decreasing', noSilent=True, graphType='pdf', graphSize='7, 7', fontSize=10, relation=None, Debug=False)[source]

export GraphViz dot file for weak order (Hasse diagram) drawing filtering from SortingDigraph instances.

Example:

>>> print('==>> Testing graph viz export of sorting Hasse diagram')
>>> MP  = True
>>> nbrActions=100
>>> tp = RandomCBPerformanceTableau(numberOfActions=nbrActions,
...                         Threading=MP,
...                         seed=100)
>>> bg = PreRankedOutrankingDigraph(tp,CopyPerfTab=True,quantiles=20,
...                             quantilesOrderingStrategy='average',
...                             componentRankingRule='Copeland',
...                             LowerClosed=False,
...                             minimalComponentSize=1,
...                            Threading=MP,nbrOfCPUs=8,
...                            #tempDir='.',
...                             nbrOfThreads=8,
...                             Comments=False,Debug=False)
>>> print(bg)
*----- show short --------------*
Instance name     : randomCBperftab_mp
# Actions         : 100
# Criteria        : 7
Sorting by        : 20-Tiling
Ordering strategy : average
Ranking rule      : Copeland
# Components      : 36
Minimal order     : 1
Maximal order     : 11
Average order     : 2.8
fill rate         : 4.121%
----  Constructor run times (in sec.) ----
Total time        : 0.15991
QuantilesSorting  : 0.11717
Preordering       : 0.00066
Decomposing       : 0.04009
Ordering          : 0.00000
<class 'sparseOutrankingDigraphs.PreRankedOutrankingDigraph'> instance
>>> bg.showComponents()
*--- Relation decomposition in increasing order---*
35: ['a010']
34: ['a024', 'a060']
33: ['a012']
32: ['a018']
31: ['a004', 'a054', 'a075', 'a082']
30: ['a099']
29: ['a065']
28: ['a025', 'a027', 'a029', 'a041', 'a059']
27: ['a063']
26: ['a047', 'a066']
25: ['a021']
24: ['a007']
23: ['a044']
22: ['a037', 'a062', 'a090', 'a094', 'a098', 'a100']
21: ['a005', 'a040', 'a051', 'a093']
20: ['a015', 'a030', 'a052', 'a055', 'a064', 'a077']
19: ['a006', 'a061']
18: ['a049']
17: ['a001', 'a033']
16: ['a016', 'a028', 'a032', 'a035', 'a057', 'a079', 'a084', 'a095']
15: ['a043']
14: ['a002', 'a017', 'a023', 'a034', 'a067', 'a072', 'a073', 'a074', 'a088', 'a089', 'a097']
13: ['a048']
12: ['a078', 'a092']
11: ['a070']
10: ['a014', 'a026', 'a039', 'a058', 'a068', 'a083', 'a086']
9: ['a008', 'a022', 'a038', 'a081', 'a091', 'a096']
8: ['a020']
7: ['a069']
6: ['a045']
5: ['a003', 'a009', 'a013', 'a031', 'a036', 'a056', 'a076']
4: ['a042', 'a071']
3: ['a085']
2: ['a019', 'a080', 'a087']
1: ['a046']
0: ['a011', 'a050', 'a053']
>>> bg.exportSortingGraphViz(actionsSubset=bg.boostedRanking[:100])     
pre-ranked digraph
htmlRelationMap(actionsSubset=None, tableTitle='Relation Map', relationName='r(x R y)', symbols=['+', '&middot;', '&nbsp;', '-', '_'], Colored=True, ContentCentered=True)[source]

renders the relation map in actions X actions html table format.

ordering2Preorder(ordering)[source]

Renders a preordering (a list of list) of a linar order (worst to best) of decision actions in increasing preference direction.

ranking2Preorder(ranking)[source]

Renders a preordering (a list of list) of a ranking (best to worst) of decision actions in increasing preference direction.

recodeValuation(newMin=-1, newMax=1, Debug=False)[source]

Specialization for recoding the valuation of all the partial digraphs and the component relation. By default the valuation domain is normalized to [-1;1]

relation(x, y, Debug=False)[source]

Dynamic construction of the global outranking characteristic function r(x S y).

showDecomposition(direction='decreasing')[source]

Prints on the console the decomposition structure of the sparse outranking digraph instance in decreasing (default) or increasing preference direction.

showHTMLMarginalQuantileLimits()[source]

shows the marginal quantiles limits.

showHTMLRelationMap(actionsSubset=None, Colored=True, tableTitle='Relation Map', relationName='r(x S y)', symbols=['+', '&middot;', '&nbsp;', '&#150;', '&#151;'])[source]

Launches a browser window with the colored relation map of self.

showRelationMap(fromIndex=None, toIndex=None, symbols=None, actionsList=None)[source]

Prints on the console, in text map format, the location of the diagonal outranking components of the sparse outranking digraph.

By default, symbols = {‘max’:’┬’,’positive’: ‘+’, ‘median’: ‘ ‘,
‘negative’: ‘-‘, ‘min’: ‘┴’}

Example:

>>> from sparseOutrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=50,seed=1)
>>> bg = PreRankedOutrankingDigraph(t,quantiles=10,minimalComponentSize=5)
>>> print(bg)
*----- show short --------------*
Instance name     : randomCBperftab_mp
# Actions         : 50
# Criteria        : 7
Sorting by        : 10-Tiling
Ordering strategy : average
Ranking Rule      : Copeland
# Components      : 7
Minimal size      : 5
Maximal size      : 13
Median size       : 6
fill rate         : 16.898%
----  Constructor run times (in sec.) ----
Total time        : 0.08494
QuantilesSorting  : 0.04339
Preordering       : 0.00034
Decomposing       : 0.03989
Ordering          : 0.00024
<class 'sparseOutrankingDigraphs.PreRankedOutrankingDigraph'> instance         
>>> bg.showRelationMap()
 ┬+++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴ ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
 + ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
--- -┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
-┴-+ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴ ┬-+┬+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴   +┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴+  +  ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴-+- ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴  + ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴   -  ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴ +++-+++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴+ +++++++++-+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴+- +--+++++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴--+ -++++++-+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴++++ +-   ++ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴--+-+ +++++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴-+-++- ++++--┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴-++-++- + -+-┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴---- ++- + ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴-+--++++- -++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴--- --+++ ++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴+-+-++-+-+ +┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴-+- -+++-++ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴  -  + + ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴  -+ + ++┬++┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴++ +++++++++┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ -- -+-++  ┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴++++ ++++++-┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴----- ++-┬+┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴  +++- -++-+┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴-----++ -++┬┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +-+-+-+ -++┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴+   +++ ┬+┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴-- --+++  -┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴--┴+ -┴--+ ┬┬┬┬┬┬┬┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +++++++┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴+ +++-+┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴--  +++┬┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴--    ++┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴+-+  +++┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ +- + --┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴---+++ +┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴- ┴-+++ ┬┬┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴  ┬┬┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴  ++ ┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ - -┬┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ -+  ┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴  ┴  ┬
┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴┴ 
Component ranking rule: Copeland
>>> 
sortingRelation(x, y, Debug=False)[source]

Dynamic construction of the quantiles sorting characteristic function r(x QS y).

Back to the Installation

sortingDigraphs module

class sortingDigraphs.QuantilesSortingDigraph(argPerfTab=None, limitingQuantiles=None, LowerClosed=False, PrefThresholds=True, hasNoVeto=False, outrankingType='bipolar', WithSortingRelation=True, CompleteOutranking=False, StoreSorting=False, CopyPerfTab=False, Threading=False, tempDir=None, nbrCores=None, nbrOfProcesses=None, Comments=False, Debug=False)[source]

Bases: sortingDigraphs.SortingDigraph

Specialisation of the sortingDigraph Class for sorting of a large set of alternatives into quantiles delimited ordered classes.

Note

The constructor requires a valid PerformanceTableau instance. If no number of limiting quantiles is given, then a default profile with the limiting quartiles Q0,Q1,Q2, Q3 and Q4 is used on each criteria. By default upper closed limits of categories are supposed to be used in the sorting.

Example Python3 session:

>>> from sortingDigraphs import QuantilesSortingDigraph
>>> from randomPerfTabs import RandomCBPerformanceTableau
>>> t = RandomCBPerformanceTableau(numberOfActions=7,numberOfCriteria=5,
...                                weightDistribution='equiobjectives')
>>> qs = QuantilesSortingDigraph(t,limitingQuantiles=7)
>>> qs.showSorting()
*--- Sorting results in descending order ---*
]0.86 - 1.00]:       []
]0.71 - 0.86]:       ['a03']
]0.57 - 0.71]:       ['a04']
]0.43 - 0.57]:       ['a04', 'a05', 'a06']
]0.29 - 0.43]:       ['a01', 'a02', 'a06', 'a07']
]0.14 - 0.29]:       []
]< - 0.14]:          []
>>> qs.showQuantileOrdering()
]0.71-0.86] : ['a03']
]0.43-0.71] : ['a04']
]0.43-0.57] : ['a05']
]0.29-0.57] : ['a06']
]0.29-0.43] : ['a07', 'a02', 'a01']
>>> qs.exportGraphViz('quantilesSorting')
_images/quantilesSorting.png
computeCategoryContents(Reverse=False, Comments=False, StoreSorting=True, Threading=False, nbrOfCPUs=None)[source]

Computes the sorting results per category.

computeQuantileOrdering(strategy=None, Descending=True, HTML=False, Comments=False, Debug=False)[source]
Parameters:
  • Descending: listing in decreasing (default) or increasing quantile order.
  • strategy: ordering in an {‘optimistic’ (default) | ‘pessimistic’ | ‘average’} in the uppest, the lowest or the average potential quantile.
computeSortingCharacteristics(action=None, Comments=False, StoreSorting=False, Debug=False, Threading=False, nbrOfCPUs=None)[source]

Renders a bipolar-valued bi-dictionary relation representing the degree of credibility of the assertion that “action x in A belongs to category c in C”, ie x outranks low category limit and does not outrank the high category limit.

computeSortingRelation(categoryContents=None, Debug=False, StoreSorting=True, Threading=False, nbrOfCPUs=None, Comments=False)[source]

constructs a bipolar sorting relation using the category contents.

computeWeakOrder(Descending=True, Debug=False)[source]

Specialisation for QuantilesSortingDigraphs.

getActionsKeys(action=None, withoutProfiles=True)[source]

extract normal actions keys()

showActionCategories(action, Debug=False, Comments=True, Threading=False, nbrOfCPUs=None)[source]

Renders the union of categories in which the given action is sorted positively or null into. Returns a tuple : action, lowest category key, highest category key, membership credibility !

showActionsSortingResult(actionSubset=None, Debug=False)[source]

shows the quantiles sorting result all (default) of a subset of the decision actions.

showHTMLQuantileOrdering(Descending=True, strategy='optimistic')[source]

Shows the html version of the quantile preordering in a browser window.

The ordring strategy is either:
  • optimistic, following the upper quantile limits (default),
  • pessimistic, following the lower quantile limits,
  • average, following the averag of the upper and lower quantile limits.
showHTMLSorting(Reverse=True)[source]

shows the html version of the sorting result in a browser window.

showOrderedRelationTable(direction='decreasing')[source]

Showing the relation table in decreasing (default) or increasing order.

showQuantileOrdering(strategy=None)[source]

Dummy show method for the commenting computeQuantileOrdering() method.

showSorting(Reverse=True, isReturningHTML=False, Debug=False)[source]

Shows sorting results in decreasing or increasing (Reverse=False) order of the categories. If isReturningHTML is True (default = False) the method returns a htlm table with the sorting result.

showSortingCharacteristics(action=None)[source]

Renders a bipolar-valued bi-dictionary relation representing the degree of credibility of the assertion that “action x in A belongs to category c in C”, ie x outranks low category limit and does not outrank the high category limit.

showWeakOrder(Descending=True)[source]

Specialisation for QuantilesSortingDigraphs.

class sortingDigraphs.SortingDigraph(argPerfTab=None, argProfile=None, scaleSteps=5, minValuation=-100.0, maxValuation=100.0, isRobust=False, hasNoVeto=False, LowerClosed=True, StoreSorting=True, Threading=False, tempDir=None, nbrCores=None, Debug=False)[source]

Bases: outrankingDigraphs.BipolarOutrankingDigraph, perfTabs.PerformanceTableau

Specialisation of the digraphs.BipolarOutrankingDigraph Class for Condorcet based multicriteria sorting of alternatives.

Besides a valid PerformanceTableau instance we require a sorting profile, i.e.:

  • a dictionary <categories> of categories with ‘name’, ‘order’ and ‘comment’

  • a dictionary <criteriaCategoryLimits> with double entry:

    [criteriakey][categoryKey] containing a [‘minimum’] and a [‘maximum’] value in the scale of the criterion respecting the order of the categories.

Template of required data for a 4-sorting:

categories = {
              'c1': { 'name': 'week','order': 1,
                      'lowLimit': 0,'highLimit': 25,
                      'comment': 'lowest category',},
              'c2': { 'name': 'ok','order': 2,
                      'lowLimit': 25,'highLimit': 50,
                      'comment': 'medium category',},
              'c3': { 'name': 'good','order': 3,
                      'lowLimit': 50,'highLimit': 75,
                      'comment': 'highest category',},
              'c4': { 'name': 'excellent','order': 4,
                      'lowLimit': 75,'highLimit': 100,
                      'comment': 'highest category',},
 }
criteriaCategoryLimits['LowerClosed'] = True # default
criteriaCategoryLimits[g] = {
        'c1': {'minimum':0, 'maximum':25},
        'c2': {'minimum':25, 'maximum':50},
        'c3': {'minimum':50, 'maximum':75},
        'c4': {'minimum':75, 'maximum':200},
 }

A template named tempProfile.py is providied in the digraphs module distribution.

Note

We generally require a performanceTableau instance and a filename where categories and a profile my be read from. If no such filename is given, then a default profile with five, equally spaced, categories is used on each criteria. By default lower-closed limts of categories are supposed to be used in the sorting.

Example Python3 session:

>>> from sortingDigraphs import SortingDigraph
>>> from randomPerfTabs import RandomPerformanceTableau
>>> t = RandomPerformanceTableau(seed=1)
>>> [x for x in t.actions]
['a01', 'a02', 'a03', 'a04', 'a05', 'a06', 'a07', 'a08',
'a09', 'a10', 'a11', 'a12', 'a13']
>>> so = SortingDigraph(t,scaleSteps=5)
# so gives a sorting result into five lower closed ordered
# categories enumerated from 0 to 5.
>>> so.showSorting()
*--- Sorting results in descending order ---*
]> - 4]:     ['a02', 'a03', 'a11']
]4 - 3]:     ['a04', 'a07', 'a08', 'a09', 'a10', 'a11', 'a12', 'a13']
]3 - 2]:     ['a04', 'a05', 'a06', 'a09', 'a12']
]2 - 1]:     ['a01']
]1 - 0]:     []
# Notice that some alternatives, like a04, a09, a11 and a12 are sorted
# into more than one adjacent category. Weak ordering the sorting result
# into ordered adjacent categories gives following result:
>>> so.showWeakOrder(strategy='average',Descending=True)
Weak ordering by average normalized 5-sorting limits
]  >  -80.0] : ['a02', 'a03']
]100.0-60.0] : ['a11']
] 80.0-60.0] : ['a07', 'a08', 'a10', 'a13']
] 80.0-40.0] : ['a04', 'a09', 'a12']
] 60.0-40.0] : ['a05', 'a06']
] 40.0-20.0] : ['a01']
computeCategoryContents(Reverse=False, StoreSorting=True, Comments=False)[source]

Computes the sorting results per category.

computeSortingCharacteristics(action=None, StoreSorting=True, Comments=False, Debug=False, Threading=False, nbrOfCPUs=None)[source]

Renders a bipolar-valued bi-dictionary relation representing the degree of credibility of the assertion that “action x in A belongs to category c in C”, ie x outranks low category limit and does not outrank the high category limit.

computeSortingRelation(categoryContents=None, StoreSorting=True, Debug=False)[source]

constructs a bipolar sorting relation using the category contents.

computeWeakOrder(Descending=False, strategy='average', Comments=False, Debug=False)[source]

specialisation of the showWeakOrder method. The weak ordering strategy may be:

“optimistic” (ranked by highest category limits), “pessimistic” (ranked by lowest category limits) or “average” (ranked by average category limits)
exportDigraphGraphViz(fileName=None, bestChoice=set(), worstChoice=set(), noSilent=True, graphType='png', graphSize='7, 7')[source]

export GraphViz dot file for digraph drawing filtering.

exportGraphViz(fileName=None, direction='decreasing', noSilent=True, graphType='png', graphSize='7, 7', fontSize=10, relation=None, Debug=False)[source]

export GraphViz dot file for weak order (Hasse diagram) drawing filtering from SortingDigraph instances.

getActionsKeys(action=None, withoutProfiles=True)[source]

extract normal actions keys()

htmlCriteriaCategoryLimits(tableTitle='Category limits')[source]

Renders category minimum and maximum limits for each criterion as a html table.

orderedCategoryKeys(Reverse=False)[source]

Renders the ordered list of category keys based on self.categories[‘order’] numeric values.

recodeValuation(newMin=-1.0, newMax=1.0, Debug=False)[source]

Recodes the characteristic valuation domain according to the parameters given.

Note

Default values gives a normalized valuation domain

saveCategories(fileName='tempCategories')[source]
saveProfilesXMCDA2(fileName='temp', category='XMCDA 2.0 format', user='sortinDigraphs Module (RB)', version='saved from Python session', title='Sorting categories in XMCDA-2.0 format.', variant='Rubis', valuationType='bipolar', isStringIO=False, stringNA='NA', comment='produced by saveProfilesXMCDA2()')[source]

Save profiles object self in XMCDA 2.0 format.

showActionCategories(action, Debug=False, Comments=True, Threading=False, nbrOfCPUs=None)[source]

Renders the union of categories in which the given action is sorted positively or null into. Returns a tuple : action, lowest category key, highest category key, membership credibility !

showActionsSortingResult(actionSubset=None, Debug=False)[source]

shows the quantiles sorting result all (default) of a subset of the decision actions.

showCriteriaCategoryLimits()[source]

Shows category minimum and maximum limits for each criterion.

showOrderedRelationTable(direction='decreasing')[source]

Showing the relation table in decreasing (default) or increasing order.

showSorting(Reverse=True, isReturningHTML=False)[source]

Shows sorting results in decreasing or increasing (Reverse=False) order of the categories. If isReturningHTML is True (default = False) the method returns a htlm table with the sorting result.

showSortingCharacteristics(action=None)[source]

Renders a bipolar-valued bi-dictionary relation representing the degree of credibility of the assertion that “action x in A belongs to category c in C”, ie x outranks low category limit and does not outrank the high category limit.

showWeakOrder(Descending=False, strategy='average')[source]

dummy for computeWeakOrder with Comments=True

Back to the Installation

votingDigraphs module

A tutorial with coding examples is available here: Computing the winner of an election

class votingDigraphs.ApprovalVotingProfile(fileVotingProfile=None, seed=None)[source]

Bases: votingDigraphs.VotingProfile

A specialised class for approval voting profiles

Structure:

candidates = OrderedDict([('a', {'name': ...}),
              ('b', {'name': ...}),
              ..., ...])
voters = OrderedDict([('v1',{'weight':1.0}),('v2':{'weight':1.0}), ...])
## each specifies the subset of candidates he approves on
approvalBallot = {
    'v1' : ['b'],
    'v2' : ['a','b'],
    ...
    }

## each specifies the subset -disjoint from the approvalBallot-  of candidates he disapproves on
disApprovalBallot = {
    'v1' : ['a'],
    'v2' : [],
    ...
    }
computeBallot()[source]

Computes a complete ballot from the approval Ballot.

Parameters:
approvalEquivalence=False, disapprovalEquivalence=False.
save(name='tempAVprofile')[source]

Persistant storage of an approval voting profile.

Parameter:
name of file (without <.py> extension!).
save2PerfTab(fileName='votingPerfTab', isDecimal=True, valueDigits=2)[source]

Persistant storage of an approval voting profile in the format of a standard performance tableau. For each voter v, the performance of candidate x corresponds to:

2 is approved; 0, if disapproved; 1, otherwise,
showApprovalResults()[source]

Renders the approval obtained by each candidates.

showDisApprovalResults()[source]

Renders the disapprovals obtained by each candidates.

showResults()[source]
class votingDigraphs.CondorcetDigraph(argVotingProfile=None, approvalVoting=False, coalition=None, majorityMargins=False, hasIntegerValuation=False)[source]

Bases: digraphs.Digraph

Specialization of the general Digraph class for generating bipolar-valued marginal pairwise majority difference digraphs.

Parameters:

stored voting profile (fileName of valid py code) or voting profile object
optional, coalition (sublist of voters)

Example Python3 session

>>> from votingDigraphs import *
>>> v = RandomLinearVotingProfile(numberOfVoters=101,numberOfCandidates=5)
>>> v.showLinearBallots()
v101(1.0):   ['a5', 'a1', 'a2', 'a4', 'a3']
v100(1.0):   ['a4', 'a1', 'a5', 'a3', 'a2']
v89(1.0):    ['a4', 'a5', 'a1', 'a2', 'a3']
v88(1.0):    ['a3', 'a2', 'a5', 'a1', 'a4']
v87(1.0):    ['a5', 'a2', 'a4', 'a3', 'a1']
v86(1.0):    ['a5', 'a3', 'a1', 'a4', 'a2']
v85(1.0):    ['a5', 'a3', 'a2', 'a4', 'a1']
v84(1.0):    ['a3', 'a1', 'a2', 'a4', 'a5']
...
...
>>> g = CondorcetDigraph(v,hasIntegerValuation=True)
>>> g.showRelationTable()
* ---- Relation Table -----
 S   |  'a1'  'a2'   'a3'   'a4'  'a5'        
-----|------------------------------------------------------------
'a1' |   -     33     9      11    21        
'a2' |  -33    -     -19     -1    -5        
'a3' |  -9     19    -       5     -1        
'a4' |  -11    1      -5     -     -9        
'a5' |  -21    5       1     9      -
>>> g.computeCondorcetWinner()
['a1']
>>> g.exportGraphViz()
*---- exporting a dot file dor GraphViz tools ---------*
Exporting to rel_randLinearProfile.dot
dot -Grankdir=BT -Tpng rel_randLinearProfile.dot -o rel_randLinearProfile.png
_images/rel_randLinearProfile.png
computeArrowRaynaudRanking(linearOrdered=True, Debug=False)[source]

Renders a ranking of the actions following Arrow&Raynaud’s rule.

computeCondorcetWinner()[source]

compute the Condorcet winner(s) renders always a, potentially empty, list

computeKohlerRanking(linearOrdered=True, Debug=False)[source]

Renders a ranking of the actions following Kohler’s rule.

constructApprovalBallotRelation(hasIntegerValuation=False)[source]

Renders the votes differences between candidates on the basis of an approval ballot.

constructBallotRelation(hasIntegerValuation)[source]

Renders the marginal majority between candidates on the basis of a complete ballot.

constructMajorityMarginsRelation(hasIntegerValuation=True)[source]

Renders the marginal majority between candidates on the basis of an approval ballot.

class votingDigraphs.LinearVotingProfile(fileVotingProfile=None, numberOfCandidates=5, numberOfVoters=9, seed=None)[source]

Bases: votingDigraphs.VotingProfile

A specialised class for linear voting profiles

Structure:

candidates = OrderedDict([('a', ...) ,('b', ...),('c', ...), ...])
voters = OrderedDict([('1',{'weight':1.0}), ('2',{'weight':1.0}), ...])
## each specifies a a ranked list of candidates
## from the best to the worst
linearBallot = {
    '1' : ['b','c','a', ...],
    '2' : ['a','b','c', ...],
    ...
    }

Sample Python3 session

>>> from votingDigraphs import *
>>> v = RandomLinearVotingProfile(numberOfVoters=5,numberOfCandidates=3)
>>> v.showLinearBallots()
voters(weight)       candidates rankings
v4(1.0):     ['a1', 'a2', 'a3']
v5(1.0):     ['a1', 'a2', 'a3']
v1(1.0):     ['a2', 'a1', 'a3']
v2(1.0):     ['a1', 'a2', 'a3']
v3(1.0):     ['a1', 'a3', 'a2']
>>> v.computeRankAnalysis()
{'a1': [4.0, 1.0, 0],
 'a2': [1.0, 3.0, 1.0],
 'a3': [0, 1.0, 4.0]}
>>> v.showRankAnalysisTable()
*----  Rank analysis tableau -----*
  ranks |  1    2    3    | Borda score
 -------|------------------------------
   'a1' |  4    1    0    |   6
   'a2' |  1    3    1    |   10
   'a3' |  0    1    4    |   14
>>> v.computeUninominalVotes()
{'a1': 4.0, 'a3': 0, 'a2': 1.0}
>>> v.computeSimpleMajorityWinner()
['a1']
>>> v.computeBordaScores()
{'a1': 6.0, 'a3': 14.0, 'a2': 10.0}
>>> v.computeBordaWinners()
['a1']
>>> v.computeInstantRunoffWinner()
['a1']
computeBallot()[source]

Computes a complete ballot from the linear Ballot.

computeBordaScores()[source]

compute Borda scores from the rank analysis

computeBordaWinners()[source]

compute the Borda winner from the Borda scores, ie the list of candidates with the minimal Borda score.

computeInstantRunoffWinner(Comments=False)[source]

compute the instant runoff winner from a linear voting ballot

computeRankAnalysis()[source]

compute the number of ranks each candidate obtains

computeSimpleMajorityWinner(Comments=False)[source]

compute the winner in a uninominal Election from a linear ballot

computeUninominalVotes(candidates=None, linearBallot=None)[source]

compute uninominal votes for each candidate in candidates sublist and restricted linear ballots

save(name='templinearprofile')[source]

Persistant storage of a linear voting profile.

Parameter:
name of file (without <.py> extension!).
save2PerfTab(fileName='votingPerfTab', isDecimal=True, valueDigits=2)[source]

Persistant storage of a linear voting profile in the format of a rank performance Tableau. For each voter v, the rank performance of candidate x corresponds to:

number of candidates - linearProfile[v].index(x)

showHTMLVotingHeatmap(criteriaList=None, actionsList=None, SparseModel=False, minimalComponentSize=1, RankingRule='Copeland', quantiles=None, strategy='average', ndigits=0, colorLevels=None, pageTitle='Voting Heatmap', Correlations=True, Threading=False, nbrOfCPUs=1, Debug=False)[source]

Show the linear voting profile as a rank performance heatmap. The linear voting profile is previously saved to a stored Performance Tableau.

(see perfTabs.PerformanceTableau.showHTMLPerformanceHeatmap() )

showLinearBallots()[source]

show the linear ballots

showRankAnalysisTable(Sorted=True, ndigits=0, Debug=False)[source]

Print the rank analysis tableau.

If Sorted (True by default), the candidates are ordered by increasing Borda Scores.

In case of decimal voters weights, ndigits allows to format the decimal precision of the numerical output.

class votingDigraphs.RandomApprovalVotingProfile(numberOfVoters=9, numberOfCandidates=5, minSizeOfBallot=1, maxSizeOfBallot=2, seed=None)[source]

Bases: votingDigraphs.ApprovalVotingProfile

A specialized class for approval voting profiles.

generateRandomApprovalBallot(minSizeOfBallot, maxSizeOfBallot, seed=None)[source]

Renders a randomly generated approval ballot.

generateRandomDisApprovalBallot(minSizeOfBallot, maxSizeOfBallot, seed=None)[source]

Renders a randomly generated approval ballot.

class votingDigraphs.RandomLinearVotingProfile(numberOfVoters=9, numberOfCandidates=5, seed=None)[source]

Bases: votingDigraphs.LinearVotingProfile

A specialized class for random linwear voting profiles.

generateRandomLinearBallot(seed)[source]

Renders a randomly generated linear ballot.

class votingDigraphs.RandomVotingProfile(numberOfVoters=9, numberOfCandidates=5, hasRandomWeights=False, maxWeight=10, seed=None, Debug=False)[source]

Bases: votingDigraphs.VotingProfile

A subclass for generating random voting profiles.

generateRandomBallot(seed, Debug=False)[source]

Renders a randomly generated approval ballot from a shuffled list of candidates for each voter.

class votingDigraphs.VotingProfile(fileVotingProfile=None, seed=None)[source]

Bases: object

A general class for storing voting profiles.

General structure:

candidates = OrderedDict([('a', ...),('b', ...),('c', ...), ( ... ) ])
voters = OrderedDict([
('1', {'weight':1.0}),
('2', {'weight':1.0}),
...,
])
ballot = {     # voters x candidates x candidates
    '1': {     # bipolar characteristic {-1,0,1} of each voter's
          'a': { 'a':0,'b':-1,'c':0, ...},   # pairwise preferences
          'b': { 'a':1,'b':0, 'c':1, ...},
          'c': { 'a':0,'b':-1,'c':0, ...},
          ...,
    },
    '2': { 'a': { 'a':0, 'b':0, 'c':1, ...},
           'b': { 'a':0, 'b':0, 'c':1, ...},
           'c': { 'a':-1,'b':-1,'c':0, ...},
           ...,
    },
    ...,
}
save(name='tempVprofile')[source]

Persistant storage of an approval voting profile.

showAll(WithBallots=True)[source]

Show method for <VotingProfile> instances.

showVoterBallot(voter, hasIntegerValuation=False)[source]

Show the actual voting of a voter.

Back to the Installation

linearOrders module

A tutorial with coding examples is available here: Computing the winner of an election

class linearOrders.CopelandOrder(other, coDual=False, Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the Copèeland Order from a given bipolar-valued Digraph instance

class linearOrders.ExtendedPrudentDigraph(other, prudentBetaLevel=None, CoDual=False, Debug=False)[source]

Bases: digraphs.Digraph

Instantiates the associated extended prudent codual of the digraph enstance. Instantiates as other.__class__ ! Copies the case given the description, the criteria and the evaluation dictionary into self.

class linearOrders.KemenyOrder(other, orderLimit=7, Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the exact Kemeny Order from a given bipolar-valued Digraph instance of small order

class linearOrders.KohlerOrder(other, coDual=False, Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the Kohler Order from a given bipolar-valued Digraph instance

class linearOrders.LinearOrder(file=None, order=7)[source]

Bases: digraphs.Digraph

abstract class for digraphs which represent linear orders.

computeKemenyIndex(other)[source]

renders the Kemeny index of the self.relation (linear order) compared with a given bipolar-valued relation of a compatible other digraph (same nodes or actions).

computeOrder()[source]

computes the linear ordering from lowest (worst) to highest (best) of an instance of the LinearOrcer class by sorting by indegrees (gamma[x][1]).

computeRanking()[source]

computes the linear ordering from lowest (best, rankk = 1) to highest (worst rank=n) of an instance of the LinearOrcer class by sorting by outdegrees (gamma[x][0]).

exportDigraphGraphViz(fileName=None, bestChoice=set(), worstChoice=set(), noSilent=True, graphType='png', graphSize='7, 7')[source]

export GraphViz dot file for digraph drawing filtering.

exportGraphViz(fileName=None, isValued=True, bestChoice=set(), worstChoice=set(), noSilent=True, graphType='png', graphSize='7, 7')[source]

export GraphViz dot file for linear order drawing filtering.

htmlOrder()[source]

returns the html encoded presentation of a linear order

htmlRanking()[source]

returns the html encoded presentation of a linear order

showOrdering()[source]

shows the linearly ordered actions in list format.

showRanking()[source]

shows the linearly ordered actions in list format.

class linearOrders.NetFlowsOrder(other, coDual=False, Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the net flows Order from a given bipolar-valued Digraph instance

class linearOrders.OutFlowsOrder(other, coDual=False, Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the out flows Order from a given bipolar-valued Digraph instance

class linearOrders.PrincipalOrder(other, Colwise=True, imageType=None, plotFileName='principalOrdering', Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the order from the scores obtained by the first princiapl axis of the eigen deomposition of the covariance of the outdegrees of the valued digraph ‘other’.

class linearOrders.RandomLinearOrder(numberOfActions=10, Debug=False, OutrankingModel=False, Valued=False, seed=None)[source]

Bases: linearOrders.LinearOrder

Instantiates random linear orders

class linearOrders.RankedPairsOrder(other, coDual=False, Leximin=False, Cpp=False, isValued=False, isExtendedPrudent=False, Debug=False)[source]

Bases: linearOrders.LinearOrder

instantiates the Extended Prudent Ranked Pairs Order from a given bipolar-valued Digraph instance

Back to the Installation

weakOrders module

class weakOrders.KemenyWeakOrder(other, orderLimit=7, Debug=False)[source]

Bases: weakOrders.WeakOrder

Specialization of the abstract WeakOrder class for weak orderings resulting from the epistemic disjunctive fusion (omax operator) of all potential Kemeny linear orderings.

class weakOrders.KohlerArrowRaynaudFusionDigraph(outrankingDigraph, fusionOperator='o-max', Threading=True, Debug=False)[source]

Bases: weakOrders.WeakOrder

Specialization of the abstract WeakOrder class for ranking-by-choosing orderings resulting from the epistemic disjunctive (o-max fusion) or conjunctive (o-min operator) fusion of a Kohler linear best ordering and an Arrow-Raynaud linear worst ordering.

class weakOrders.PrincipalInOutDegreesOrdering(other, fusionOperator='o-max', imageType=None, plotFileName=None, Threading=True, Debug=False)[source]

Bases: weakOrders.WeakOrder

Specialization of abstract WeakOrder class for ranking by fusion of the principal orders of the variance-covariance of in- (Colwise) and outdegrees (Rowwise).

Example Python3 session with same outranking digraph g as shown in the RankingByChoosingDigraph example session (see below).

>>> from weakOrders import PrincipalInOutDegreesOrdering
>>> pro = PrincipalInOutDegreesOrdering(g,imageType="png",\ 
                 plotFileName="proWeakOrdering")
>>> pro.showWeakOrder()
Ranking by Choosing and Rejecting
 1st ranked ['a06'] (1.00)
   2nd ranked ['a05'] (1.00)
     3rd ranked ['a02'] (1.00)
       4th ranked ['a04'] (1.00)
       4th last ranked ['a04'] (1.00)
     3rd last ranked ['a07'] (1.00)
   2nd last ranked ['a01'] (1.00)
 1st last ranked ['a03'] (1.00)
>>> pro.showPrincipalScores(ColwiseOrder=True)
List of principal scores
Column wise covariance ordered
action       colwise         rowwise
a06          15.52934        13.74739
a05          7.71195         4.95199
a02          3.40812         0.70554
a04          2.76502         0.15189
a07          0.66875         -1.77637
a01          -3.19392        -5.36733
a03          -18.51409       -21.09102
_images/proWeakOrdering_Colwise.png
computeWeakOrder(ColwiseOrder=False)[source]

Specialisation for PrincipalInOutDegreesOrderings.

exportGraphViz(fileName=None, direction='ColwiseOrder', Comments=True, graphType='png', graphSize='7, 7', fontSize=10)[source]

Specialisation for PincipalInOutDegrees class.

direction = “Colwise” (best to worst, default) | “Rowwise” (worst to best)

showPrincipalScores(ColwiseOrder=False, RowwiseOrder=False)[source]

showing the principal in- (Colwise) and out-degrees (Rowwise) scores.

showWeakOrder(ColwiseOrder=False)[source]

Specialisation for PrincipalInOutDegreesOrderings.

class weakOrders.RankingByBestChoosingDigraph(digraph, Normalized=True, CoDual=False, Debug=False)[source]

Bases: weakOrders.RankingByChoosingDigraph

Specialization of abstract WeakOrder class for computing a ranking by best-choosing.

showWeakOrder()[source]

Specialisation of showWeakOrder() for ranking-by-best-choosing results.

class weakOrders.RankingByChoosingDigraph(other, fusionOperator='o-max', CoDual=False, Debug=False, CppAgrum=False, Threading=True)[source]

Bases: weakOrders.WeakOrder

Specialization of the abstract WeakOrder class for ranking-by-Rubis-choosing orderings.

Example python3 session:

>>> from outrankingDigraphs import *
>>> t = RandomCBPerformanceTableau(numberOfActions=7,\ 
            numberOfCriteria=5,\ 
            weightDistribution='equiobjectives')
>>> g = BipolarOutrankingDigraph(t,Normalized=True)
>>> g.showRelationTable()
* ---- Relation Table -----
  S   |   'a01'  'a02'  'a03'  'a04'  'a05'  'a06'  'a07'   
 -----|------------------------------------------------------------
'a01' |   +0.00  -1.00  -1.00  -0.33  +0.00  +0.00  +0.00  
'a02' |   +1.00  +0.00  -0.17  +0.33  +1.00  +0.33  +0.67  
'a03' |   +1.00  +0.67  +0.00  +0.33  +0.67  +0.67  +0.67  
'a04' |   +0.33  +0.17  -0.33  +0.00  +1.00  +0.67  +0.67  
'a05' |   +0.00  -0.67  -0.67  -1.00  +0.00  -0.17  +0.33  
'a06' |   +0.33  +0.00  -0.33  -0.67  +0.50  +0.00  +1.00  
'a07' |   +0.33  +0.00  -0.33  -0.67  +0.50  +0.17  +0.00  
>>> from weakOrders import RankingByChoosingDigraph
>>> rbc = RankingByChoosingDigraph(g)
>>> rbc.showWeakOrder()
Ranking by Choosing and Rejecting
  1st ranked ['a03'] (0.47)
   2nd ranked ['a02', 'a04'] (0.58)
    3rd ranked ['a06'] (1.00)
    3rd last ranked ['a06'] (1.00)
   2nd last ranked ['a07'] (0.50)
  1st last ranked ['a01', 'a05'] (0.58)
>>> rbc.exportGraphViz('weakOrdering')
*---- exporting a dot file for GraphViz tools ---------*
Exporting to converse-dual_rel_randomCBperftab.dot
dot -Grankdir=BT -Tpng converse-dual_rel_randomCBperftab.dot 
   -o weakOrdering.png 
_images/weakOrdering.png
>>> rbc.showOrderedRelationTable(direction="decreasing")
* ---- Relation Table -----
  S   |  'a03'  'a04'  'a02'  'a06'  'a07'  'a01'  'a05'      
 -----|------------------------------------------------------------
'a03' |   -      0.33   0.17   0.33   0.33   1.00   0.67     
'a04' |  -0.33    -     0.00   0.67   0.67   0.33   1.00     
'a02' |  -0.17   0.00    -     0.33   0.67   1.00   0.67     
'a06' |  -0.33  -0.67  -0.33    -     0.17   0.33   0.17     
'a07' |  -0.33  -0.67  -0.67  -0.17    -     0.33   0.33     
'a01' |  -1.00  -0.33  -1.00  -0.33  -0.33    -     0.00     
'a05' |  -0.67  -1.00  -0.67  -0.17  -0.33   0.00    -       
computeRankingByBestChoosing(Forced=False)[source]

Dummy for blocking recomputing without forcing.

computeRankingByLastChoosing(Forced=False)[source]

Dummy for blocking recomputing without forcing.

showRankingByChoosing(rankingByChoosing=None)[source]

Dummy for showWeakOrder method

showWeakOrder(rankingByChoosing=None)[source]

Specialization of generic method. Without argument, a weak ordering is recomputed from the valued self relation.

class weakOrders.RankingByLastChoosingDigraph(digraph, Normalized=True, CoDual=False, Debug=False)[source]

Bases: weakOrders.RankingByChoosingDigraph

Specialization of abstract WeakOrder class for computing a ranking by rejecting.

showWeakOrder()[source]

Specialisation of showWeakOrder() for ranking-by-last-choosing results.

class weakOrders.RankingByPrudentChoosingDigraph(digraph, CoDual=False, Normalized=True, Odd=True, Limited=0.2, Comments=False, Debug=False, SplitCorrelation=True)[source]

Bases: weakOrders.RankingByChoosingDigraph

Specialization for ranking-by-rejecting results with prudent single elimination of chordless circuits. By default, the cut level for circuits elimination is set to 20% of the valuation domain maximum (1.0).

class weakOrders.WeakOrder(file=None, order=7)[source]

Bases: digraphs.Digraph

Abstract class for weak orderings’ specialized methods.

exportDigraphGraphViz(fileName=None, bestChoice=set(), worstChoice=set(), noSilent=True, graphType='png', graphSize='7, 7')[source]

export GraphViz dot file for digraph drawing filtering.

exportGraphViz(fileName=None, relation=None, direction='best', noSilent=True, graphType='png', graphSize='7, 7', fontSize=10)[source]

export GraphViz dot file for weak order (Hasse diagram) drawing filtering.

showOrderedRelationTable(direction='decreasing', originalRelation=False)[source]

Showing the relation table in decreasing (default) or increasing order.

showRankingByChoosing(actionsList=None, rankingByChoosing=None)[source]

Dummy name for showWeakOrder() method

showWeakOrder(rankingByChoosing=None)[source]

A show method for self.rankinByChoosing result.

class weakOrders.WeakRankingOrder(other, rankings, Debug=False)[source]

Bases: weakOrders.WeakOrder

Specialization of the abstract WeakOrder class for weak orderings resulting from the epistemic disjunctive fusion (omax operator) of a list of rankings.

Example application:

>>> from weakOrders import WeakRankingOrder
>>> from sparseOutrankingDigraphs import PreRankedOutrankingDigraph
>>> t = RandomPerformanceTableau()
>>> pr = PreRankedOutrankingDigraph(t,10,quantilesOrderingStrategy='average')
>>> r1 = qr.boostedRanking
>>> pro = PreRankedOutrankingDigraph(t,10,quantilesOrderingStrategy='optimistic')
>>> r2 = pro.boostedRanking
>>> prp = QuantilesRankingDigraph(t,10,quantilesOrderingStrategy='pessimistic')
>>> r3 = prp.boostedRanking
>>> wqr = WeakQuantilesRankingOrder(pr,[r1,r2,r3])
>>> wqr.exportGraphViz('partialOrdering',graphType="pdf")

Back to the Installation

randomNumbers module

class randomNumbers.CauchyRandomVariable(position=0.0, scale=1.0, seed=None, Debug=False)[source]

Bases: object

Cauchy random variable generator.

Parameters:
  • position := median (default=0.0) of the Cauchy distribution
  • scale := typical spread (default=1.0) with respect to median
  • seed := integer (default=None) for fixing the sequence generation.
Cauchy quantile (inverse cdf) function:
Q(x|position,scale) = position + scale*tan[pi(x-1/2)]
Cauchy Distribution
random()[source]

generating a Cauchy random number.

class randomNumbers.DiscreteRandomVariable(discreteLaw=None, seed=None, Debug=False)[source]

Bases: object

Discrete random variable generator

Parameters:
discreteLaw := dictionary with integer values
as keys and probabilities as float values,
seed := integer for fixing the sequence generation.
Example usage:
>>> from randomNumbers import DiscreteRandomVariable
>>> discreteLaw = {0:0.0478,
                   1:0.3349,
                   2:0.2392,
                   3:0.1435,
                   4:0.0957,
                   5:0.0670,
                   6:0.0478,
                   7:0.0096,
                   8:0.0096,
                   9:0.0048,}
## initialze the random generator
>>> rdv = DiscreteRandomVariable(discreteLaw,seed=1)
## sample discrete random variable and
## count frequencies of obtained values
>>> sampleSize = 1000
>>> frequencies = {}
>>> for i in range(sampleSize):
        x = rdv.random() 
        try:
            frequencies[x] += 1
        except:
            frequencies[x] = 1
## print results
>>> results = [x for x in frequencies]
>>> results.sort()
>>> counts= 0.0
>>> for x in results:
        counts += frequencies[x]
        print  ('%s, %d, %.3f, %.3f' % (x, frequencies[x],
                  float(frequencies[x])/float(sampleSize),
                  discreteLaw[x]))
>>> print ('# of valid samples = %d' % counts)
random()[source]

generating discrete random values from a discrete random variable.

class randomNumbers.ExtendedTriangularRandomVariable(lowLimit=0.0, highLimit=1.0, mode=None, probRepart=0.5, seed=None, Debug=False)[source]

Bases: object

Extended triangular random variable generator

Parameters:
  • mode := most frequently observed value
  • probRepart := probability mass distributed until the mode
  • seed := integer for fixing the sequence generation.
Extended triangular distribution
random()[source]

generating an extended triangular random number.

Back to the Installation

digraphsTools module

Python3+ implementation of Digraph3 tools

Copyright (C) 2016-2017 Raymond Bisdorff

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

digraphsTools.all_perms(str)[source]
digraphsTools.flatten(iterable, ltypes=<class 'collections.abc.Iterable'>)[source]

Flattens a list of lists into a flat list.

Main usage:

>>> listOfLists = [[1,2],[3],[4]]
>>> [x for x in flatten(listOfLists)]
[1,2,3,4]
digraphsTools.generateBipolarGrayCode(n)[source]

Bipolar version of generateGrayCode. X is a partially determined -1 vector.

digraphsTools.generateGrayCode(n)[source]

Knuth ACP (4) 7.2.1.1. p.6 Algorithm G

digraphsTools.generateLooplessGrayCode(n)[source]

Knuth ACP (4) 7.2.1.1. p.7 Algorithm L

digraphsTools.grayCode(n)[source]
digraphsTools.omax(Med, L, Debug=False)[source]

epistemic disjunction for bipolar outranking characteristics computation: Med is the valuation domain median and L is a list of r-valued statement characteristics.

digraphsTools.omin(Med, L, Debug=False)[source]

epistemic conjunction of a list L of bipolar outranking characteristics. Med is the given valuation domain median.

digraphsTools.powerset(S)[source]

Power set generator iterator.

Parameter S may be any object that is accepted as input by the set class constructor.

digraphsTools.ranking2preorder(R)[source]
digraphsTools.timefn(fn)[source]

A decorator for automate run time measurements from “High Performance Python” by M Gorelick & I Ozswald O’Reilly 2014 p.27

digraphsTools.total_size(o, handlers={}, verbose=False)[source]

Returns the approximate memory footprint of an object and all of its contents.

Automatically finds the contents of the following containers and their subclasses: tuple, list, deque, dict, set, frozenset, Digraph and BigDigraph. To search other containers, add handlers to iterate over their contents:

handlers = {SomeContainerClass: iter,
OtherContainerClass: OtherContainerClass.get_elements}

See http://code.activestate.com/recipes/577504/

Back to the Installation

arithmetics module

class arithmetics.QuadraticResiduesDigraph(integers=[3, 5, 7, 11, 13, 17, 19])[source]

Bases: digraphs.Digraph

The Legendre symbol (a/p) of any pair of non null integers a and p is:

  • 0 if a = 0 (mod p);
  • 1 if a is a quadratic residue in Zp, ie a in Qp;
  • -1 if a is a non quadratic residue unit in Zp, ie a in Up - Qp.

The Legendre symbol hence defines a bipolar valuation on pairs of non null integers. The reciprocity theorem of the Legendre symbol states that, for p being an odd prime, (a/p) = (p/a), apart from those pairs (a/p), where a = p = 3 (mod 4). In this case, (a/p) = -(p/a).

We may graphically illustrate the reciprocity theorem as follows:

>>> from arithmetics import *
>>> leg = QuadraticResiduesDigraph(primesBelow(20,Odd=True))
>>> from digraphs import AsymmetricPartialDigraph
>>> aleg = AsymmetricPartialDigraph(leg)
>>> aleg.exportGraphViz('legendreAsym')
Quadratic residues digraph asymmetric part
arithmetics.bezout(a, b)[source]

Renders d = gcd(a,b) and the Bezout coefficient x, y such that d = ax + by.

arithmetics.computePiDecimals(decimalWordLength=4, nbrOfWords=600, Comments=False)[source]

Renders at least decimalWordLenght * nbrOfWords (default: 4x600=2400) decimals of \pi. The Python transcription here recodes an original C code of unknown author (see [*]).

Uses the following infinite Euler series:

\pi = 2 * \sum_{n=0}^{\infty} [ (n !) / (1 * 3  * 5 ... * (2n+1)) ].

The series gives a new \pi decimal after adding in average 3.32 terms.

>>> from arithmetics import computePiDecimals
>>> from time import time
>>> t0=time();piDecimals = computePiDecimals(decimalWordLength=3,nbrOfWords=100);t1= time()
>>> print('pi = '+piDecimals[0]+'.'+piDecimals[1:])
pi = 3.14159265358979323846264338327950288419716939937510582097494459
2307816406286208998628034825342117067982148086513282306647093844609
5505822317253594081284811174502841027019385211055596446229489549303
8196442881097566593344612847564823378678316527120190914564856692346
034861045432664821339360726024914127372458700660630
>>> print('precision = '+str(len(piDecimals[1:]))+'decimals')
precision = 314 decimals
>>> print('%.4f' % (t1-t0)+' sec.')
0.0338 sec.
[*]Source: J.-P. Delahaye “Le fascinant nombre \pi”, Pour la science Belin 1997 p.95.
arithmetics.divisors(n, Sorted=True)[source]

Renders the list of divisors of integer n.

arithmetics.divisorsFunction(k, n)[source]

generic divisor function:

  • the number of divisors of n is divisorsFunction(0,n)
  • the sum of the divisors of n is divisorsFunction(1,n)
arithmetics.factorization(n)[source]
arithmetics.gcd(a, b)[source]

Renders the greatest common divisor of a and b.

arithmetics.isprime(n, precision=7)[source]

http://en.wikipedia.org/wiki/Miller-Rabin_primality_test#Algorithm_and_running_time

arithmetics.lcm(a, b)[source]

Renders the least common multiple of a and b.

arithmetics.moebius_mu(n)[source]

Implements the Moebius mu function on N based on n’s prime factorization: n = p1^e1 * ... * pk^ek with each ei >= 1 for i = 1, ..., k.

mu = 0 if ei > 1 for some i = 1, ... k else mu = (-1)^k.

arithmetics.pollard_brent(n)[source]

https://comeoncodeon.wordpress.com/2010/09/18/pollard-rho-brent-integer-factorization/

arithmetics.primeFactors(n, sort=True)[source]
arithmetics.primesBelow(N, Odd=False)[source]

http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 Input N>=6, Returns a list of primes, 2 <= p < N

arithmetics.solPartEqnDioph(a, b, c)[source]

renders a particular integer solution of the Diophantian equation ax + by = c.

arithmetics.totient(n)[source]

Implements the totient function rendering Euler’s number of coprime elements a in Zn.

arithmetics.zn_squareroots(n, Comments=False)[source]

Renders the quadratic residues of Zn as a dictionary.

arithmetics.zn_units(n, Comments=False)[source]

Renders the set of units of Zn.

Back to the Installation

Indices and tables

Tutorials