dexipy package
Subpackages
Submodules
dexipy.types module
Module dexipy.types defines type aliases and enumeration classess that are used throughout DEXiPy.
- class dexipy.types.BoundAssoc(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Enumeration associated with bounds that discretize continuous scales.
- Parameters:
Enum (int) – indicates the interval to which some corresponding bound \(b\) belongs.
- DOWN = -1
Indicates that \(b\) belongs to the interval \([..., b]\).
- UP = 1
Indicates that \(b\) belongs to the interval \([b, ...]\).
- dexipy.types.CallableNorm
Callable normalization functions that accept and return a list of floats.
- Type:
Type alias
alias of
Callable
[[…],list
[float
]]
- dexipy.types.CallableOperator
Callable and_op and or_op operator functions that accept a list of floats and return a single float.
- Type:
Type alias
alias of
Callable
[[list
[float
]],float
]
- dexipy.types.DexiAltData = dict[str, None | float | set[int] | list[float] | str] | list[dict[str, None | float | set[int] | list[float] | str]]
General internal representation of a single or multiple alternatives:
DexiAlternative | DexiAlternatives
.- Type:
Type alias
- dexipy.types.DexiAlternative
Internal representation of a single decision alternative:
dict[str, DexiValue | str]
. String value is allowed only with non-attribute entries, such as alternative “name” or “description”.- Type:
Type alias
alias of
dict
[str
,None
|float
|set
[int
] |list
[float
] |str
]
- dexipy.types.DexiAlternatives
Internal representation of multiple decision alternatives as
list[DexiAlternative]
.- Type:
Type alias
alias of
list
[dict
[str
,None
|float
|set
[int
] |list
[float
] |str
]]
- class dexipy.types.DexiEvalMethod(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Enumeration od DEXiPy evaluation methods.
- Parameters:
Enum (int) – Evaluation method.
- FUZZY = 3
Evaluation interpreting DEXi values as fuzzy set memberships (possibility distributions).
- FUZZYNORM = 4
Similar to FUZZY, but enforcing fuzzy normalization (the maximum distribution element must be equal to 1.0).
- PROB = 2
Evaluation interpreting DEXi values as probability distributions.
- SET = 1
Evaluation using sets (default).
- class dexipy.types.DexiOrder(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Enumeration of DexiScale preferential order.
- Parameters:
Enum (int) – Preferential order.
- ASCENDING = 1
Scale values are ordered from “bad” to “good” ones (default).
- DESCENDING = -1
Scale values are ordered from “good” to “bad” ones.
- NONE = 0
Scale values are not ordered by preference.
- class dexipy.types.DexiQuality(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
Enumeration of DexiScale value quality classes.
- Parameters:
Enum (int) – Scale value quality class.
- BAD = -1
A “bad” value class, indicating an undesired value.
- GOOD = 1
A “good” value class, indicating a desired value.
- NONE = 0
A “neutral” value class, neither particularly “good” or “bad”.
- dexipy.types.DexiValue = None | float | set[int] | list[float]
Admissible DEXi values that can be interpreted without knowing the DexiScale or DexiModel context. Used to represent DEXi values internally.
- Type:
Type alias
- dexipy.types.DexiValueSpecification = None | float | set[int] | list[float] | str | set[int | str] | tuple[int | str, ...] | dict[int | str, float]
Admissible DEXi values for user interaction. In addition to DexiValue, it accepts strings, tuples and value distributions represented by dictionaries. Requires a DexiScale or DexiModel context to be interpreted or converted to DexiValue.
- Type:
Type alias
dexipy.values module
Module dexipy.values contains helper classes and functions for handling DEXi values.
- class dexipy.values.DexiValues(value)
Bases:
object
A wrapper class around a DexiValue data element. An object of this class contains a value of type
dexipy.values.DexiValues
, on which methods operate.- Parameters:
value (DexiValue) – A DexiValue element stored internally and operated upon by methods.
- as_distr()
Convert self.value to a value distribution, if possible.
- Return type:
list[float] | None
- as_set(strict=False)
Convert self.value to a set, if possible. See
dexipy.values.dexi_value_as_set()
for details.- Parameters:
strict (bool, optional) – Defines the conversion when self.value is a value distribution. When True, only distributions that clearly represent sets, i.e., contain only 0.0 or 1.0 elements, are converted. When False, all elements with non-zero values are considered set members. Defaults to False.
- Return type:
set[int] | None
- check_value()
Check whether or not self.value contains valid DexiValue data.
- Return type:
bool
- reduce()
Reduces the data representation of self.value, if possible. See
dexipy.values.reduce_dexi_value()
for details.- Return type:
None | float | set[int] | list[float]
- reduce_value()
Returns a reduced data representation of self.value.
- Return type:
None
- val_str(scale, none=None, reduce=False, decimals=None, use_dict=True)
Returns a string representation of self.value. See
dexipy.dexi.value_text()
for more details.- Parameters:
scale (Any) – Expected a
dexipy.dexi.DexiScale
ordexipy.dexi.DexiAttribute
object.none (Optional[str], optional) – An optional string that is returned when the value cannot be interpreted. Defaults to None.
reduce (bool, optional) – Whether or not the value is reduced (see
reduce_dexi_value()
) prior to processing. Defaults to False.decimals (Optional[int], optional) – The number of decimals used to display float numbers. Defaults to None.
use_dict (bool, optional) – Whether or not the dictionary-form is used for displaying value distributions (rather than list-form). Defaults to True.
- Return type:
str | None
- value_type()
Determine the value type of self.value.
- Return type:
DexiValueType | None
- dexipy.values.aggregate_value(value, aggregate='mean', interpret='distribution')
Aggregates value to a single number or None.
- Parameters:
value (DexiValue) – A DexiValue (internal representation without strings).
aggregate (str, optional) – One of “min”, “max” or “mean”. Determines aggregation operation in the case that value is a set or distribution. Defaults to “mean”.
interpret (str) – Whether to interpret value distributions as sets (“set”) or distributions (“distribution”). Defaults to “distribution”.
- Returns:
Aggregated value or None.
- Return type:
Optional[int | float]
- dexipy.values.check_dexi_value(value)
Checks the data object and determines whether or not it represents a DexiValue.
Only the data structure is checked. Even if the structure is correct, value can still contain elements that may not be correct in the context of some specific DexiScale. For instance, the object may contain value indices not found in the scale definition.
- Parameters:
value (Any) – Value object to be checked.
- Returns:
Whether or not the object’s structure is valid for representing a DexiValue.
- Return type:
bool
- dexipy.values.check_dexi_value_specification(value)
Checks the data object and determines whether or not it represents a DexiValueSpecification.
Only the data structure is checked. Even if the structure is correct, value can still contain elements that may not be correct in the context of some specific DexiScale. For instance, the object may contain value names or indices not found in the scale definition.
- Parameters:
value (Any) – Value object to be checked.
- Returns:
Whether or not the object’s structure is valid for representing a DexiValue.
- Return type:
bool
- dexipy.values.compare_values(value1, value2)
Compare two DEXi values.
- Parameters:
value1 (DexiValue) – First value.
value2 (DexiValue) – Second value.
- Returns:
0 if values are equal, -1 if value1 < value2, +1 if value1 > value2 and None if values are incomparable. Values are incomparable if they are not of DexiValue type or if they represent two overlapping sets.
- Return type:
Optional[int]
- dexipy.values.compare_values_by_preference(value1, value2, order)
Compare two DEXi values, considering preference order.
- Parameters:
value1 (DexiValue) – First value.
value2 (DexiValue) – Second value.
order (Optional[DexiOrder]) – Preference order.
- Returns:
Returns result of
dexipy.values.compare_values()
, interpreted in the context of preference order. When order is None, results are retained. Results 0 (equal values) and None (incomparable values) are retained for any order. Results -1 and +1 are retained when order is ascending and reversed when order is descending. When order is DexiOrder.NONE, non-equal values return None.- Return type:
Optional[int]
- dexipy.values.dexi_value_as_distr(value)
Converts a DexiValue object to a value distribution.
- Parameters:
value (DexiValue) – A DexiValue.
- Returns:
value represented in terms of a value distribution, or None if it cannot be interpreted.
- Return type:
Optional[list[float]]
Examples
>>> dexi_value_as_distr(2) [0.0, 0.0, 1.0] >>> dexi_value_as_distr({1, 2}) [0.0, 1.0, 1.0] >>> dexi_value_as_distr({0: 0.5, 2: 1.0}) [0.5, 0.0, 1.0] >>> dexi_value_as_distr((1, 1, 2, 2)) [0.0, 1.0, 1.0]
- dexipy.values.dexi_value_as_set(value, strict=False)
Converts a DexiValue object to a set.
- Parameters:
value (DexiValue) – A DexiValue.
strict (bool, optional) – Defines the conversion from value distributions. When True, only distributions that clearly represent sets, i.e., contain only 0.0 or 1.0 elements, are converted. When False, all elements with non-zero values are considered set members, too. Defaults to False.
- Returns:
Resulting value set. None if value cannot be interpreted as a set.
- Return type:
Optional[set[int]]
Examples
>>> dexi_value_as_set([0, 1, 0.5, 1], strict = True) # returns None >>> dexi_value_as_set([0, 1, 0.0, 1], strict = True) {1, 3} >>> dexi_value_as_set([0, 1, 0.5, 1], strict = False) {1, 2, 3}
- dexipy.values.dexi_value_type(value)
Determines the DexiValueType of the argument.
- Parameters:
value (Any) – Value object to be checked.
- Returns:
Enumeration of the argument’s DEXi value type.
- Return type:
- dexipy.values.distr_to_dexi_string(value)
Convert a value distribution to a string that can be imported by DEXi/DEXiWin software.
- Parameters:
value (list) – Value distribution.
- Returns:
DEXi representation of value.
- Return type:
str
- dexipy.values.export_dexi_value(value)
Formats value so that it can be imported to DEXi/DEXiWin software.
- Parameters:
value (DexiValue) – A DexiValue to be formatted. Internal (non-text) representation of values is assumed.
- Returns:
String representation of value.
- Return type:
str
- Raises:
ValueError – When value is not a DexiValue or is represented in a way that cannot be interpreted without model context.
- dexipy.values.reduce_dexi_value(value)
Reduce a DexiValue to a smaller and possibly more comprehensible data representation, if possible.
- Typical reductions:
a tuple to set:
(1, 1, 2, 2) -> {1, 2}
a single-element tuple or set to int:
(1,) -> {1} -> 1
a distribution to set, if possible:
[1.0, 0.0, 1.0] -> {0, 2}
- Parameters:
value (DexiValue) – A DexiValue.
- Returns:
Reduced representation of value, or value itself if no reduction is possible.
- Return type:
DexiValue
Examples
>>> reduce_dexi_value((1, 1, 2, 2)) {1, 2} >>> reduce_dexi_value({1}) 1 >>> reduce_dexi_value([1.0, 0.0, 1.0]) {0, 2} >>> reduce_dexi_value([1.0, 0.5, 1.0]) # no reduction [1.0, 0.5, 1.0] >>> reduce_dexi_value({1: 1.0}) 1
- dexipy.values.reduce_set(value)
Reduces a DexiValue, represented as a set, to a smaller data representation, if possible.
- Typical reductions:
an empty set to None:
{} -> None
a single-element tuple or set to int:
(1,) -> {1} -> 1
or{"low"} -> "low"
- Parameters:
value (Any) – A DexiValue.
- Returns:
Reduced representation of value, or value itself if no reduction is possible.
- Return type:
DexiValue
Examples
>>> reduce_set(set()) # returns None >>> reduce_set({1}) 1 >>> reduce_set({1, 2}) # no reduction {1, 2} >>> reduce_set(0.1) # no reduction 0.1
dexipy.dexi module
Module dexipy.dexi is the main DEXiPy module. It defines all the main classess that constitute a DEXi model and exposes all functions that are usually used to read DEXi models, and evaluate and analyze decision alternatives.
- class dexipy.dexi.DexiAttribute(name='', description='', id=None, inputs=None, parent=None, link=None, scale=None, funct=None)
Bases:
object
DexiAttribute is a class representing DEXi attributes.
In a DEXi model, attributes are variables that represent observed properties of decision alternatives. Attributes are structured in a tree, so each attribute may, but need not, have one or more direct descendants (lower-level attributes) in the tree. Attributes without descendants are called basic and serve as model inputs. Attributes with one or more descendants are called aggregate and represent model outputs. In order to represent attribute hierarchies (directed acyclic graphs) rather than plain trees, some attributes may be linked: two attributes of which one links to another one collectively represent, in a conceptual sense, a single attribute in the hierarchy.
When completely defined, each attribute is associated with a value scale represented by a
dexipy.dexi.DexiScale
object. It is also expected that adexipy.dexi.DexiFunction
is defined for each aggregate attribute, where it serves for the aggregation or discretization of the attribute’s inputs to output values of that attribute.- Parameters:
name (str, optional) – Attribute name. Defaults to “”.
description (str, optional) – Attribute description. Defaults to “”.
id (Optional[str] optional) – Attribute ID. By default equals to name, but may be adjusted for uniqueness in the model context. Automatically adjusted after reading a DexiModel with
dexipy.parse.read_dexi()
. Defaults to None.inputs (Sequence[DexiAttribute], optional) – A vector of this attribute’s input attributes. Defaults to None.
parent (DexiAttribute | DexiModel, optional) – This attribute’s parent attribute in the DEXi model tree. By convention,
model.root.parent == model
. Defaults to None.link (DexiAttribute, optional) – An optional link to an alias of this attribute. Defaults to None.
scale (DexiScale, optional) – A scale associated with this attribute. Defaults to None.
funct (DexiFunction, optional) – An aggregation/discretization function associated with this attribute. Defaults to None.
- affects(attribute)
Checks if this attribute affects attribute. An attribute is affected if it lies on the path from the affecting attribute to the model root.
- Parameters:
attribute (DexiAttribute) – An attribute checked for being affected.
- Returns:
Is attribute affected by this attribute?
- Return type:
bool
- att_str()
Returns a string representation of the main non-empty attributes of this object.
- Returns:
A string representation of a dictionary containing the non-empty values of name, id, description, inputs, link, scale and funct.
- Return type:
str
- count()
Returns the number of input attributes of this attribute.
- Returns:
The number of input attributes.
- Return type:
int
- dim()
Returns dimensions of this attribute’s input attributes.
- Returns:
A list of all input attribute’s scale sizes. May contain None elements for undefined input scales.
- Return type:
list[Optional[int]]
- has_order(order)
Checks if this attribute’s scale has order.
- Returns:
If this attribute has a scale and scale.order equals to order.
- Return type:
bool
- Parameters:
order (DexiOrder)
- inp_index(inp)
Returns the index of inp in self.inputs.
- Parameters:
inp (DexiAttribute) – An attribute.
- Returns:
Index of inp, or None if not found.
- Return type:
Optional[int]
- is_aggregate()
Checks if this attribute is aggregate.
- Returns:
Is this attribute aggregate?
- Return type:
bool
- is_ascending()
Checks if this attribute’s scale is ascending.
- Returns:
Is this attribute’s scale ascending?
- Return type:
bool
- is_basic(include_linked=True)
Checks if this attribute is basic.
- Parameters:
include_linked (bool, optional) – Whether a linked attribute is considered basic. Defaults to True.
- Returns:
Is this attribute basic?
- Return type:
bool
- is_continuous()
Returns True is this attribute’s scale is continuous.
- Returns:
Does this attribute have a continuous scale?
- Return type:
bool
- is_descending()
Checks if this attribute’s scale is descending.
- Returns:
Is this attribute’s scale descending?
- Return type:
bool
- is_discrete()
Returns True is this attribute’s scale is discrete.
- Returns:
Does this attribute have a discrete scale?
- Return type:
bool
- is_link()
Checks if this attribute is linked.
- Returns:
Is this attribute linked, i.e., has a defined self.link?
- Return type:
bool
- is_ordered()
Checks if this attribute’s scale is ordered.
- Returns:
Is this attribute’s scale ordered?
- Return type:
bool
- level()
Returns the level of this attribute in the DEXi model. The level of DexiModel.root is 0.
- Returns:
The level of this attribute.
- Return type:
int
- model()
Returns a
dexipy.dexi.DexiModel
to which this attribute belongs.- Returns:
The model containing this attribute. None might be returned if this attribute is improperly “wired” (using self.parent) in the enclosing model.
- Return type:
Optional[DexiModel]
- ninp()
Returns the number of input attributes of this attribute.
- Returns:
The number of input attributes.
- Return type:
int
- structure()
Makes a specific indentation string used in DEXiPy to print DEXi model structure.
This method calls
dexipy.dexi.DexiAttribute.tree_indent()
with arguments that indent attributes by two characters per level.- Returns:
A DEXiPy indentation string, including connections with other attributes.
- Return type:
str
- tree_indent(none=' ', thru='|', link='*', last='+')
Creates a string indicating the level of this attribute and its connections with other attributes in the model. In model printouts, such a string can be used in front of the attribute name or ID, achieving an indented output.
- Parameters:
none (str, optional) – String to indicate no connection at a given tree level. Defaults to “ “.
thru (str, optional) – Vertical connection to attributes displayed below this one. Defaults to “|”.
link (str, optional) – Horizontal connection to this attribute and vertical connection to attributes displayed below. Defaults to “*”.
last (str, optional) – Horizontal connection to the attribute that occurs as last child of the parent attribute. Defaults to “+”.
- Returns:
An indentation string, including connections with other attributes.
- Return type:
str
- class dexipy.dexi.DexiContinuousScale(order=DexiOrder.ASCENDING, lpoint=-inf, hpoint=inf)
Bases:
DexiScale
DexiContinuousScale is a scale class representing continuous scales in DEXi.
- Parameters:
order (DexiOrder, optional) – Preferential order of the scale. Defaults to DexiOrder.ASCENDING.
lpoint (float) – Defines the interval [-Infinity, lpoint]. All float values lying in this interval are considered to be of a DexiQuality.BAD quality (for order = DexiOrder.ASCENDING) or DexiQuality.GOOD quality (for order = DexiOrder.DESCENDING).
hpoint (float) – Defines the interval [hpoint, +Infinity]. All float values lying in this interval are considered to be of a DexiQuality.GOOD quality (for order = DexiOrder.ASCENDING) or DexiQuality.BAD quality (for order = DexiOrder.DESCENDING).
- equal(scl)
Checks whether or not this scale is equal to another scale scl.
- Parameters:
scl (Optional[DexiScale]) – Expected a
dexipy.dexi.DexiScale
object.- Returns:
Is this scale equal to scl?
- Return type:
bool
- is_continuous()
Returns True is this scale is continuous.
- Returns:
Is this scale continous?
- Return type:
bool
- scale_str()
Returns a short string representing the scale to be used in DEXi model printouts.
- Returns:
A short string representation of this scale.
- Return type:
str
- value_quality(value)
Returns the quality (value class) of value.
- Parameters:
value (Any) – Some scale value, usually a number or string.
- Returns:
Value quality.
- Return type:
Optional[DexiQuality]
- class dexipy.dexi.DexiDiscreteScale(values, order=DexiOrder.ASCENDING, descriptions=[], quality=[])
Bases:
DexiScale
DexiDiscreteScale is a scale class representing qualitative (symbolic, discrete, verbal) scales in DEXi. Such scales are typical for DEXi models and are the only scale type supported by the DEXi Classic software.
An attribute associated with a discrete scale can take values from a finite (and usually small) set of string values contained in self.values. Additionally, each of these values is associated with
dexipy.types.DexiQuality
. The latter are contained in the list self.quality, which is of the same length as self.values.- Parameters:
order (DexiOrder, optional) – Preferential order of the scale. Defaults to DexiOrder.ASCENDING.
values (list[str]) – A list of qualitative scale values. Example:
self.values = ["low", "medium", "high"]
.descriptions (list[str], optional) – A list of textual descriptions of the corresponding self.values. If necessary, the list is internally paddedd with empty strings to the same length as self.values.
quality (list[DexiQuality], optional) – A list of qualities, corresponding to self.values. Should be of the same length as self.values. Defaults to [], which assigns default qualities using
dexipy.dexi.DexiDiscreteScale.default_quality()
.
- count()
Returns the number of discrete values of this scale.
- Returns:
The number of values or 0 for non-discrete scales.
- Return type:
int
- classmethod default_quality(order, nvals)
Makes a default list of value qualities.
- Parameters:
order (DexiOrder) – Preferential order of the scale.
nvals (int) – The number of discrete scale values.
- Returns:
A list of length nvals of value qualities. The list depends on order as follows:
DexiOrder.ASCENDING: Returns
[DexiQuality.BAD, ..., DexiQuality.GOOD]
DexiOrder.DESCENDING: Returns
[DexiQuality.GOOD, ..., DexiQuality.BAD]
DexiOrder.NONE: Returns
[...]
Here,
...
denotes a sufficiently long sequence ofDexiQuality.NONE
.- Return type:
list[DexiQuality]
- equal(scl)
Checks whether or not this scale is equal to another scale scl.
- Parameters:
scl (Optional[DexiScale]) – Expected a
dexipy.dexi.DexiScale
object.- Returns:
Is this scale equal to scl?
- Return type:
bool
- full_range()
Returns the full range of admissible values for this scale.
- Returns:
A set of all values or None for non-discrete scales.
- Return type:
Optional[set[int]]
- is_discrete()
Returns True is this scale is discrete.
- Returns:
Is this scale discrete?
- Return type:
bool
- scale_str()
Returns a short string representing the scale to be used in DEXi model printouts.
- Returns:
A short string representation of this scale.
- Return type:
str
- value_index(value)
Returns the index of value in the scale.
- Parameters:
value (str) – Some string.
- Raises:
ValueError – When value was not found.
- Returns:
Index of value in self.values.
- Return type:
int
- value_index_or_none(value)
Returns the index of value in the scale or None if not found.
- Parameters:
value (str) – Some string.
- Returns:
Index of value in self.values or None if value was not found.
- Return type:
Optional[int]
- value_quality(value)
Returns the quality (value class) of value.
- Parameters:
value (Any) – Some scale value, usually a number or string.
- Returns:
Value quality.
- Return type:
Optional[DexiQuality]
- class dexipy.dexi.DexiDiscretizeFunction(attribute=None, bounds=[], assoc=[], values=[])
Bases:
DexiFunction
DexiDiscretizeFunction represents DEXi functions that discretize numerical values of continuous attributes to qualitative values of discrete attributes. A DexiDiscretizeFunction can be associated only with a discrete attribute that has exactly one continuous input. The function discretizes numeric values of the input attribute and maps them to discrete values of the parent attribute. This function type is supported in DEXi Suite software, but not in DEXi Classic.
Objects of class DexiDiscretizeFunction define discretization rules in terms of three lists: values, bounds and assoc. Using n = self.nvals() to denote the length of values, the required lengths of bounds and assoc are n - 1,
The list bounds refers to values of the input attribute and partitions its scale in n intervals
[-Infinity, bound[0]], [bound[0], bound[1]], ..., [bound[n - 1], +Infinity]
.The list values defines the output DEXi values for each interval.
The list assoc contains
dexipy.types.BoundAssoc
elements that indicate to which interval, lower or higher, belong the corresponding bounds.When creating a DexiDiscretizeFunction, the determining argument is bounds. The remaining two arguments, values and assoc are padded to the correct length, possibly inserting None and BoundAssoc.DOWN, respectively.
- Parameters:
attribute (Optional[DexiAttribute], optional) – A
dexipy.dexi.DexiAttribute
to which this function is assigned. The attribute is required to be discrete (i.e., associated withdexipy.dexi.DexiDiscreteScale
) and must have exactly one continuous attribute (i.e., associated withdexipy.dexi.DexiContinuousScale
). Defaults to None.bounds (list[float], optional) – List of bounds. Defaults to [].
assoc (list, optional) – List of bound associations. Defaults to [].
values (list[DexiValue], optional) – List of output DEXi values corresponding to each interval induced by bounds. Defaults to [].
- bound_assoc(idx, default=None)
Returns association of the idx-th bound.
- Parameters:
idx (int) – A bound index.
default (BoundAssoc, optional) – An optional association returned for out-of-bound indices. Defaults to None.
- Returns:
Association of the idx-th bound or default when idx is out of bounds.
- Return type:
Optional[BoundAssoc]
- funct_str()
Creates a short string for displaying information about the function in printouts.
- Returns:
A short string, whose contents depends on this function’s type.
- Return type:
str
- nargs()
Returns the number of function arguments.
- Returns:
The number of this function’s arguments.
- Return type:
int
- nvals()
Returns this function size.
- Returns:
The number of this function’s decision rules. Returns 0 for function types that do not have rules.
- Return type:
int
- value(args)
Returns the function value for given arguments.
- Parameters:
args (float) – A single float function argument.
- Returns:
Function value for the given argument.
- Return type:
DexiValue
- class dexipy.dexi.DexiFunction(attribute=None)
Bases:
object
DexiFunction is a base class for representing DEXi aggregation and discretization functions.
- Parameters:
attribute (Optional[DexiAttribute], optional) – A
dexipy.dexi.DexiAttribute
to which this function is assigned. Defaults to None.
- evaluate(args)
A wrapper around
dexipy.dexi.DexiFunction.value()
that returns None whenvalue()
raises an error.- Parameters:
args (Any) – Expected is a single float number or a list of integer arguments passed to the function.
- Returns:
Function value for the given args, or None when the value cannot be determined for the given args.
- Return type:
DexiValue
- funct_str()
Creates a short string for displaying information about the function in printouts.
- Returns:
A short string, whose contents depends on this function’s type.
- Return type:
str
- nargs()
Returns the number of function arguments.
- Returns:
The number of this function’s arguments.
- Return type:
int
- nvals()
Returns this function size.
- Returns:
The number of this function’s decision rules. Returns 0 for function types that do not have rules.
- Return type:
int
- value(args)
Returns the function value for given arguments.
- Parameters:
args (Any) – Expected is a single float number or a list of integer arguments passed to the function.
- Raises:
ValueError – When function value cannot be determined for the given args.
- Returns:
Function value for the given args.
- Return type:
DexiValue
- class dexipy.dexi.DexiModel(name='', description='', root=None, linking=False)
Bases:
object
DexiModel is the class that represents a DEXi model.
In DEXiPy, DexiModel objects are normally created by reading from a .dxi file, previously developed by external DEXi/DEXiWin software. Reading models from files ensures that they are properly “wired” into a consistent structure of attributes, scales and functions. In principle, all fields of a DexiModel should be thus considered read-only. DEXiPy does not provide any explicit functionality for creating and changing DEXi models. Models can still be created and modified in Python, but without any integrity or consistency guarantees.
- Parameters:
name (str, optional) – Model name. Defaults to “”.
description (str, optional) – An optional textual description of the model. Defaults to “”.
root (Optional[DexiAttribute], optional) – The virtual root of all subtrees/hierarchies of attributes in the model. Defaults to None.
linking (bool, optional) – Indicates whether or not the model uses linked attributes, which are used in DEXi to represent hierarchies of attributes (i.e., directed acyclic graphs) rather than trees. Defaults to False.
- attributes
List of all model attributes, using the depth-first order.
- Type:
list[DexiAttribute]
- natt
Length of self.attributes.
- Type:
int
- att_names
List of attribute names in the model, in the order of self.attributes.
- Type:
list[str]
- att_ids
List of attribute IDs in the model, in the order of self.attributes.
- Type:
list[str]
- basic
List of all basic attributes.
- Type:
list[DexiAttribute]
- aggregate
List of all aggregate attributes.
- Type:
list[DexiAttribute]
- links
List of all linked attributes.
- Type:
list[DexiAttribute]
- non_root
List of all self.attributes without self.root.
- Type:
list[DexiAttribute]
- basic_names
List of all basic attributes’s names.
- Type:
list[str]
- aggregate_names
List of all aggregate attributes’ names.
- Type:
list[str]
- links_names
List of all linked attributes’ names.
- Type:
list[str]
- non_root_names
List of all self.non_root attributes’ names.
- Type:
list[str]
- basic_ids
List of all basic attributes’s IDs.
- Type:
list[str]
- aggregate_ids
List of all aggregate attributes’ IDs.
- Type:
list[str]
- links_ids
List of all linked attributes’ IDs.
- Type:
list[str]
- non_root_ids
List of all self.non_root attributes’ IDs.
- Type:
list[str]
- alternatives
A list of DEXi decision alternatives defined as part of the model.
- Type:
DexiAlternatives
- alt_table(alternatives=None, alt_head='alternative', sel_att=[], basic=False, aggregate=False, structure=False, decimals=None, transpose=False, use_dict=True, text=False, none='')
Creates a string that, when printed out, displays alternatives in a tabular form.
- Parameters:
alternatives (Optional[DexiAltData], optional) – A single alterative or a list of alternatives. Defaults to None, which selects self.alternatives.
alt_head (str, optional) – Text to be displayed in the topmost-left cell. Defaults to “alternative”.
sel_att (list[str], optional) – A list of attribute IDs to be displayed. Defaults to [], which selects all non-root attributes, unless overriden by basic and aggregate arguments.
basic (bool, optional) – Selects all basic attributes for display. Considered only when
sel_att == []
. Defaults to False.aggregate (bool, optional) – Selects all aggregate attributes for display. Considered only when
sel_att == []
. Defaults to False.structure (bool, optional) – Whether attribute structure is displayed together with attribute names. Considered only when transpose is True. Defaults to False.
decimals (Optional[int], optional) – The number of decimal places used to display floating-point numbers. Defaults to None.
transpose (bool, optional) – Normally, the table displays attributes in rows and alternatives in columns. Setting this argument to True transposes the table. Defaults to False.
use_dict (bool, optional) – Whether or not the dictionary-form is used for displaying value distributions (rather than list-form). Defaults to True.
text (bool, optional) – Whether of not value cells are textualized using
dexipy.dexi.DexiModel.textualize_alternatives()
. Defaults to False.none (str, optional) – The string used to display None values. Defaults to “”.
- Returns:
A multi-line string representation of alternatives.
- Return type:
str
- alt_text(alternatives=None, **kwargs)
Creates a string that, when printed out, displays alternatives in a tabular and textualized form. It is meant as a convenient abbreviation for calling
self.alt_table(alternatives, text = True, **kwargs)
.- Parameters:
alternatives (Optional[DexiAltData], optional) – A single alterative or a list of alternatives. Defaults to None, which selects self.alternatives.
**kwargs – Other arguments passed to
dexipy.dexi.DexiModel.alt_table()
.
- Returns:
A multi-line string representation of alternatives.
- Return type:
str
- alternative(name=None, description=None, alt=None, sel_att=[], basic=False, aggregate=False, default=None, deindex=False, values=None, **kwargs)
Defines a new decision alternative.
- Parameters:
name (Optional[str], optional) – Name of the alternative. Defaults to None.
description (Optional[str], optional) – Textual description of the alternative. Defaults to None.
alt (Optional[DexiAlternative], optional) – A base alternative. If specified, all the values of alt are copied to the resulting alternative prior to adding or overwriting them with values specified in other arguments. Defaults to None.
sel_att (list[str], optional) – The list of attributes whose values are added to the resulting alternative and initialized to the None value. Defaults to [].
basic (bool, optional) – If True, add all basic attributes. Considered only when
sel_att == []
. Defaults to False.aggregate (bool, optional) – If True, add all aggregate attributes. Considered only when
sel_att == []
. Defaults to False.default (DexiValue, optional) – Default attribute value that is assigned unless it has been specified in other arguments. Defaults to None.
deindex (bool, optional) – Whether or not the resulting alternative data is deindexed after setup, using
dexipy.dexi.deindex_alternative()
. Defaults to False.values (Optional[DexiAlternative], optional) – A dictionary of
attribute_id: attribute_value
orattribute_index: attribute_value
elements, added to the resulting dictionary in addition to or overwriting values set by other arguments. Defaults to None.**kwargs – Keyword method arguments in the form
attribute_id = attribute_value
. This form is possible only with attributes whose IDs match the Python’s syntax for variable names.
- Returns:
Alternative data represented as a dictionary consisting of
attribute_id: attribute_value
orattribute_index: attribute_value
elements.- Return type:
DexiAlternative
- att_and_scale(find)
Find an attribute and also return its scale.
- Parameters:
find (Optional[DexiAttribute | str | int]) – An attribute object, ID or index.
- Returns:
A tuple consisting of DexiAttribute and DexiScale objects. If attribute has not been found, (None, None) is returned.
- Return type:
tuple[Optional[DexiAttribute], Optional[DexiScale]]
- att_index(attname, use_id=True)
Given an ID or name of an attribute, find its index in self.attributes.
- Parameters:
attname (str) – Attribute ID or name.
use_id (bool, optional) – Whether to search by attribute ID (True) or name (False). Defaults to True.
- Returns:
Attribute index or None if not found. When searching by name, attribute names may not be unique and only the first index is returned in this case.
- Return type:
Optional[int]
- att_indices(attname)
Returns the index of attribute named attname in self.attributes.
- Parameters:
attname (str) – Attribute name.
- Returns:
A list of attributes. May contain multiple attributes when attribute names are not unique.
- Return type:
list[int]
- att_stat()
Counts attributes of different types in the model.
- Returns:
A dictionary of the form
{"all": int, "basic": int, "aggregate": int, "link": int}
, containing counts of the corresponding attribute types.- Return type:
dict[str, int]
- attrib(find)
A general method for finding an attribute in the model.
- Parameters:
find (Optional[DexiAttribute | str | int]) – An attribute object, ID or index.
- Returns:
DexiAttribute object if found in the model, or None otherwise.
- Return type:
Optional[DexiAttribute]
- attribute_list(select, exclude=[])
Wrapper around
find_attributes()
that returns a clean list of attributes.- Parameters:
select (Iterable[Optional[DexiAttribute | str | int]]) – A list of DEXiAttributes, attribute IDs or attribute indices.
exclude (list[list[DexiAttribute | str]], optional) – Exclude attributes elements from result.
- Returns:
A clean list of DexiAttributes w.r.t. the correspoding select and exclude criteria, without any None elements.
- Return type:
list[DexiAttribute]
- check_alternative(alt, aggregate=False)
Checks the data representing alternative alt, and reports found errors and warnings.
- Parameters:
alt (DexiAlternative) – A DEXi alternative.
aggregate (bool, optional) – Whether values of aggregate attributes are checked or not. The rationale for this argument is that
evaluate()
, which typically follows checking, overwrites values of aggregate attributes. Defaults to False.
- Returns:
A dictionary of the form
{"errors": <list of error strings>, "warnings": <list of warning strings>}
.- Return type:
dict[str, list[str]]
- check_alternatives(alternatives=None, aggregate=False)
A vectorized version of
dexipy.dexi.check_alternative()
. May check a single alternative or a list of alternatives.- Parameters:
alternatives (Optional[DexiAltData], optional) – A single alterative or a list of alternatives. Defaults to None, which selects self.alternatives.
aggregate (bool, optional) – Whether values of aggregate attributes are checked or not. Defaults to False.
- Raises:
ValueError – When alternatives is not of a DexiAltData type.
- Returns:
A dictionary of the form
{"errors": <list of error strings>, "warnings": <list of warning strings>}
.- Return type:
dict[str, list[str]]
- collect_attributes(att)
Returns a list of attributes, obtained by a recursive depth-first travesal of the subtree rooted at att.
- Parameters:
att (DexiAttribute) – The root attribute of traversal.
- Returns:
List of attributes found in the subtree rooted at att, including att.
- Return type:
list[DexiAttribute]
- compare_alternatives(alt, alternatives=None, root=None, prune=[], compare=True, deep=True, text=True, structure=True)
Compare Alternatives
Compare alt with each of alternatives. Display only values that differ and, optionally when compare = True, include preference-relational operators.
- Parameters:
alt (DexiAlternative) – A single DexiAlternative to be compared with alternatives.
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Alternatives are assumed to be previously fully evaluated. Defaults to None, which selects all self.alternatives.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute for displaying results. Defaults to None, which selects self.root.
prune (list[str], optional) – List of attribute IDs at which the display is “pruned”, skipping their subordinate attributes. Defaults to [].
compare (bool, optional) – Whether or not to display preference comparison operators “=”, “<”, “>”, “<=”, “>=”. Defaults to True.
deep (bool, optional) – Whether or not “deep” comparison (see
dexipy.eval.compare_two_alternatives()
) is carried out. Defaults to True.text (bool, optional) – Whether to display results textually (True) or using internal value representation (False). Defaults to True.
structure (bool, optional) – Whether to display only attribute IDs in the first column (False) or to extend them with tree-structure information. Defaults to True.
- Raises:
ValueError – When alt or alternatives are None, when alt is not a single alternative, and when root is undefined.
- Returns:
None and prints out the resulting alternative comparison table.
- Return type:
None
- deindex_alternative(alt)
Converts a DexiAlternative dictionary replacing all attribute indices with the corresponding attribute IDs.
- Args:
- alt (DexiAlternative):
An alternative, represented by a dictionary.
- Returns:
- DexiAlternative:
A dictionary with all numeric indices replaced with string IDs.
- Parameters:
alt (DexiAlternative)
- Return type:
DexiAlternative
- evaluate(alternatives=None, method='set', root=None, prune=[], pre_check=False, bounding=False, in_place=False, eval_param=None)
Evaluates decision alternative(s).
See Evaluation of alternatives for more information about the evaluation process and evaluation methods used in DEXiPy.
- Parameters:
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Defaults to None, which selects self.alternatives.
method (str, optional) – One of the strings “set”, “prob”, “fuzzy”, “fuzzynorm” that select the evaluation method. Defaults to “set”.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute of the evaluation. Defaults to None, which selects self.root.
prune (list[str], optional) – List of attribute IDs at which the evaluation is “pruned”. This means that input attributes below some pruned attribute are not evaluated and the pruned attribute is treated as an input (basic) attribute for this evaluation. Defaults to [].
pre_check (bool, optional) – Whether of not alternatives are checked by
dexipy.dexi.DexiModel.check_alternatives()
prior to evaluation. Defaults to False.bounding (bool, optional) – Whether or not the evaluation keeps calculated values within bounds prescribed by the corresponding scales. Defaults to False.
in_place (bool, optional) – If True, evaluation modifies alternatives in place, otherwise a copy is made and returned by the method. Defaults to False.
eval_param (Optional[DexiEvalParameters], optional) – Optional DexiEvalParameters that may customize the normalization and aggregation methods used in the evaluation. Defaults to None.
- Returns:
Returns an evaluated alternative or list of alternatives, depending on the type of the alternatives argument.
- Return type:
DexiAltData
- find_attributes(select, exclude=[])
A vectorized version of
dexipy.dexi.DexiModel.attrib()
. Returns a list of attributes found in the model according to the select specification.- Parameters:
select (Iterable[Optional[DexiAttribute | str | int]]) – A list of DEXiAttributes, attribute IDs or attribute indices.
exclude (list[list[DexiAttribute | str]], optional) – Exclude attributes elements from result.
- Returns:
A list of DexiAttributes w.r.t. the correspoding select and exclude criteria. May contain None elements for not-found attributes.
- Return type:
Optional[list[DexiAttribute] | list[Optional[DexiAttribute]]]
- first()
Return first non-virtual model attribute, i.e., first descendant of model.root.
- Return type:
DexiAttribute | None
- link_attributes()
Carries out the linking of attributes.
DEXi attributes that have the same names and value scales, and satisfy some other constraints to prevent making cycles in the model, are linked together so that they logically represent a single attribute. In this way, a tree of attributes is conceptually turned in a hierarchy (directed acyclic graph).
- Return type:
None
- make_ids(max_len=None, var_names=False)
A helper method for creating attribute IDs from attribute names. Generated IDs are assigned to self.att_ids and propagated through the model.
- Parameters:
max_len (Optional[int], optional) – Maximum length of IDs (excluding “_<idx>” strings added to ensure the uniqueness of IDs). Defaults to None, which leaves the attribute name length intact.
var_names (bool, optional) – Whether or not IDs should be generated so that they conform with Python’s syntax for variable names. This allows using attribute IDs as function arguments, for example with
dexipy.dexi.DexiModel.alternative()
. Defaults to False.
- Return type:
None
- parent_attributes(att)
Traverses the subtree of attributes rooted at att and sets the parent field of each attribute.
- Parameters:
att (DexiAttribute) – The root attribute of traversal.
- Return type:
None
- plus_minus(alt, target=None, minus=9223372036854775807, plus=9223372036854775807, text=True, structure=True)
Plus Minus Analysis
Investigate the effects of changing single attributes’ values on the evaluation of alt. The values of discrete basic attributes (“input attributes”) are changed, one attribute at a time, by a particular number of steps downwards (minus) and upwards (plus), while observing the changes of the target attribute values.
- Parameters:
alt (DexiAlternative) – A single DexiAlternative. Assumed to be previously evaluated using
evaluate()
.target (DexiAttribute, optional) – A DexiAttribute on which effects are observed. Defaults to None, which selects self.root.
minus (int, optional) – The maximum number of downward steps to be made for each input attribute. Defaults to sys.maxsize. The actual minus value is further determined with respect to alternative values and involved attributes’ scales.
plus (int, optional) – The maximum number of upward steps to be made for each input attribute. Defaults to sys.maxsize. The actual plus value is further determined with respect to alternative values and involved attributes’ scales.
text (bool, optional) – Whether to display results textually (True) or using internal value representation (False). Defaults to True.
structure (bool, optional) – Whether to display only attribute IDs in the first column (False) or to extend them with tree-structure information. Defaults to True.
- Raises:
ValueError – When target is None or does not have a scale defined.
ValueError – When alt is not a single DexiAlternative.
- Returns:
A data table containing the following columns of strings:
First column: Attribute IDs, optionally extended with structure information.
For -minus to -1: Columns containing evaluation values of target when decreasing attribute values by the corresponding number of steps.
Middle column: Original alternative values assigned to the corresponding attributes.
For +1 to +plus: Columns containing evaluation values of target when increasing attribute values by the corresponding number of steps.
- Return type:
Optional[list[list[str]]]
- Limitations:
Only basic attributes with defined discrete scales participate in the analysis.
- propagate_ids()
Propagates self.att_ids to other self.*_ids lists and to IDs of individual attributes in the model. Should be explicitly called after a modification of self.att_ids.
- Return type:
None
- selective_explanation(alternatives=None, root=None, prune=[], text=True, structure=True)
Selective Explanation
Displays subtrees of alternatives’ values in which values are particularly weak (DexiQuality.BAD) and particularly strong (DexiQuality.GOOD).
- Parameters:
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Alternatives are assumed to be previously fully evaluated. Defaults to None, which selects all self.alternatives.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute for displaying results. Defaults to None, which selects self.root.
prune (list[str], optional) – List of attribute IDs at which the display is “pruned”, skipping their subordinate attributes. Defaults to [].
text (bool, optional) – Whether to display results textually (True) or using internal value representation (False). Defaults to True.
structure (bool, optional) – Whether to display only attribute IDs in the first column (False) or to extend them with tree-structure information. Defaults to True.
- Raises:
ValueError – When model, root or alternatives are undefined.
- Return type:
None
- setup()
A helper method called as the last step when creating a DexiModel.
This method assigns self.root, sets attributes’ parents, generates attribute IDs and creates all model-level attribute lists. If self.linking is True, it also traverses the model and links attributes.
When manually changing elements of a DexiModel, calling this method might (but need not) reestablish a consistent model structure.
- Raises:
ValueError – When self.root is undefined or not of the DexiAttribute class.
- Return type:
None
- textualize_alternative(alt, decimals=None, use_dict=True)
Converts an internal representation of alternative alt, which typically uses numerical attribute and value indices, to a more comprehensible dictionary that uses string attribute IDs and value names.
- Parameters:
alt (DexiAlternative) – An alternative, represented by a dictionary.
decimals (Optional[int], optional) – The number of decimal places used to display floating-point numbers. Defaults to None.
use_dict (bool, optional) – Whether or not the dictionary-form is used for displaying value distributions (rather than list-form). Defaults to True.
- Returns:
alt converted to an equivalent dictionary that uses strings instead of numbers.
- Return type:
DexiAlternative
- textualize_alternatives(alts, decimals=None, use_dict=True)
A vectorized version of
dexipy.dexi.textualize_alternative()
. May textualize a single alternative or a list of alternatives.- Parameters:
alts (DexiAltData) – A single alterative or a list of alternatives. Defaults to None, which selects self.alternatives.
decimals (Optional[int], optional) – The number of decimal places used to display floating-point numbers. Defaults to None.
use_dict (bool, optional) – Whether or not the dictionary-form is used for displaying value distributions (rather than list-form). Defaults to True.
- Returns:
alts converted to an equivalent representation that uses strings instead of numbers.
- Return type:
DexiAltData
- class dexipy.dexi.DexiScale(order=DexiOrder.ASCENDING)
Bases:
object
DexiScale is a base class for representing DEXi value scales.
A value scale defines the type and set of values that can be assigned to some
dexipy.dexi.DexiAttribute
.dexipy.dexi.DexiScale
defines attributes and methods common to all scales. Normally, this class should not be created itself, but only through derived scale classes,dexipy.dexi.DexiContinuousScale
anddexipy.dexi.DexiDiscreteScale
.- Parameters:
order (DexiOrder) – Preferential order of the scale. Defaults to DexiOrder.ASCENDING.
- count()
Returns the number of discrete values of this scale.
- Returns:
The number of values or 0 for non-discrete scales.
- Return type:
int
- equal(scl)
Checks whether or not this scale is equal to another scale scl.
- Parameters:
scl (Optional[DexiScale]) – Expected a
dexipy.dexi.DexiScale
object.- Returns:
Is this scale equal to scl?
- Return type:
bool
- classmethod equal_scales(scl1, scl2)
Checks whether of not two scales are equal.
- Parameters:
scl1 (Any) – First scale.
scl2 (Any) – Second scale.
- Returns:
Returns True if both scales are None or both are not None and
scl1.equals(scl2)
. Returns False for non-scale arguments.- Return type:
bool
- full_range()
Returns the full range of admissible values for this scale.
- Returns:
A set of all values or None for non-discrete scales.
- Return type:
Optional[set[int]]
- has_bad(value)
Determines whether or not value, interpreted as a set on this scale, contains at least one element of DexiQuality.BAD
- Parameters:
value (DexiValue)
- Return type:
bool
- has_good(value)
Determines whether or not value, interpreted as a set on this scale, contains at least one element of DexiQuality.GOOD
- Parameters:
value (DexiValue)
- Return type:
bool
- has_none(value)
Determines whether or not value, interpreted as a set on this scale, contains at least one element of DexiQuality.NONE
- Parameters:
value (DexiValue)
- Return type:
bool
- has_quality(value, quality)
Determines whether or not value, interpreted as a set on this scale, contains at least one element of given quality
- Parameters:
value (DexiValue)
quality (DexiQuality)
- Return type:
bool
- is_continuous()
Returns True is this scale is continuous.
- Returns:
Is this scale continous?
- Return type:
bool
- is_discrete()
Returns True is this scale is discrete.
- Returns:
Is this scale discrete?
- Return type:
bool
- scale_str()
Returns a short string representing the scale to be used in DEXi model printouts.
- Returns:
A short string representation of this scale.
- Return type:
str
- value_index(value)
Returns the index of value in the scale.
- Returns:
Integer index or None for non-discrete scales.
- Return type:
Optional[int]
- Parameters:
value (Any)
- value_qualities(value)
Returns a list of DexiQuality items for value interpreted as a set on this scale.
- Parameters:
value (DexiValue)
- Return type:
Sequence[DexiQuality | None] | None
- value_quality(value)
Returns the quality (value class) of value.
- Parameters:
value (Any) – Some scale value, usually a number or string.
- Returns:
Value quality.
- Return type:
Optional[DexiQuality]
- class dexipy.dexi.DexiTabularFunction(attribute=None, dim=None, values=None, low=None, high=None)
Bases:
DexiFunction
DexiTabularFunction represents the most common function type used in DEXi models. Functions of this type aggregate discrete attribute values according to decision rules, defined in terms of a decision table.
A decision table contains as many decision rules as there are possible combinations of input attributes’ values. For instance, if some attribute has two inputs whose discrete scales have three and four values, respectively, then the number of rules is equal to \(3 * 4 = 12\). Each rule defines the value of the attribute for one of the possible combinations of values of the attribute’s inputs. For example, a decision rule
(0, 1): 2
maps the zeroth and first value of the first and second input attribute to value 2 of the output attribute. A decision table is represented as a dictionary of such rules. Thus, it can be interpreted as a lookup table that, given a vector of values of attribute.inputs, (i.e., function arguments) returns the corresponding output attribute value. In general, the output value can be any DEXi value.Notes
In order to properly define the context in which the newly created function operates, at least one of the arguments, attribute or dim, must be given.
Decision rules must be defined either directly by the values argument, or indirectly using the low and high strings.
- Parameters:
attribute (Optional[DexiAttribute], optional) – A
dexipy.dexi.DexiAttribute
to which this function is assigned. Both the attribute and its inputs are required to be discrete (i.e., associated withdexipy.dexi.DexiDiscreteScale
. Defaults to None.dim (Any, optional) – A list of integers, representing the size of the corresponding input attribute dimensions. Defaults to None.
values (Optional[list[DexiValue]], optional) – A decision table. Represented in the form of a dictionary that maps function arguments (represented as integer tuples) to function values (represented as DEXi values). Defaults to None.
low (Optional[str], optional) – A DEXi string representing lower bounds of function values in .dxi files. Defaults to None.
high (Optional[str], optional) – A DEXi string representing upper bounds of function values in .dxi files. When None, it is assumed that
low == high
. Defaults to None.
- Raises:
ValueError –
When at least one of the arguments attribute or dim is not given. * When dim is not a list of integers, has length different from attribute.count() or contains dimensions incompatible with input attributes. * When low and/or high are of length different than the expected number of decision rules.
- funct_str()
Creates a short string for displaying information about the function in printouts.
- Returns:
A short string, whose contents depends on this function’s type.
- Return type:
str
- nargs()
Returns the number of function arguments.
- Returns:
The number of this function’s arguments.
- Return type:
int
- nvals()
Returns the function space size (the total number of input attributes’ value combinations).
- Returns:
Size of the space defined by this function’s input attributes.
- Return type:
int
- value(args)
Returns the function value for given arguments.
- Parameters:
args (Iterable[int]) – A vector of integer arguments passed to the function.
- Raises:
ValueError – When function value cannot be determined for the given args.
- Returns:
Function value for the given args.
- Return type:
DexiValue
- value_vector()
Returns the vector of this function’s values.
- Returns:
A list of DEXi values, extracted from self.values, in the order determined using
dexipy.utils.cartesian_product()
.- Return type:
list[DexiValue]
- dexipy.dexi.alt_lines(alternatives, alt_head='alternative', sel_att=[], transpose=False, none='')
Makes a list of strings that represent alternative in a tabular form.
- Parameters:
alternatives (DexiAltData) – A DEXi alternative or a list of DEXi alternatives.
alt_head (str, optional) – Text to be included as the top-left element of the table. Defaults to “alternative”.
sel_att (list[str], optional) – A list of selected attribute IDs. Any remaining IDs in alternatives are ignored. Defaults to [], which selects all attributes.
transpose (bool, optional) – Normally, table columns correspond to alternatives. Setting transpose to True makes columns corresponding to attributes. Defaults to False.
none (str, optional) – A string to display None values. Defaults to “”.
- Returns:
A list of lines that can be joined together and printed.
- Return type:
list[str]
- dexipy.dexi.alt_name(alt, default='', name='name')
Extracts alternative name from DexiAlternative data.
- Parameters:
alt (DexiAlternative) – A DEXi alternative.
default (str, optional) – Name returned when no name has been found. Defaults to “”.
name (str, optional) – Key string for finding alternative name. Defaults to “name”.
- Returns:
Name of the alternative, or default if not found.
- Return type:
str
- dexipy.dexi.alternative(name=None, description=None, alt=None, values=None, **kwargs)
Defines a new decision alternative.
- Parameters:
name (Optional[str], optional) – Name of the alternative. Defaults to None.
description (Optional[str], optional) – Textual description of the alternative. Defaults to None.
alt (Optional[DexiAlternative], optional) – A base alternative. If specified, all the values of alt are copied to the resulting alternative prior to adding or overwriting them with values. Defaults to None.
values (Optional[DexiAlternative], optional) – A dictionary of
attribute_id: attribute_value
orattribute_index: attribute_value
elements, added to the resulting dictionary. Defaults to None.**kwargs – Keyword function arguments in the form
attribute_id = attribute_value
. This form is possible only with attributes whose IDs match Python’s syntax for variable names.
- Raises:
ValueError – When alt is not a dictionary.
- Returns:
Alternative data represented as a dictionary consisting of
attribute_id: attribute_value
orattribute_index: attribute_value
elements.- Return type:
DexiAlternative
- dexipy.dexi.att_names(atts, use_id=True)
Given a sequence of attributes, returns the list of names or IDs of that attribute.
- Parameters:
atts (Iterable[DexiAttribute]) – A sequence of attributes.
use_id (bool, optional) – Whether to use attribute IDs (True) or names (False). Defaults to True.
- Returns:
A list of attributes’ IDs or names.
- Return type:
list[str]
- dexipy.dexi.bounded_scale_value(value, scale)
A wrapper around
dexipy.dexi.scale_value()
that ensures that the resulting value lies within the bounds set up by scale.- Parameters:
value (DexiValue) – A Dexi value specificatuion.
scale (Any) – Expected a
dexipy.dexi.DexiScale
ordexipy.dexi.DexiAttribute
object.
- Raises:
ValueError – When value cannot be interpreted or bound to scale limits.
- Returns:
An interpreted value (see
dexipy.dexi.scale_value()
) and reduced to scale bounds.- Return type:
DexiValue
- dexipy.dexi.columnize(alternatives, alt_head='alternative', sel_att=[], att_text=None, transpose=False, none='')
A helper function that “columnizes” DexiAltData. A suitable list of columns is produced for further processing.
- Parameters:
alternatives (DexiAltData) – A DEXi alternative or a list of DEXi alternatives.
alt_head (str, optional) – Text to be included as the first element of the first column. Defaults to “alternative”.
sel_att (list[str], optional) – A list of selected attribute IDs. Any remaining IDs in alternatives are ignored. Defaults to [].
att_text (list[str], optional) – A text to be displayed for each corresponding item in sel_att. Considered only if not None, sel_att is defined, lengths of sel_att and att_text are equal and transpose is False. Defaults to None.
transpose (bool, optional) – Normally, columns correspond to alternatives. Setting transpose to True makes columns corresponding to attributes. Defaults to False.
none (str, optional) – A string to display None values. Defaults to “”.
- Returns:
List of columns. Each column is a list of strings. All columns are padded to the same length.
- Return type:
list[list[str]]
- dexipy.dexi.compare_values_on_scale(value1, value2, scale, force=False)
Compare DEXi values value1 and value2 considering scale.order.
- Parameters:
value1 (DexiValue) – First value.
value2 (DexiValue) – Second value.
scale (Optional[DexiScale]) – A DexiScale or derived object.
force (bool, optional) – Considered when scale or scale.order are None. When force is True, comparison is enforced, assuming ascending preference order. When False, None is returned in such cases. Defaults to False.
- Returns:
Returns result of
dexipy.values.compare_values_by_preference()
, considering scale.order.- Return type:
Optional[int]
- dexipy.dexi.dexi_value_has_bad(value, scale)
Determines whether value, interpreted on scale, has at least one element of DexiQuality.BAD.
- Parameters:
value (DexiValue) – A DexiValue.
scale (Optional[DexiScale]) – A DexiScale or derived object.
- Returns:
Whether or not value contains an item of given DexiQuality.BAD.
- Return type:
bool
- dexipy.dexi.dexi_value_has_good(value, scale)
Determines whether value, interpreted on scale, has at least one element of DexiQuality.GOOD.
- Parameters:
value (DexiValue) – A DexiValue.
scale (Optional[DexiScale]) – A DexiScale or derived object.
- Returns:
Whether or not value contains an item of given DexiQuality.GOOD.
- Return type:
bool
- dexipy.dexi.dexi_value_has_none(value, scale)
Determines whether value, interpreted on scale, has at least one element of DexiQuality.NONE.
- Parameters:
value (DexiValue) – A DexiValue.
scale (Optional[DexiScale]) – A DexiScale or derived object.
- Returns:
Whether or not value contains an item of given DexiQuality.NONE.
- Return type:
bool
- dexipy.dexi.dexi_value_has_quality(value, scale, quality)
Determines whether value, interpreted on scale, has at least one element of given quality.
- Parameters:
value (DexiValue) – A DexiValue.
scale (Optional[DexiScale]) – A DexiScale or derived object.
quality (DexiQuality) – Required DexiQuality.
- Returns:
Whether or not value contains an item of given quality.
- Return type:
bool
- dexipy.dexi.dexi_value_qualities(value, scale)
Returns a list of DexiQuality items for value interpreted as a set.
- Parameters:
value (DexiValue) – A DexiValue.
scale (Optional[DexiScale]) – A DexiScale or derived object.
- Returns:
A list of DexiQuality items corresponding to value items, where value is interpreted as a value set on scale.
- Return type:
Optional[Sequence[Optional[DexiQuality]]]
- dexipy.dexi.evaluate(model, alternatives=None, method='set', root=None, prune=[], pre_check=False, bounding=False, in_place=False, eval_param=None)
Evaluates decision alternative(s).
Please see Evaluation of alternatives for more information about the evaluation process and evaluation methods used in DEXiPy.
- Parameters:
model (DexiModel) – A DexiModel. Required.
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Defaults to None, which selects model.alternatives.
method (str, optional) – One of the strings “set”, “prob”, “fuzzy”, “fuzzynorm” that select the evaluation method. Defaults to “set”.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute of the evaluation. Defaults to None, which selects model.root.
prune (list[str], optional) – List of attribute IDs at which the evaluation is “pruned”. This means that input attributes below some pruned attribute are not evaluated and the pruned attribute is treated as an input (basic) attribute for this evaluation. Defaults to [].
pre_check (bool, optional) – Whether or not alternatives are checked by
dexipy.dexi.DexiModel.check_alternatives()
prior to evaluation. Defaults to False.bounding (bool, optional) – Whether or not the evaluation keeps calculated values within bounds prescribed by the corresponding scales. Defaults to False.
in_place (bool, optional) – If True, evaluation modifies alternatives in place, otherwise a copy is made and returned by the method. Defaults to False.
eval_param (Optional[DexiEvalParameters], optional) – Optional DexiEvalParameters, that may customize the normalization and aggregation methods used in the evaluation. Defaults to None.
- Returns:
Returns an evaluated alternative or list of alternatives, depending on the type of the alternatives argument.
- Return type:
DexiAltData
- dexipy.dexi.read_dexi(filename)
Reads a DEXi model from a .dxi file.
- Parameters:
filename (str) – File name.
- Returns:
DEXi model read from the file.
- Return type:
- dexipy.dexi.read_dexi_from_string(xml)
Reads a DEXi model from a xml string.
- Parameters:
xml (str) – XML string representation of a DEXi model, conforming to the format used in .dxi files.
- Returns:
DEXi model read from the string.
- Return type:
- dexipy.dexi.scale_of(obj)
Returns a DEXi scale related to obj.
- Parameters:
obj (Any) – Expected are
dexipy.dexi.DexiScale
ordexipy.dexi.DexiAttribute
objects.- Returns:
Returns obj if obj is a
dexipy.dexi.DexiScale
object. Returns obj.scale if obj isdexipy.dexi.DexiAttribute
. Returns None for other object types.- Return type:
Optional[DexiScale]
- dexipy.dexi.scale_value(value, scale)
Checks and interprets value on scale.
- Parameters:
value (DexiValue) – Normally, a DEXi value is expected.
scale (Any) – A
dexipy.dexi.DexiScale
object.
- Raises:
ValueError – When scale is undefined, when value does not contain a valid DexiValue or value cannot be interpreted on scale.
- Returns:
An interpreted value. The interpretation includes:
replacing the value
"*"
by the actualdexipy.dexi.DexiScale.full_range()
of the scale,interpreting
""
and"undef..."
as None,float values are admissible only with continuous scales, otherwise they are interpreted as None,
all value-name strings that occur in value sets, lists and dictionaries, are replaced by the corresponding numeric indices.
- Return type:
DexiValue
- dexipy.dexi.subtree_attributes(att, prune=[], links=True)
Determine the depth-first order of attributes, starting at att and pruning at prune.
- Parameters:
att (DexiAttribute) – The starting point of making the subtree.
prune (list[str], optional) – A list of attribute IDs at which to prune the search. Defaults to [].
links (bool, optional) – Whether to include linked attributes. Defaults to True.
- Returns:
A list of DexiAttribute objects.
- Return type:
list[DexiAttribute]
- dexipy.dexi.subtree_order(att, prune=[], links=True)
Determine the depth-first order of attributes, starting at att and pruning at prune.
- Parameters:
att (DexiAttribute) – The starting point of making the subtree.
prune (list[str], optional) – A list of attribute IDs at which to prune the search. Defaults to [].
links (bool, optional) – Whether to include linked attributes. Defaults to True.
- Returns:
A list of attribute IDs.
- Return type:
list[str]
- dexipy.dexi.value_text(value, scale, none='None', reduce=False, decimals=None, use_dict=True)
Represents value by a human-readable string that can be printed.
- Parameters:
value (DexiValue | str) – Normally a DexiValue. May also be string, which is returned as-is.
scale (Any) – Expected a
dexipy.dexi.DexiScale
ordexipy.dexi.DexiAttribute
object.none (Optional[str], optional) – An optional string that is returned when the value cannot be interpreted. Defaults to None.
reduce (bool, optional) – Whether or not the value is reduced (see
dexipy.values.reduce_dexi_value()
) prior to processing. Defaults to False.decimals (Optional[int], optional) – The number of decimals used to display float numbers. Defaults to None.
use_dict (bool, optional) – Whether or not the dictionary-form is used for displaying value distributions (rather than list-form). Defaults to True.
- Returns:
A string representation of value.
- Return type:
Optional[str]
dexipy.eval module
The module dexipy.eval implements classess and functions for the evaluation of decision alternatives.
- class dexipy.eval.DexiEvalMethods
Bases:
object
A class defining default
dexipy.eval.DexiEvalParameters
for the evaluation methods implemented in DEXiPy.The default parameters are set as follows:
import dexipy.utils as utl self.set_method(DexiEvalParameters("set", lambda x: 0, lambda x: 1, utl.norm_none)) self.set_method(DexiEvalParameters("prob", utl.prod, sum, utl.norm_sum)) self.set_method(DexiEvalParameters("fuzzy", min, max, utl.norm_none)) self.set_method(DexiEvalParameters("fuzzynorm", min, max, utl.norm_max))
- classmethod get_method(method)
Gets default evaluation parameters for method.
- Parameters:
method (str) – Method name.
- Raises:
ValueError – When method parameters have not been previously defined for the given method name.
- Returns:
Default parameters of the given method.
- Return type:
- classmethod set_method(method)
Sets default evaluation parameters for method.
- Parameters:
method (DexiEvalParameters) – Evaluation parameters with defined method name method.method.
- Return type:
None
- class dexipy.eval.DexiEvalParameters(method, and_op, or_op, norm)
Bases:
object
A class defining evaluation parameters.
Please see Evaluation of alternatives for more information about the evaluation process and evaluation methods used in DEXiPy.
- Parameters:
method (str) – Method name. One of the strings “set”, “prob”, “fuzzy”, “fuzzynorm”.
and_op (CallableOperator) – Conjunctive aggregation function.
or_op (CallableOperator) – Disjunctive aggregation function.
norm (CallableNorm) – Normalization function.
- dexipy.eval.EvalMethods = <dexipy.eval.DexiEvalMethods object>
A
dexipy.eval.DexiEvalMethods
object containing default evaluation parameters for all methods implemented in DEXiPy.
- dexipy.eval.aggregate_alternatives(model, alternatives=None, attributes=None, name='name', aggregate='mean', interpret='distribution')
Aggregate alternatives so as to contain only numeric data (or None). Value sets and distributions are converted by
dexipy.values.aggregate_value()
.- Parameters:
model (DexiModel) – A DexiModel object.
alternatives (Optional[DexiAltData], optional) – One or more DEXi alternatives. Defaults to None, which selects model.alternatives.
attributes (Optional[Iterable[Optional[DexiAttribute | str | int]]], optional) – A sequence of DexiAttributes, attribute IDs or indices. Defaults to None, which selects model.attributes.
name (str) – Name of DexiAlternative element that contains alternatives’ name. Defaults to “name”.
aggregate (str, optional) – One of “min”, “max” or “mean”. Determines aggregation operation for sets and distributions. Defaults to “mean”.
interpret (str, optional) – One of “set” or “distribution”. Determines whether to interpret value distributions as sets or distributions. Defaults to “distribution”.
- Returns:
A list of aggregated alternatives. Sublist entries are guaranteed to contain None, int or float values.
- Return type:
list[dict[str, Optional[float]]] (subtype of DexiAlternatives)
- dexipy.eval.alternatives_value_ranges(alternatives, attributes, defined_ranges={})
A helper function for determining attribute value ranges in alternatives. Particularly needed for continues attributes.
- Parameters:
alternatives (DexiAlternatives) – Aggregated DEXi alternatives.
attributes (list[str]) – Attribute IDs.
defined_ranges (dict[str, tuple[float, float]], optional) – Dictionary of attributes’ lower and upper range bounds that are already known. Attributes already listed in defined_ranges are not considered here and their ranges are just included in the output. Defaults to {}.
- Returns:
A dictionary, indexed by attribute IDs, containing (lower, upper) bound tuples.
- Return type:
dict[str, tuple[float, float]]
- dexipy.eval.columnize_alternatives(alternatives=None, model=None, attributes=None)
‘Columnizes’ alternatives to a dictionary of columns that is suitable for importing data to other packahes, such as Panda’s DataFrame. Data is columnized “as-is”, without any checking, which is left to the recipient.
- Parameters:
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of DexiAlternatives. Defaults to None, which invokes
dexipy.eval.get_alternatives()
to make the list.model (Optional[DexiModel], optional) – A DexiModel. Defaults to None.
attributes (Optional[Iterable[Optional[DexiAttribute | str]]], optional) – The list of attributes to be columnized. When present, it can contain DexiAttribute`s (which need a defined `model, otherwise AssertionError is raised) or attribute IDs (strings that are not checked against model). When None: if ‘model` is defined, then model.non_root_ids, otherwise attribute names are determined from alternatives themselves. Defaults to None.
- Returns:
- A dictionary composed of data columns.
Keys are attribute IDs and other column headings (such as “name”). Individual columns are lists, all of length equal to the number of alternatives, containing corresponding values extracted from alternatives.
- Return type:
dict[str, list]
- dexipy.eval.compare_two_alternatives(alt1, alt2, attributes, deep=True)
Compare two alternatives alt1 and alt2 with respect to attributes.
- Parameters:
alt1 (DexiAlternative) – First alternative.
alt2 (DexiAlternative) – Second alternative.
attributes (list[DexiAttribute]) – List of DexiAttribute objects.
deep (bool, optional) – When True and compared values are equal, subordinate attributes are additionally investigated for possible preferential differences. Defaults to True.
- Returns:
Float vector of the same length as attributes. Each element represents the comparison result w.r.t. the corresponding attribute. Possible element values are:
0: Values are equal.
-1: alt1’s value is worse than alt2’s.
+1: alt1’s value is better than alt2’s.
None: Values are incomparable.
When deep = True, the so-called deep comparison is performed: when the compared attribute’s values are equal, subordinate attributes are checked for differences, possibly returning:
-0.5: indicates the weak preference relation “<=”.
+0.5: indicates the weak preference relation “>=”.
- Return type:
list[float]
- dexipy.eval.convert_alternatives(model, alternatives=None, attributes=None, name='name', aggregate='mean', interpret='distribution', scale_values=True, omin=0, omax=1, defined_ranges={}, reverse_descending=True, shift=0)
- Converts alternatives’ data, generally performing four steps:
Aggregating DEXi values to single numbers, using
dexipy,eval.aggregate_alternatives()
.Scaling those numbers to a given numeric interval.
Reversing values corresponding to descending DexiAttributes.
Shifting values by a small amount (aimed at avoiding overlapped chart lines).
Steps 2-4 are optional.
- Parameters:
model (DexiModel) – A DexiModel object.
alternatives (Optional[DexiAltData], optional) – One or more DEXi alternatives. Defaults to None, which selects model.alternatives.
attributes (Optional[Iterable[Optional[DexiAttribute | str | int]]], optional) – A sequence of DexiAttribute`s, attribute IDs or indices. Defaults to None, which selects `model.attributes.
name (str) – Name of DexiAlternative element that contains alternatives’ name. Defaults to “name”.
aggregate (Optional[str], optional) – One of “min”, “max” or “mean”. Determines aggregation operation for sets and distributions. Defaults to “mean”.
interpret (str, optional) – One of “set” or “distribution”. Determines whether to interpret value distributions as sets or distributions. Defaults to “distribution”.
scale_values (bool, optional) – Whether or not to scale values to the [omin, omax] interval. Defaults to True.
omin (float, optional) – Lower output bound for value scaling. Defaults to 0.
omax (float, optional) – Upper output bound for value scaling. Defaults to 1.
defined_ranges (dict[str, tuple[float, float]], optional) – A dictionary of pre-determined value ranges. Applicable to continuous attributes. Continuous attribute ranges, which are not specified in defined_ranges, are determined from alternatives data. Discrete attribute ranges are always determined from their scales. Defaults to {}.
reverse_descending (bool, optional) – Whether or not to reverse values of descending attributes. Defaults to True.
shift (float, optional) – Used to “shift” numerical values by a small amount to avoid overlapping lines in charts. Defaults to 0.
- Returns:
A list of converted alternatives.
- Return type:
DexiAlternatives
- dexipy.eval.eval_parameters(method, and_op=None, or_op=None, norm=None)
Fetches default evaluation parameters from EvalMethods and optionally modifies them considering non-None arguments of this function.
- Parameters:
method (str) – Method name. Required.
and_op (Optional[CallableOperator], optional) – If not None, set the conjuntive aggregation function. Defaults to None.
or_op (Optional[CallableOperator], optional) – If not None, set the disjuntive aggregation function. Defaults to None.
norm (Optional[CallableNorm], optional) – If not None, set the normalization function. Defaults to None.
- Returns:
Fetched and optionally modified evaluation parameters.
- Return type:
- dexipy.eval.evaluate(model, alternatives=None, method='set', root=None, prune=[], pre_check=False, bounding=False, in_place=False, eval_param=None)
This is the main implementation of the evaluation method in DEXiPy.
While it is possible to call this function directly, it is also possible to avoid importing
dexipy.eval
and run evaluations usingdexipy.dexi.evaluate()
ordexipy.dexi.DexiModel.evaluate()
.Please see Evaluation of alternatives for more information about the evaluation process and evaluation methods used in DEXiPy.
- Parameters:
model (DexiModel) – A DexiModel object. Required.
alternatives (Optional[DexiAltSelect], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Defaults to None, which selects model.alternatives.
method (str, optional) – One of the strings “set”, “prob”, “fuzzy”, “fuzzynorm” that select the evaluation method. Defaults to “set”.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute of the evaluation. Defaults to None, which selects model.root.
prune (list[str], optional) – List of attribute IDs at which the evaluation is “pruned”. This means that input attributes below some pruned attribute are not evaluated and the pruned attribute is treated as an input (basic) attribute for this evaluation. Defaults to [].
pre_check (bool, optional) – Whether alternatives are checked by
dexipy.dexi.DexiModel.check_alternatives()
prior to evaluation. Defaults to False.bounding (bool, optional) – Whether or not the evaluation keeps calculated values within bounds prescribed by the corresponding scales. Defaults to False.
in_place (bool, optional) – If True, evaluation modifies alternatives in place, otherwise a deep copy is made and returned by the method. Defaults to False.
eval_param (Optional[eval.DexiEvalParameters], optional) – Optional
dexipy.eval.DexiEvalParameters
, which may customize the normalization and aggregation methods used in the evaluation. Defaults to None.
- Returns:
Returns a list of evaluated alternatives.
- Return type:
DexiAltData
- dexipy.eval.evaluation_order(att, prune=[])
Determine the evaluation order of attributes. Interpreted as a sequence, the order guarantees that whenever some attribute is reached as a next candidate for evaluation, all the affecting attributes have already been evaluated.
- Parameters:
att (DexiAttribute) – The starting point of evaluation.
prune (list[str], optional) – A list of attribute IDs at which to prune the evaluation. The evaluation will treat them as if they were basic attributes, not looking to any descendant attributes. Defaults to [].
- Returns:
A list of attribute IDs in the evaluation order.
- Return type:
list[str]
- dexipy.eval.export_alternatives(model, alternatives=None)
Export alternatives: Convert alternatives’ data to a data table, prepared to be written out by
dexipy.eval.write_alternatives()
- Parameters:
model (DexiModel) – A DexiModel object.
alternatives (Optional[DexiAltData], optional) – One or more DEXi alternatives. Defaults to None, which selects model.alternatives.
- Raises:
ValueError – When model is undefined.
- Returns:
Data table containing rows of strings to be written out.
- Return type:
list[list[str]]
- dexipy.eval.get_alt_value(alt, attid)
Returns
alt[attid]
.- Parameters:
alt (Any) – Expected a DexiAlternative.
attid (str) – Value ID, a key in the alt dictionary.
- Returns:
Alternative value corresponding to ID, or None if not found.
- Return type:
DexiValue
- dexipy.eval.get_alternatives(alternatives, model=None)
Makes a proper list of alternatives from alternatives.
- Parameters:
alternatives (Optional[DexiAltData]) – Alternative(s) specification, which might be None or contain a single alternative or a list of alternatives. None selects model.alternatives, but only if model is not None.
model (Optional[DexiModel], optional) – A DexiModel object. Defaults to None.
- Returns:
List of DEXi alternatives (may be empty, but not None or does not contain None).
- Return type:
list[DexiAlternative]
- dexipy.eval.write_alternatives(model, alternatives=None, filename='', **fmtparams)
Write alternatives to a file, which can be subsequently imported in DEXi/DEXiWin software.
In order to successfully import the output of this function in DEXi/DEXiWin software, the formats of this export and DEXi/DEXiWin’s settings must be properly configured and matched. In DEXi/DEXiWin, see “Import/Export” settings and make sure that they are set as follows:
Option values: “Base 1”
Attributes: “All”
Orientation: “Attributes Alternatives” or “normal”
CSV Format: “Invariant” (DEXiWin only)
When importing in the “csv” format, make sure that you write alternatives using the parameters:
write_alternatives(model, alternatives, filename, delimiter = ',')
For importing in the “tab” format, use the parameters:
write_alternatives(model, alternatives, filename, delimiter = '\t')
If alternatives contain value distributions, they can be imported only by DEXiWin and not by DEXi.
- Parameters:
model (DexiModel) – A DexiModel object.
alternatives (Optional[DexiAltData], optional) – One or more DEXi alternatives. Defaults to None, which selects model.alternatives.
filename (Optional[str], optional) – File name for writing out the data. None or “” mean that data is written to the console. Defaults to “”.
- Returns:
Writes out alternatives’ data to a file or console.
- Return type:
None
dexipy.analyse module
The module dexipy.analyse implements functions for the analysis of decision alternatives.
- dexipy.analyse.compare_alternatives(model, alternative, alternatives=None, root=None, prune=[], compare=True, deep=True, text=True, structure=True)
Compare Alternatives: Compare alternative with each of alternatives. Display only values that differ and, optionally when
compare = True
, include preference-relational operators.- Parameters:
model (DexiModel) – A DexiModel object. Required.
alternative (DexiAlternative) – A single DEXi alternative to be compared with alternatives.
alternatives (Optional[DexiAltSelect], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Alternatives are assumed to be previously fully evaluated. Defaults to None, which selects model.alternatives.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute for displaying results. Defaults to None, which selects model.root.
prune (list[str], optional) – List of attribute IDs at which the display is “pruned”, skipping their subordinate attributes. Defaults to [].
compare (bool, optional) – Whether to display preference comparison operators “=”, “<”, “>”, “<=”, “>=”. Defaults to True.
deep (bool, optional) – Whether of not “deep” comparison (see
dexipy.eval.compare_two_alternatives()
) is carried out. Defaults to True.text (bool, optional) – Whether to display results textually (True) or using internal value representation (False). Defaults to True.
structure (bool, optional) – Whether to display only attribute IDs in the first column (False) or to extend them with tree-structure information (True). Defaults to True.
- Raises:
ValueError – When model, alternative or alternatives are None, when alternative is not a single alternative, or when root is undefined.
- Returns:
None and prints out the resulting alternative comparison table.
- Return type:
None
- dexipy.analyse.plus_minus(model, alternative, target=None, minus=9223372036854775807, plus=9223372036854775807, text=True, structure=True)
Plus Minus Analysis: Investigate the effects of changing single attributes’ values on the evaluation of alternative. The values of discrete basic attributes (“input attributes”) are changed, one attribute at a time, by a particular number of steps downwards (minus) and upwards (plus), while observing the changes of the target attribute values.
- Parameters:
model (DexiModel) – A DexiModel object. Required.
alternative (DexiAlternative) – A single DexiAlternative. Assumed to be previously evaluated using evaluate().
target (Optional[DexiAttribute], optional) – A DexiAttribute on which effects are observed. Defaults to None, which selects model.root.
minus (int, optional) – The maximum number of downward steps to be made for each input attribute. Defaults to sys.maxsize. The actual minus value is further determined with respect to alternative values and involved attributes’ scales.
plus (int, optional) – The maximum number of upward steps to be made for each input attribute. Defaults to sys.maxsize. The actual plus value is further determined with respect to alternative values and involved attributes’ scales.
text (bool, optional) – Whether to display results textually (True) or using internal value representation (False). Defaults to True.
structure (bool, optional) – Whether to display only attribute IDs in the first column (False) or to extend them with tree-structure information. Defaults to True.
- Raises:
ValueError – When model is None, when target is None or does not have a scale defined, and when alternative is not a single DEXi alternative.
- Returns:
A data table containing the following columns of strings:
First column: Attribute IDs, optionally extended with structure information.
For -minus to -1: Columns containing evaluation values of target when decreasing attribute values by the corresponding number of steps.
Middle column: Original alternative values assigned to the corresponding attributes.
For +1 to +plus: Columns containing evaluation values of target when increasing attribute values by the corresponding number of steps.
- Return type:
Optional[list[list[str]]]
- Limitations:
Only basic attributes with defined discrete scales participate in the analysis.
- dexipy.analyse.selective_explanation(model, alternatives=None, root=None, prune=[], text=True, structure=True)
Selective Explanation: Displays subtrees of alternatives’ values in which values are particularly weak (DexiQuality.BAD) and particularly strong (DexiQuality.GOOD).
- Parameters:
model (DexiModel) – A DexiModel object. Required.
alternatives (Optional[DexiAltSelect], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Alternatives are assumed to be previously fully evaluated. Defaults to None, which selects model.alternatives.
root (Optional[DexiAttribute], optional) – The topmost (root) attribute for displaying results. Defaults to None, which selects model.root.
prune (list[str], optional) – List of attribute IDs at which the display is “pruned”, skipping their subordinate attributes. Defaults to [].
text (bool, optional) – Whether to display results textually (True) or using internal value representation (False). Defaults to True.
structure (bool, optional) – Whether to display only attribute IDs in the first column (False) or to extend them with tree-structure information (True). Defaults to True.
- Raises:
ValueError – When model or root are undefined.
- Return type:
None
dexipy.charts module
Module dexipy.charts is aimed at drawing various charts of alternatives.
- dexipy.charts.plotalt1(model, attribute=None, alternatives=None, colors=('r', 'k', 'g'), marker='o', markersize=1.0, left_adjust=None, plot=True)
Plot alternatives with respect to a single attribute.
- Parameters:
model (DexiModel) – A DexiModel object. Required.
attribute (Optional[DexiAttribute | str | int], optional) – A DexiAttribute object, attribute ID or attribute index. Defaults to None, which selects model.first().
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Defaults to None, which selects model.alternatives.
colors (tuple[ColorType, ColorType, ColorType], optional) – A tuple of three colors for displaying “bad”, “neutral” and “good” values, respectively. Defaults to (‘r’, ‘k’, ‘g’).
marker (str, optional) – Matplotlib marker to draw plot points. Defaults to ‘o’.
markersize (float, optional) – Relative marker size with respect to default plot size. Defaults to 1.0.
left_adjust (Optional[float], optional) – A number between 0 and 0.5 that reserves the left proportion of the plot for y-axis label and names of alternatives. Defaults to None, which approximates this proportion considering alternatives’ names.
plot (bool, optional) – Whether to draw (True) or return (False) the plot.
- Returns:
Draws the plot (if plot = True) or returns Matplotlib figure and axes (False).
- Return type:
Optional[tuple[Figure, Axes]]
- Raises:
ValueError – When model is None, when attribute cannot be determined from the second argument, or when attribute.scale is None.
- dexipy.charts.plotalt2(model, attribute1, attribute2, alternatives=None, colors=[], marker='o', markersize=1.0, left_adjust=None, label_adjust=0.1, plot=True)
Draw a scatterpolot of alternatives with attribute1 and attribute2 on the \(x\) and \(y\) axis, respectively.
- Parameters:
model (DexiModel) – A DexiModel object. Required.
attribute1 (DexiAttribute | str | int) – First attribute (x-axis). A DexiAttribute object, attribute ID or index.
attribute2 (DexiAttribute | str | int) – Second attribute (y-axis). A DexiAttribute object, attribute ID or index.
alternatives (Optional[DexiAltData], optional) – A single DexiAlternative or a list of alternatives (DexiAlternatives). Defaults to None, which selects model.alternatives.
colors (list[ColorType], optional) – A list of colors to be used for drawing consecutive alternatives (circulated if necessary). Defaults to [], which selects the matplotlib default color palette.
marker (str, optional) – Matplotlib marker to draw plot points. Defaults to ‘o’.
markersize (float, optional) – Relative marker size with respect to default plot size. Defaults to 1.0.
left_adjust (Optional[float], optional) – A number between 0 and 0.5 that reserves the left proportion of the plot for y-axis label and names of alternatives. Defaults to None, which approximates this proportion considering y-axis attribute values.
label_adjust (float, optional) – A number (in plot coordinates) indicating the displacement of alternative names, which are displayed with individual points, to the right. Defaults to 0.1.
plot (bool, optional) – Whether to draw (True) or return (False) the plot.
- Returns:
Draws the plot (if plot = True) or returns Matplotlib figure and axes (False).
- Return type:
Optional[tuple[Figure, Axes]]
- Raises:
ValueError – When model is None, when attribute1 or attribute2 cannot be determined from the respective arguments, or when attributes’ scales are not discrete.
- dexipy.charts.plotalt_parallel(model, attributes=None, alternatives=None, aggregate='minmax', name='name', interpret='distribution', scale_values=True, omin=0, omax=1, defined_ranges={}, reverse_descending=True, shift=0, colors=[], marker='o', markersize=5.0, linestyle='-', linewidth=2.0, figsize=(10, 5), rect=(0.1, 0.1, 0.7, 0.8), plot=True)
Plots DEXi alternatives on parallel axes, corresponding to attributes.
- Parameters:
model (DexiModel) – A DexiModel object.
attributes (Optional[Iterable[DexiAttribute | str | in]]], optional) – A sequence of DexiAttributes, attribute IDs or indices. Defaults to None, which selects model.non_root.
alternatives (Optional[DexiAltData], optional) – One or more DEXi alternatives. Defaults to None, which selects model.alternatives.
aggregate (Optional[str], optional) – One of “min”, “max”, “mean” or “minmax”. Determines aggregation operation for sets and distributions. “minmax” selects both “min” and “max”, so that each alternative is plotted twice. Defaults to “minmax”.
name (str) – Name of DexiAlternative element that contains alternatives’ name. Defaults to “name”.
interpret (str, optional) – One of “set” or “distribution”. Determines whether to interpret value distributions as sets or distributions. Defaults to “distribution”.
scale_values (bool, optional) – Whether or not to scale values to the [omin, omax] interval. Defaults to True.
omin (float, optional) – Lower output bound for value scaling. Defaults to 0.
omax (float, optional) – Upper output bound for value scaling. Defaults to 1.
defined_ranges (dict[str, tuple[float, float]], optional) – A dictionary of pre-determined value ranges. Applicable to continuous attributes. Continuous attribute ranges, which are not specified in defined_ranges, are determined from alternatives data. Discrete attribute ranges are always determibned from their scales. Defaults to {}.
reverse_descending (bool, optional) – Whether or not to reverse values of descending attributes. Defaults to True.
shift (float, optional) – Used to “shift” numerical values by a small amount to avoid overlapping lines in charts. Defaults to 0.
colors (list[ColorType], optional) – A list of colors to be used for drawing consecutive alternatives (circulated if necessary). Defaults to [], which selects the matplotlib default color palette.
marker (str, optional) – Matplotlib marker to draw plot points. Defaults to ‘o’.
markersize (float, optional) – Marker size. Defaults to 5.0.
linestyle (str, optional) – Matplotlib style to draw lines. Defaults to ‘-‘.
linewidth (float, optional) – Line width. Defaults to 2.0.
figsize (tuple[float, float], optional) – Figure size in inches. Defaults to (10, 5).
rect (tuple[float, float, float, float], optional) – (left, bottom, width, height), defines the position of the figure on the canvas. Elements are numbers between 0 and 1. Defaults to (0.1, 0.1, 0.7, 0.8).
plot (bool, optional) – Whether to draw (True) or return (False) the plot.
- Returns:
Draws the plot (if plot = True) or returns Matplotlib figure and axes (False).
- Return type:
Optional[tuple[Figure, list[Axes]]]
- dexipy.charts.plotalt_radar(model, attributes=None, alternatives=None, aggregate='minmax', name='name', interpret='distribution', scale_values=True, omin=0, omax=1, defined_ranges={}, reverse_descending=True, shift=0, colors=[], fill=0, marker='o', markersize=5.0, linestyle='-', linewidth=2.0, inner=0.2, figsize=(8, 5), legend_pos=(1.1, 1), legend_loc='upper left', plot=True)
Plots DEXi alternatives on parallel axes, corresponding to attributes.
- Parameters:
model (DexiModel) – A DexiModel object.
attributes (Optional[Iterable[DexiAttribute | str | int]], optional) – A sequence of DexiAttributes, attribute IDs or indices. Defaults to None, which selects model.attributes.
alternatives (Optional[DexiAltData], optional) – One or more DEXi alternatives. Defaults to None, which selects model.alternatives.
aggregate (Optional[str], optional) – One of “min”, “max”, “mean” or “minmax”. Determines aggregation operation for sets and distributions. “minmax” selects both “min” and “max”, so that each alternative is plotted twice. Defaults to “minmax”.
name (str) – Name of DexiAlternative element that contains alternatives’ name. Defaults to “name”.
interpret (str, optional) – One of “set” or “distribution”. Determines whether to interpret value distributions as sets or distributions. Defaults to “distribution”.
scale_values (bool, optional) – Whether or not to scale values to the [omin, omax] interval. Defaults to True.
omin (float, optional) – Lower output bound for value scaling. Defaults to 0.
omax (float, optional) – Upper output bound for value scaling. Defaults to 1.
defined_ranges (dict[str, tuple[float, float]], optional) – A dictionary of pre-determined value ranges. Applicable to continuous attributes. Continuous attribute ranges, which are not specified in defined_ranges, are determined from alternatives data. Discrete attribute ranges are always determibned from their scales. Defaults to {}.
reverse_descending (bool, optional) – Whether or not to reverse values of descending attributes. Defaults to True.
shift (float, optional) – Used to “shift” numerical values by a small amount to avoid overlapping lines in charts. Defaults to 0.
colors (list[ColorType], optional) – A list of colors to be used for drawing consecutive alternatives (circulated if necessary). Defaults to [], which selects the matplotlib default color palette.
fill (float | tuple[float, float]]) – Alpha-channel value(s) for color-filling the drawn polygon(s). Expected are values from the \([0, 1]\) interval. If fill > 0, polygons are filled with the same color as lines and with the given alpha. The tuple form may be used for to charts with aggregate = “minmax”, where the two tuple values represent alpha settings for the “max” and “min” polygon, respectively. Defaults to 0.
marker (str, optional) – Matplotlib marker to draw plot points. Defaults to ‘o’.
markersize (float, optional) – Marker size. Defaults to 5.0.
linestyle (str, optional) – Matplotlib style to draw lines. Defaults to ‘-‘.
linewidth (float, optional) – Line width. Defaults to 2.0.
inner (float, optional) – Radius of the inner chart circle where nothing is drawn. The value is relative to the \([0, 1]\) scale used to draw the data. Defaults to 0.2.
figsize (tuple[float, float], optional) – Figure size in inches. Defaults to (8, 5).
legend_pos (tuple[float, float], optional) – Legend position. Defaults to (1.1, 1).
legend_loc (str, optional) – Legend location. See matplotlib.axes.Axes.legend for possible values. Defaults to “upper left”.
plot (bool, optional) – Whether to draw (True) or return (False) the plot.
- Returns:
Draws the plot (if plot = True) or returns Matplotlib figure and axes (False).
- Return type:
Optional[tuple[Figure, Axes]]
dexipy.parse module
The module dexipy.parse implements parsing and reading of .dxi files.
The only functions interesting for public use are dexipy.parse.read_dexi()
and
dexipy.parse.read_dexi_from_string()
; both are aliased in the module
dexipy.dexi
.
For more information, please refer to
dexipy.dexi.read_dexi()
and dexipy.dexi.read_dexi_from_string()
.
- dexipy.parse.read_dexi(filename)
Read a DexiModel from file.
- Parameters:
filename (str) – File name.
- Raises:
ValueError – When the file does not contain a DEXi model.
- Returns:
A DexiModel object.
- Return type:
dexipy.utils module
Module dexipy.utils contains a collection of helper functions used in DEXiPy.
- dexipy.utils.aligned(s, width=-1, align='l')
Pads and/or aligns the string.
- Parameters:
s (str) – Some input string.
width (int, optional) – The required length of the resulting string. Defaults to -1, not affecting string length.
align (str, optional) – A one-character string in
("l", "c", "r")
, requesting a left, centered or right justification, respectively. Any other value returns the original string. Defaults to “l”.
- Returns:
Padded and justified string.
- Return type:
str
- dexipy.utils.cartesian_product(*dimensions)
Constructs the cartesian product of ranges, tuples or sets submitted as the function arguments.
Uses itertools.product.
- Returns:
List of all possible combinations of values of dimensions.
Examples
>>> cartesian_product((0, 1), (2, 3, 4)) [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)] >>> cartesian_product({"a", "b"}, (2, 3, 4)) [('a', 2), ('a', 3), ('a', 4), ('b', 2), ('b', 3), ('b', 4)] >>> cartesian_product(range(2), range(3)) [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
- dexipy.utils.check_str(check, errors=True, warnings=False)
Makes a string, suitable for printing, from an error/warning dictionary.
- Parameters:
check (dict[str, list[str]]) – A dictionary in the form
{"errors": [...], "warnings": [...]}
.errors (bool, optional) – Should this function consider errors? Defaults to True.
warnings (bool, optional) – Should this function consider warnings? Defaults to False.
- Returns:
A string containing error and warning messages, formatted for printing.
- Return type:
str
- dexipy.utils.col_width(column)
Calculates the maximum width of strings in column.
- Parameters:
column (None | list[str]) – A list of strings.
- Returns:
Maximum string length.
- Return type:
int
- dexipy.utils.compare_operator(comp, none='', eq='=', lt='<', le='<=', gt='>', ge='>=')
Converts a float value comparison value to a string operator.
- Parameters:
comp (Optional[float]) – Result of comparison of two variables. Expected values are: None, -1, -0.5, 0, +0.5, +1.
none (str, optional) – String representation of None (incomparable values). Defaults to “”.
zero (str, optional) – String representation of 0 (equal values). Defaults to “=”.
lt (str, optional) – String representation of -1 (lower_than). Defaults to “<”.
le (str, optional) – String representation of -0.5 (lower_than or equal). Defaults to “<=”.
gt (str, optional) – String representation of +1 (greater_than). Defaults to “>”.
ge (str, optional) – String representation of +0.5 (greater_than or equal). Defaults to “>=”.
eq (str)
- Returns:
String representation of comp. Returns “?” for an unexpected argument value.
- Return type:
str
- dexipy.utils.dict_to_list(distr)
Converts a dictionary-form value distribution to a list-form one. Example:
{1: 0.7, 2: 0.2}
is converted to[0.0, 0.7, 0.2]
.- Parameters:
distr (dict[int, float]) – A dictionary-form value distribution to be converted.
- Returns:
A list-form value distribution.
- Return type:
list[float]
Examples
>>> dict_to_list({1: 0.7, 2: 0.2}) [0.0, 0.7, 0.2]
- dexipy.utils.distr_to_set(distr, eps=2.220446049250313e-16)
Converts a DEXi value distribution to a DEXi value set.
- Parameters:
distr (list[float]) – A distribution to be converted.
eps (float, optional) – Threshold for determining whether a distribution element can be considered a member of the resulting set. Defaults to float_info.epsilon.
- Returns:
The set, composed of indices of distr elements greater than eps.
- Return type:
set[int]
Examples
>>> distr_to_set([0.0, 0.5, 1.0, 0.0]) {1, 2} >>> distr_to_set([0.0, 0.5, 1.0, 0.0], 0.5) {2}
- dexipy.utils.distr_to_strict_set(distr, eps=2.220446049250313e-16)
Converts a DEXi value distribution to a DEXi value set. Only distributions that strictly represent sets, i.e., they contain only 0.0 and 1.0 entries, are converted.
- Parameters:
distr (list[float]) – A distribution to be converted.
eps (float, optional) – Allowed tolerance around distribution values, so that they can be considered 0.0 or 1.0. Defaults to float_info.epsilon.
- Returns:
The set, composed of indices of distr elements that differ from 0.0 or 1.0 for at most eps. None is returned if distr contains values that are not sufficiently close to 0.0 or 1.0.
- Return type:
Optional[set[int]]
Examples
>>> distr_to_strict_set([0.0, 0.5, 1.0, 0.0]) # returns None >>> distr_to_strict_set([0.0, 1.0, 1.0, 0.0]) {1, 2} >>> distr_to_strict_set([0.0, 0.9, 1.1, 0.0]) # returns None >>> distr_to_strict_set([0.0, 0.9, 1.1, 0.0], 0.1) {1, 2}
- dexipy.utils.is_in_range(x, lb, hb, la=BoundAssoc.UP, ha=BoundAssoc.DOWN)
Checks whether or not the argument x lies in the interval bounded by lb and hb, considering the corresponding bound associations la and ha.
- Parameters:
x (float) – An integer or floating point value.
lb (float) – Lower interval bound.
hb (float) – Upper interval bound.
la (BoundAssoc, optional) – Bound association of lb. Defaults to BoundAssoc.UP.
ha (BoundAssoc, optional) – Bound association of hb. Defaults to BoundAssoc.DOWN.
- Returns:
Whether or not x lies in the specified interval.
- Return type:
bool
Examples
>>> is_in_range(0.5, 0, 1) True >>> is_in_range(0.0, 0, 1, BoundAssoc.UP, BoundAssoc.DOWN) True >>> is_in_range(0.0, 0, 1, BoundAssoc.DOWN, BoundAssoc.DOWN) False >>> is_in_range(1.0, 0, 1, BoundAssoc.DOWN, BoundAssoc.DOWN) True >>> is_in_range(1.0, 0, 1, BoundAssoc.DOWN, BoundAssoc.UP) False
- dexipy.utils.lin_map(x, imin, imax, omin=0.0, omax=1.0)
Map value \(x\) linearly from interval \([imin:imax]\) to \([omax:omax]\).
- Parameters:
x (float) – Value to be mapped.
imin (float) – Lower bound of the input range.
imax (float) – Upper bound of the input range.
omin (float, optional) – Lower bound of the output range. Defaults to 0.0.
omax (float, optional) – Upper bound of the output range. Defaults to 1.0.
- Returns:
Mapped value.
- Return type:
float
- Raises:
ZeroDivisionError – when \(imin = imax\).
- dexipy.utils.lin_map_values(values, imin, imax, omin=0.0, omax=1.0)
Map values \(x\) linearly from interval \([imin:imax]\) to \([omax:omax]\), using
lin_map()
.- Parameters:
values (Sequence[float]) – Values to be mapped.
imin (float) – Lower bound of the input range.
imax (float) – Upper bound of the input range.
omin (float, optional) – Lower bound of the output range. Defaults to 0.0.
omax (float, optional) – Upper bound of the output range. Defaults to 1.0.
- Returns:
Mapped value.
- Return type:
list[float]
- Raises:
ZeroDivisionError – when \(imin = imax\).
- dexipy.utils.name_to_id(name, replace='_')
Replaces all non-alphanumeric characters in name with replace.
- Parameters:
name (str) – Some string.
replace (str, optional) – Replacement string. Defaults to “_”.
- Returns:
Converted string.
- Return type:
str
Example
>>> name_to_id("Some #string 1") 'Some__string_1'
- dexipy.utils.names_to_ids(names, replace='_')
A vectorized version of
dexipy.utils.name_to_id()
.- Parameters:
names (list[str]) – List of strings.
replace (str, optional) – Replacement string. Defaults to “_”.
- Returns:
Converted list of strings, of the same length as names.
- Return type:
list[str]
- dexipy.utils.norm_max(vals, req_max=1.0)
Normalizes a list of float values so that
max(values) == req_max
.- Parameters:
vals (list[float]) – A list of values.
req_max (float, optional) – The required maximum of the resulting list. Defaults to 1.0.
- Returns:
Normalized list. Returns the original list if
max(vals) == 0
.- Return type:
list[float]
Examples
>>> norm_max([0.1, 0.2, 0.4]) [0.25, 0.5, 1.0] >>> norm_max([0.1, -0.2, 0.4]) [0.25, -0.5, 1.0] >>> norm_max([0.1, -0.2, 0.4], 2) [0.5, -1.0, 2.0]
- dexipy.utils.norm_none(vals)
A no-normalization function that can be used in place of other normalization functions.
- Parameters:
vals (list[float]) – A list of values.
- Returns:
The original list of values. No normalization is performed.
- Return type:
list[float]
- dexipy.utils.norm_sum(vals, req_sum=1.0)
Normalizes a list of float values so that
sum(vals) == req_sum
.- Parameters:
vals (list[float]) – A list of values.
req_sum (float, optional) – The required sum of the resulting list. Defaults to 1.0.
- Returns:
Normalized list. Returns the original list if
sum(vals) == 0
.- Return type:
list[float]
Examples
>>> norm_sum([0.1, 0.2, 0.5]) [0.125, 0.25, 0.625] >>> norm_sum([0.1, -0.2, 0.5]) [0.25, -0.5, 1.25] >>> norm_sum([0.1, 0.2, 0.5], 2) [0.25, 0.5, 1.25]
- dexipy.utils.objlen(obj)
Returns length of any object type.
- Parameters:
obj (Any) – An object.
- Returns:
len(obj) if object’s length is defined, or 0 otherwise.
- Return type:
int
- dexipy.utils.pad_list(lst, newlen, pad)
Pads a list to the required length, adding pad elements if necessary.
- Parameters:
lst (list[Any]) – List of objects of any type.
newlen (int) – The required length of the resulting list.
pad (Any) – Elements to be added if necessary.
- Returns:
A list obtained from lst, padded or trimmed to the required length.
- Return type:
list[Any]
- dexipy.utils.prod(iterable)
Calculates the product of arguments.
- Parameters:
iterable (Iterable[int | float]) – A sequence of integer or float numbers.
- Returns:
Product of arguments.
- Return type:
int | float
- dexipy.utils.round_float(val, decimals=None)
Rounds a float number to the required number of decimals.
- Parameters:
val (float) – An int or float number.
decimals (Optional[int], optional) – The required number of decimals. No rounding takes place if None. Defaults to None.
- Returns:
Rounded float value.
- Return type:
float
- dexipy.utils.round_float_list(values, decimals=None)
Rounds all list elements to the required number of decimals. A vectorized version of
dexipy.utils.round_float()
.- Parameters:
values (list[float]) – List of floats.
decimals (Optional[int], optional) – The required number of decimals. No rounding takes place if None. Defaults to None.
- Returns:
A list of rounded values.
- Return type:
list[float]
- dexipy.utils.rule_values(vals, add=0)
Convert a DEXi rule values string to a tuple of integers to be used in DEXiPy.
In .dxi files, values of decision rules are encoded using character strings, where each individual character encodes some function value. The encoding is zero-based, so that the character “0” represents the lowest ordinal number on the corresponding discrete scale.
- Parameters:
vals (str) – A value string as used in .dxi files.
add (int, optional) – An optional integer value to be added to elements of the resulting tuple. Defaults to 0.
- Returns:
A tuple of integers, of the same length as vals.
- Return type:
tuple[int, …]
Example
>>> rule_values("05A") (0, 5, 17)
- dexipy.utils.set_to_distr(valset, length=0)
Converts a set to a value distribution.
- Parameters:
valset (int | set[int]) – A value to be converted.
length (int, optional) – The required length of the distribution. Defaults to 0.
- Returns:
Set converted to a list of floats. The minimal length of the list is length, but it may be extended if valset contains elements larger than length - 1.
- Return type:
list[float]
Examples
>>> set_to_distr(1) [0.0, 1.0] >>> set_to_distr(1, 5) [0.0, 1.0, 0.0, 0.0, 0.0] >>> set_to_distr({1,2}, 4) [0.0, 1.0, 1.0, 0.0]
- dexipy.utils.table_lines(columns, align='', def_align='l')
A general-purpose function for making a table from a list of column strings.
- Parameters:
columns (list[list[str]]) – A list of columns. Each column is a list of strings.
align (str, optional) – A string consisting of letters in (“l”, “c”, “r”) that indicate the justification of the corresponding columns . Defaults to “”.
def_align (str, optional) – Default aligning character for columns not specified in align. Defaults to “l”.
- Returns:
A list of table lines that can be joined for printing.
- Return type:
list[str]
- dexipy.utils.unique_names(names, reserved=[], start=0)
Converts a list of strings to a list of unique ID strings.
- Parameters:
names (list[str]) – A list of strings to be converted to IDs.
reserved (list[str], optional) – Reserved strings that should not be used as IDs. Defaults to [].
start (int, optional) – To make IDs unique, indices of the form _<int> are added to the original strings. This argument defines the starting index, which corresponds to the first appearance of some string and is incremented before each subsequent occurence. Defaults to 0.
- Returns:
A list of unique IDs, of the same length as names.
- Return type:
list[str]
Examples
>>> unique_names(["name", "state", "name", "city", "name", "zip", "zip"]) ['name', 'state', 'name_1', 'city', 'name_2', 'zip', 'zip_1'] >>> unique_names(["name", "name", "city", "name", "zip", "zip"], reserved = ["name"]) ['name_1', 'name_2', 'city', 'name_3', 'zip', 'zip_1']
- dexipy.utils.values_to_str(vals, add=0)
Converts numbers to a DEXi string. A reverse operation of
rule_values()
.- Parameters:
vals (Iterable[int]) – An iterable of integers to be converted to characters.
add (int, optional) – An optional integer value to be added to vals before conversion. Defaults to 0.
- Returns:
A string of the same length as vals.
- Return type:
str
Example
>>> values_to_str((0, 5, 17)) '05A'