Core#
impactshpc.src.core Package#
Core classes and functions of ImpactsHPC
- class impactshpc.src.core.CorrelationMode(*values)#
Enumeration representing the correlation mode of a value. See Uncertainty.
- DEPENDENT#
Indicates that the value is positively correlated with other variables in the context (correlation = 1).
- INDEPENDENT#
Indicates that the value is independent and not affected by other variables in the context (correlation = 0).
- DEPENDENT = 'DEPENDENT'#
- INDEPENDENT = 'INDEPENDENT'#
- class impactshpc.src.core.Formatter(uncertainty_format: UncertaintyFormat = UncertaintyFormat.STANDARD_DEVIATION)#
Abstract class Formatter defines a simple API for formatting the
ReplicableValuein theReplicableValue.explain()method.Formatter uses Python generics for type hinting.
T is a type, defined by each sub-class of Formatter for the whole subclass. For example, in
JSONFormatter, T is defined asdict.format_sourced_value()andformat_operation()must return something of type T. So forJSONFormattertheir return type isdict.U is the
format_result()return type, it will the type of the output result. ForJSONFormatter, it’sstr. Under the hood,JSONFormatter.format_sourced_value()andJSONFormatter.format_operation()returns dicts andJSONFormatter.format_result()usesjson.dumps()to convert thoses dicts to JSON.- uncertainty_format#
the uncertainty format. See Uncertainty. Defaults to UncertaintyFormat.STANDARD_DEVIATION.
- Type:
UncertaintyFormat, optional
- abstractmethod format_extracted_important_values(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None) T#
Format extracted values which are the
ReplicableValueinstances with theReplicable.importantboolean set to true. These values are extracted and can be used to format the final result informat_result().- Parameters:
name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
source (str) – The source (quote, link, etc.) of the value.
warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
- Returns:
Formatted extracted important source value.
- Return type:
T
- abstractmethod format_operation(formula: str, name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, operator: str, operands: list[T], isInfix: bool, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) T#
Format an
Operationinstance. This method must be implemented.- Parameters:
formula (str) – A string representing the formula that the
Operationrepresents, returned byOperation._as_formula().name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
operator (str) – The operator of this operation.
operands (list[T]) – List of the operands used in this operation, already formatted.
isInfix (bool) – True if the operation is infix (i.e., it’s a binary operation and the operator is placed between the operands, like
A + B). False if the operation is prefix (i.e., the operation can have any number of parameters and is written as a function, likeln(a)).warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
recursion_level (int) – Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().already_seen (bool) – Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.important (bool) – True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.
- Returns:
The formatted
Operation.- Return type:
T
- abstractmethod format_result(result: T, extracted_important_values: list[T]) U#
Format the final result. Does nothing by default, but can be overridden to process or modify the final result before
ReplicableValue.explain()returns it.For example,
TextFormatteroverridesformat_result()in order to add the extracted important values at the beginning of the explanation.JSONFormatteroverrideformat_result()to usejson.dumps()on the final dict returned byformat_operation()andformat_sourced_value()- Parameters:
result (T) – The formatted result of
ReplicableValue._explain_rec().extracted_important_values (list[T]) – The extracted important values. These can be used to add a quick recap of the important results at the beginning of the explanation.
- Returns:
By default, returns the
resultparameter as is. Can be overridden to modify the final result beforeReplicableValue.explain()returns it.- Return type:
T
- abstractmethod format_sourced_value(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) T#
Format a
SourcedValueinstance. This method must be implemented.- value#
The central value, with units.
- Type:
Quantity
- min#
Minimum plausible value.
- Type:
Quantity
- max#
Maximum plausible value.
- Type:
Quantity
- standard_deviation#
Standard deviation (uncertainty) of the value.
- Type:
Quantity
- recursion_level#
Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().- Type:
- already_seen#
Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.- Type:
- important#
True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.- Type:
- Returns:
The formatted
SourcedValue.- Return type:
T
- class impactshpc.src.core.FuzzymatchMultipleResult(request: str, results: List[str], threshold: float = 90)#
- __repr__()#
Return repr(self).
- class impactshpc.src.core.FuzzymatchSingleResult(request: str, result: str)#
- __repr__()#
Return repr(self).
- class impactshpc.src.core.HTMLFormatter(uncertainty_format: UncertaintyFormat = UncertaintyFormat.STANDARD_DEVIATION)#
- format_extracted_important_values(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None) str#
Format extracted values which are the
ReplicableValueinstances with theReplicable.importantboolean set to true. These values are extracted and can be used to format the final result informat_result().- Parameters:
name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
source (str) – The source (quote, link, etc.) of the value.
warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
- Returns:
Formatted extracted important source value.
- Return type:
T
- format_operation(formula: str, name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, operator: str, operands: list[str], isInfix: bool, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) str#
Format an
Operationinstance. This method must be implemented.- Parameters:
formula (str) – A string representing the formula that the
Operationrepresents, returned byOperation._as_formula().name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
operator (str) – The operator of this operation.
operands (list[T]) – List of the operands used in this operation, already formatted.
isInfix (bool) – True if the operation is infix (i.e., it’s a binary operation and the operator is placed between the operands, like
A + B). False if the operation is prefix (i.e., the operation can have any number of parameters and is written as a function, likeln(a)).warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
recursion_level (int) – Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().already_seen (bool) – Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.important (bool) – True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.
- Returns:
The formatted
Operation.- Return type:
T
- format_result(result: str, extracted_important_values: List[str]) str#
Format the final result. Does nothing by default, but can be overridden to process or modify the final result before
ReplicableValue.explain()returns it.For example,
TextFormatteroverridesformat_result()in order to add the extracted important values at the beginning of the explanation.JSONFormatteroverrideformat_result()to usejson.dumps()on the final dict returned byformat_operation()andformat_sourced_value()- Parameters:
result (T) – The formatted result of
ReplicableValue._explain_rec().extracted_important_values (list[T]) – The extracted important values. These can be used to add a quick recap of the important results at the beginning of the explanation.
- Returns:
By default, returns the
resultparameter as is. Can be overridden to modify the final result beforeReplicableValue.explain()returns it.- Return type:
T
- format_sourced_value(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) str#
Format a
SourcedValueinstance. This method must be implemented.- value#
The central value, with units.
- Type:
Quantity
- min#
Minimum plausible value.
- Type:
Quantity
- max#
Maximum plausible value.
- Type:
Quantity
- standard_deviation#
Standard deviation (uncertainty) of the value.
- Type:
Quantity
- recursion_level#
Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().- Type:
- already_seen#
Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.- Type:
- important#
True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.- Type:
- Returns:
The formatted
SourcedValue.- Return type:
T
- class impactshpc.src.core.Impacts(impact_per_criteria: dict[str, ReplicableValue])#
- __add__(other: Impacts | ReplicableValue | int) Impacts#
- __mul__(other: Impacts | ReplicableValue | int) Impacts#
- __sub__(other: Impacts | ReplicableValue | int) Impacts#
- __truediv__(other: Impacts | ReplicableValue | int) Impacts#
- static from_config(name: str, configEntry: dict[str, dict[str, Any]]) Impacts#
Creates an Impact object from a configuration entry. The configEntry should be a dictionary where keys are criteria names and values are dictionaries with ‘value’ and ‘source’ keys.
- make_intermediate_result(name: str, explainations: str | None = None, ontology: Ontology | None = None)#
Call
impacthpc.src.core.ReplicableValue.make_intermediate_result()on theimpacthpc.src.core.ReplicableValueof this Impcats.
- values() list[ReplicableValue]#
- class impactshpc.src.core.JSONFormatter(uncertainty_format: UncertaintyFormat = UncertaintyFormat.STANDARD_DEVIATION)#
- format_extracted_important_values(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None) dict#
Format extracted values which are the
ReplicableValueinstances with theReplicable.importantboolean set to true. These values are extracted and can be used to format the final result informat_result().- Parameters:
name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
source (str) – The source (quote, link, etc.) of the value.
warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
- Returns:
Formatted extracted important source value.
- Return type:
T
- format_operation(formula: str, name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, operator: str, operands: list[dict], isInfix: bool, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) dict#
Format an
Operationinstance. This method must be implemented.- Parameters:
formula (str) – A string representing the formula that the
Operationrepresents, returned byOperation._as_formula().name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
operator (str) – The operator of this operation.
operands (list[T]) – List of the operands used in this operation, already formatted.
isInfix (bool) – True if the operation is infix (i.e., it’s a binary operation and the operator is placed between the operands, like
A + B). False if the operation is prefix (i.e., the operation can have any number of parameters and is written as a function, likeln(a)).warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
recursion_level (int) – Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().already_seen (bool) – Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.important (bool) – True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.
- Returns:
The formatted
Operation.- Return type:
T
- format_result(result: dict, extracted_important_values: List[dict]) str#
Format the final result. Does nothing by default, but can be overridden to process or modify the final result before
ReplicableValue.explain()returns it.For example,
TextFormatteroverridesformat_result()in order to add the extracted important values at the beginning of the explanation.JSONFormatteroverrideformat_result()to usejson.dumps()on the final dict returned byformat_operation()andformat_sourced_value()- Parameters:
result (T) – The formatted result of
ReplicableValue._explain_rec().extracted_important_values (list[T]) – The extracted important values. These can be used to add a quick recap of the important results at the beginning of the explanation.
- Returns:
By default, returns the
resultparameter as is. Can be overridden to modify the final result beforeReplicableValue.explain()returns it.- Return type:
T
- format_sourced_value(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) dict#
Format a
SourcedValueinstance. This method must be implemented.- value#
The central value, with units.
- Type:
Quantity
- min#
Minimum plausible value.
- Type:
Quantity
- max#
Maximum plausible value.
- Type:
Quantity
- standard_deviation#
Standard deviation (uncertainty) of the value.
- Type:
Quantity
- recursion_level#
Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().- Type:
- already_seen#
Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.- Type:
- important#
True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.- Type:
- Returns:
The formatted
SourcedValue.- Return type:
T
- class impactshpc.src.core.Operation(name: str | None, value: Quantity | str, min: Quantity | str | None, max: Quantity | str | None, operator: str, operands: list[ReplicableValue | int | float], isInfix: bool = True, standard_deviation: Quantity | str | None = None, warnings: List[str] = [], explaination: str | None = None, ontology: Ontology | None = None, important: bool = False)#
Subclass of
ReplicableValuerepresenting the composed nodes of a tree, as opposed toSourcedValue, which represents the leaf of the tree.In addition to the attributes of ReplicableValue, Operations have an operator and operands and can represent infix operations (like a + b, where the
+operator is between the two operands) or prefix operations (like ln(a), where the operator is a function name before the operands).- operands#
The list of operands. Operands can be ReplicableValues or numbers (int or float). Numbers are treated as if min = max = value, and standard_deviation = 0.
- Type:
List[ReplicableValue | int | float]
- isInfix#
Trueif the operation is infix (like a + b, where the+operator is between the two operands),Falseif it is prefix (like ln(a), where the operator is a function name before the operands).- Type:
- _as_formula() str#
Returns a string representing the formula that this ReplicableValue represents.
For each operand, it is converted to a string (see
ReplicableValue.__repr__()). If the operand is an intermediate result (i.e., it has a name, seeReplicableValue.make_intermediate_result()), it will return its name; otherwise, it will recursively call itsReplicableValue._as_formula()method.The decision to parenthesize an operand is based on the following rule: If an operand is not an intermediate result and it is an Operation (i.e., its string representation will be a formula), then we examine its operator. If this operator has a higher priority than
self.operatoraccording tooperator_priorities, we parenthesize the operand. Otherwise, we do not.- Returns:
A string representing the formula that this ReplicableValue represents.
- Return type:
- _explain_rec(formatter: ~impactshpc.src.core.formatters.Formatter[~typing.Any, T] = <impactshpc.src.core.formatters.TextFormatter object>, recursion_level: int = 0, already_seen_values: set[int] = {}) T | list[T]#
Provides an explanation of the current object using the specified formatter. Uses a Depth-first search algorithm, and respect the order of the
operandslist.First, it calls the
ReplicableValue._explain_rec()method on each of its operands. Then, it flattens the list of operands’ operands to obtain the list of ReplicableValues used to compute this result.If the current object is an intermediate result (i.e., it has a name, see
ReplicableValue.make_intermediate_result()), it callsFormatter.format_operation()with the created list.Otherwise, if it is not an intermediate result, it simply returns this list as is.
For example, suppose that
self.operatoris “+” andself.operandsis[A, B], where A and B are two ReplicableValues. Ifself.nameis not None, then this Operation is an intermediate result. We callA.explain()andB.explain().Let’s say A is a SourcedValue, so
A.explain()returns something of the formatter’s type, whileB.explain()is an operation that isn’t an intermediate result. Thus,B.explain()returns a list of ReplicableValues. Suppose it returns a list of two SourcedValues. We create a 3-element list with the return value of A and the two operands of B, and we pass it toFormatter.format_operation().If
self.namehad been None, then this Operation would not be an intermediate result, and thus we would have just returned the 3-element list as is.- Parameters:
- Returns:
The formatted explanation of the object or a list of formatted explanations.
- Return type:
Union[T, List[T]]
- extract_important_values() list[SourcedValue]#
Returns a list of the SourcedValues (leaves) used in the computation.
Recursively calls
extract_sourced_values()on each operand.
- class impactshpc.src.core.ReplicableValue(name: str | None, value: Quantity | str, min: Quantity | str | None, max: Quantity | str | None, standard_deviation: Quantity | str | None = None, warnings: List[str] = [], explaination: str | None = None, ontology: Ontology | None = None, important: bool = False)#
ReplicableValue is a core class of ImpactsHPC for representing numerical values with associated uncertainties and provenance. This class enables the construction of operation trees, where each leaf represents a value (with its minimum, maximum, and standard deviation) and each node represents an operation that produces a result. Arithmetic operations between ReplicableValue instances automatically propagate uncertainties according to standard rules (see https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulae). See ReplicableValue.
- correlation_mode#
(static) Class-level setting for how uncertainties are combined during operations.
- Type:
- value#
The central value, with units.
- Type:
Quantity
- min#
Minimum plausible value.
- Type:
Quantity
- max#
Maximum plausible value.
- Type:
Quantity
- standard_deviation#
Standard deviation (uncertainty) of the value.
- Type:
Quantity
- important#
True if the value is important. When true, this value is extracted during the explaination process in
explain()- Type:
Note
This class is abstract and should not be instantiated directly. Subclasses must implement
_as_formula()andexplain(). The two subclasses areSourcedValueandOperation.- __add__(other: ReplicableValue | int | float) ReplicableValue#
- __mul__(other: ReplicableValue | int | float) ReplicableValue#
- __sub__(other: ReplicableValue | int | float) ReplicableValue#
- __truediv__(other: ReplicableValue | int | float) ReplicableValue#
- static _add(a: ReplicableValue | int | float, b: ReplicableValue | int | float) ReplicableValue#
Implements the addition operator for ReplicableValue objects. Supports addition with another ReplicableValue, int, or float. If
otheris an int or float, the value is added to the current value, considering a standard deviation of 0 and the same unit as self.- Parameters:
a (ReplicableValue | int | float) – The first operand
b (ReplicableValue | int | float) – The second operand
- Returns:
The result of the addition as a new Operation object.
- Return type:
- Raises:
NotImplementedError – If the operand type is not supported.
- abstractmethod _as_formula() str#
Returns a string representing the formula that this ReplicableValue represents.
- static _div(a: ReplicableValue | int | float, b: ReplicableValue | int | float) ReplicableValue#
Implements the division operator for ReplicableValue objects. Supports division with another ReplicableValue, int, or float. If
otheris an int or float, the value is added to the current value, considering a standard deviation of 0 and the same unit as self.- Parameters:
a (ReplicableValue | int | float) – The first operand
b (ReplicableValue | int | float) – The second operand
- Returns:
The result of the division as a new Operation object.
- Return type:
- Raises:
NotImplementedError – If the operand type is not supported.
- abstractmethod _explain_rec(formatter: ~impactshpc.src.core.formatters.Formatter[~typing.Any, T] = <impactshpc.src.core.formatters.TextFormatter object>, recursion_level: int = 0, already_seen_values: set[int] = {}) T | list[T]#
Recusive method called by
explain()to provides an explanation of the current object using the specified formatter.- See implementations in:
- Args:static_usage_attributed_to_job
formatter (impacthpc.src.core.formatters.Formatter[T]): The formatter used to format the explanation. Defaults to
TextFormatter. recursion_level (int, optional): The current recursion depth, used to control nested explanations. Defaults to 0. already_seen_values (set[int]): A set of hashs of theReplicableValuethat have already been traversed when a value is duplicated and present in several branches.
- Returns:
The formatted explanation of the object.
- Return type:
T
- static _mul(a: ReplicableValue | int | float, b: ReplicableValue | int | float) ReplicableValue#
Implements the multiplication operator for ReplicableValue objects. Supports multiplication with another ReplicableValue, int, or float. If
otheris an int or float, the value is added to the current value, considering a standard deviation of 0 and the same unit as self.- Parameters:
a (ReplicableValue | int | float) – The first operand
b (ReplicableValue | int | float) – The second operand
- Returns:
The result of the multiplication as a new Operation object.
- Return type:
- Raises:
NotImplementedError – If the operand type is not supported.
- static _sub(a: ReplicableValue | int | float, b: ReplicableValue | int | float) ReplicableValue#
Implements the substraction operator for ReplicableValue objects. Supports substraction with another ReplicableValue, int, or float. If
otheris an int or float, the value is added to the current value, considering a standard deviation of 0 and the same unit as self.- Parameters:
a (ReplicableValue | int | float) – The first operand
b (ReplicableValue | int | float) – The second operand
- Returns:
The result of the substraction as a new Operation object.
- Return type:
- Raises:
NotImplementedError – If the operand type is not supported.
- static average(values: List[float | int], unit: str, name: str, source: str) SourcedValue#
Computes the average of the list as a SourcedValue.
valueis the average ofvalues.minandmaxare the minimum and maximum ofvalues.standard_deviationis the standard deviation ofvalues.
- Parameters:
- Returns:
An object containing the average, minimum, maximum, and standard deviation of the input values, all formatted with the specified unit, along with the provided name and source.
- Return type:
- Raises:
ValueError – If the input list of values is empty.
- correlation_mode: CorrelationMode = 'INDEPENDENT'#
- explain(formatter: ~impactshpc.src.core.formatters.Formatter[~typing.Any, T] = <impactshpc.src.core.formatters.TextFormatter object>) T#
Provides an explanation of the current object using the specified formatter.
Internally calls
_explain_rec()and format the result withFormatter.format_result(). It extracts the important values usingextract_important_values()and pass them toFormatter.format_result().- Parameters:
formatter (impacthpc.src.core.formatters.Formatter[T]) – The formatter used to format the explanation. Defaults to
TextFormatter.recursion_level (int, optional) – The current recursion depth, used to control nested explanations. Defaults to 0.
- Returns:
The formatted explanation of the object.
- Return type:
T
- static ln(value: ReplicableValue) ReplicableValue#
Computes the natural logarithm of a value.
- Parameters:
value (ReplicableValue) – The value for which to compute the natural logarithm.
- Returns:
The result of the natural logarithm as a new Operation object.
- Return type:
- Raises:
NotImplementedError – If the operand type is not supported.
- make_intermediate_result(name: str, explaination: str | None = None, ontology: Ontology | None = None, override_unit: Unit | None = None)#
Makes this value an intermediate result. This is used in the explain() method. For example, if you have the computation
A + B + Cthat isn’t easy to understand, you can decompose it with intermediate results by doing:AandB = A + B AandB.make_intermediate_result("AandB") result = AandB + C result.make_intermediate_result("result")This will print something like:
result is [some_value] Formula = AandB + C where - AandB is [other value] Formula = A + B where - A is [value] - B is [value] - C is [value]You can also add an explanation and an ontology to the results, and override its unit.
- Parameters:
name (str) – The name of the intermediate result that will be displayed by
explain().explanation (str | None, optional) – If not None, sets the
explanationattribute. Defaults to None.ontology (str | None, optional) – If not None, sets the
ontologyattribute. Defaults to None.override_unit (Unit | None, optional) – If not None, overrides the unit of the result by calling
set_unit(). Defaults to None.
- static set_correlation_mode(mode: CorrelationMode)#
Context manager to temporarily set the correlation mode used for arithmetic operations involving ReplicableValue instances. ReplicableValue instances represent random variables, where the value attribute is the expectation and the standard_deviation attribute quantifies uncertainty. When performing arithmetic operations on these values, the standard deviation of the result depends on the correlation between operands. In practice, determining the exact correlation between arbitrary values is often infeasible.
To address this, ImpactsHPC restricts correlation handling to two modes: - Independent (correlation = 0): Standard deviations are combined assuming no correlation. - Dependent (correlation = 1): Standard deviations are combined assuming full positive correlation.
This context manager allows you to specify which correlation mode should be used within a given block of code. For example, when subtracting a value from itself (e.g., C - C), the operands are fully correlated, and the standard deviation of the result should be zero. In contrast, when adding unrelated values (e.g., A + B), the operands are considered independent.
Example usage: .. code-block:: python
- with ReplicableValue.set_correlation_mode(CorrelationMode.DEPENDENT):
# Computations here assume full correlation (correlation = 1) result = C - C
# Outside the context, computations assume independence (correlation = 0) result2 = A + B
This approach simplifies the handling of correlations in complex systems, such as server impact computations, by allowing explicit control over correlation assumptions at the group or component level.
- Parameters:
mode (CorrelationMode) – The correlation mode to use within the context.
- set_unit(unit: Unit)#
Sets the unit of the value. ImpactsHPC uses the library Pint (https://pint.readthedocs.io/en/stable/) for handling units.
- Parameters:
unit (Unit) – The new unit. You should use a Unit from
impacthpc.src.core.config.ureg.- Raises:
ValueError – Raised if the value should be dimensionless to be set but is not.
- static sum(values: List[ReplicableValue]) ReplicableValue#
Computes the sum of a list of ReplicableValue using
__add__(), handling duplicates. Duplicates are removed:same_value + other_value + same_value + same_valuebecomesother_value + 3 * same_value.- Parameters:
values (List[ReplicableValue]) – The list to sum.
- Returns:
The sum of the ReplicableValue instances in
values.- Return type:
- class impactshpc.src.core.SourcedValue(name: str, value: Quantity | str, min: Quantity | str | None = None, max: Quantity | str | None = None, source: str = 'No source available', standard_deviation: Quantity | str | None = None, warnings: List[str] = [], explaination: str | None = None, ontology: Ontology | None = None, important: bool = False)#
Subclass of
ReplicableValuerepresenting a leaf of the tree, as opposed toOperation, which represents the composed nodes of a tree.In addition to the attributes of ReplicableValue, Operations have an operator and operands and can represent infix operations (like a + b, where the
+operator is between the two operands) or prefix operations (like ln(a), where the operator is a function name before the operands).- _as_formula() str#
Returns a string representing the formula this ReplicableValue represents.
For SourcedValue, returns the
SourcedValue.nameof the Sourcedvalue or a string representation of its value if name is None.
- _explain_rec(formatter: ~impactshpc.src.core.formatters.Formatter[~typing.Any, T] = <impactshpc.src.core.formatters.TextFormatter object>, recursion_level: int = 0, already_seen_values: set[int] = {}) T#
Provides an explanation of the current object using the specified formatter. Calls the
Formatter.format_sourced_value()offormatterand return its results.- Parameters:
- Returns:
the resutl returned by
Formatter.format_sourced_value()- Return type:
T
- static from_argument(name: str, argument: ReplicableValue | str | int | float | None) ReplicableValue | None#
Creates a
ReplicableValuefromargumentif it is not already one.If
argumentis aReplicableValue, it is returned as is. Otherwise, a newSourcedValueis created with the namename, the valueargument, and the source"Argument". Ifargumentis None, returns None.- Parameters:
name (str) – The name of the
SourcedValuecreated ifargumentis not aReplicableValue.argument (ReplicableValue | str | int | float) – If it’s a
ReplicableValue, it is returned as is. If it’s a string, aSourcedValueis created with this string as the value. If it is a number, it is converted into a string (with no unit) and aSourcedValueis created.
- Returns:
The resulting
ReplicableValue.- Return type:
- class impactshpc.src.core.TextFormatter(uncertainty_format: UncertaintyFormat = UncertaintyFormat.STANDARD_DEVIATION)#
- format_extracted_important_values(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None) str#
Format extracted values which are the
ReplicableValueinstances with theReplicable.importantboolean set to true. These values are extracted and can be used to format the final result informat_result().- Parameters:
name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
source (str) – The source (quote, link, etc.) of the value.
warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
- Returns:
Formatted extracted important source value.
- Return type:
T
- format_operation(formula: str, name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, operator: str, operands: list[str], isInfix: bool, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) str#
Format an
Operationinstance. This method must be implemented.- Parameters:
formula (str) – A string representing the formula that the
Operationrepresents, returned byOperation._as_formula().name (str | None) – Name of the SourcedValue, if any. It is unique.
value (Quantity) – The central value, with units.
min (Quantity) – Minimum plausible value.
max (Quantity) – Maximum plausible value.
standard_deviation (Quantity) – Standard deviation (uncertainty) of the value.
operator (str) – The operator of this operation.
operands (list[T]) – List of the operands used in this operation, already formatted.
isInfix (bool) – True if the operation is infix (i.e., it’s a binary operation and the operator is placed between the operands, like
A + B). False if the operation is prefix (i.e., the operation can have any number of parameters and is written as a function, likeln(a)).warnings (List[str]) – List of warnings or notes about the value.
explanation (str | None) – Optional explanation or description.
ontology (str | None) – Optional ontology tag for semantic annotation.
recursion_level (int) – Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().already_seen (bool) – Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.important (bool) – True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.
- Returns:
The formatted
Operation.- Return type:
T
- format_result(result: str, extracted_important_values: list[str])#
Format the final result. Does nothing by default, but can be overridden to process or modify the final result before
ReplicableValue.explain()returns it.For example,
TextFormatteroverridesformat_result()in order to add the extracted important values at the beginning of the explanation.JSONFormatteroverrideformat_result()to usejson.dumps()on the final dict returned byformat_operation()andformat_sourced_value()- Parameters:
result (T) – The formatted result of
ReplicableValue._explain_rec().extracted_important_values (list[T]) – The extracted important values. These can be used to add a quick recap of the important results at the beginning of the explanation.
- Returns:
By default, returns the
resultparameter as is. Can be overridden to modify the final result beforeReplicableValue.explain()returns it.- Return type:
T
- format_sourced_value(name: str | None, value: Quantity, min: Quantity, max: Quantity, standard_deviation: Quantity, source: str, explaination: str | None, warnings: List[str], ontology: Ontology | None, recursion_level: int, already_seen: bool, important: bool) str#
Format a
SourcedValueinstance. This method must be implemented.- value#
The central value, with units.
- Type:
Quantity
- min#
Minimum plausible value.
- Type:
Quantity
- max#
Maximum plausible value.
- Type:
Quantity
- standard_deviation#
Standard deviation (uncertainty) of the value.
- Type:
Quantity
- recursion_level#
Recursion level is the depth of this value in the tree represented by the
ReplicableValueon which we calledReplicableValue.explain().- Type:
- already_seen#
Whether the value has already been formatted in a previously traversed branch of the tree represented by the
ReplicableValueon which we calledReplicableValue.explain(). TheOperation._explain_rec()method uses Depth-First Search and respects the order of theOperation.operandslist.- Type:
- important#
True if the value is an important intermediate result. If true, it will be extracted and passed to
format_result()in the list of extracted important values.- Type:
- Returns:
The formatted
SourcedValue.- Return type:
T
- impactshpc.src.core.decrease_over_time_allocation(age: ReplicableValue | str) AllocationMethod#
First year of commissioning is 50% of the embodied impact, second year is 25%, third year is 12.5%, etc.
- impactshpc.src.core.energy_intensity_at_location(location: str) Impacts#
Get the energy intensity of the electrical mix in a specific location. If the location is not found, it returns the energy intensity for the EEE location.
- impactshpc.src.core.find_close_cpu_model_name(name: str, threshold: float = 90) FuzzymatchResult | None#
Fuzzymatch search for close CPU model names from a dataset using fuzzy matching on name, code name, and generation. This method can return zero (None),one (
FuzzymatchSingleResult) or several matches (FuzzymatchMultipleResult). Returns the exact name of the CPU, making it suitable to use withCPUclass.- Parameters:
- Returns:
FuzzymatchSingleResultif a single good match is found.FuzzymatchMultipleResultif multiple results are above the threshold.None if no suitable match is found.
- Return type:
FuzzymatchResult| None
- impactshpc.src.core.find_close_gpu_model_name(name: str, threshold: float = 80) FuzzymatchResult | None#
Fuzzymatch search for close GPU model names from a dataset using fuzzy matching on name and variant. This method can return zero (None),one (
FuzzymatchSingleResult) or several matches (FuzzymatchMultipleResult). Returns the exact name of the GPU, making it suitable to use withGPUclass.- Parameters:
- Returns:
FuzzymatchSingleResultif a single good match is found.FuzzymatchMultipleResultif multiple results are above the threshold.None if no suitable match is found.
- Return type:
FuzzymatchResult| None
- impactshpc.src.core.find_close_ram_manufacturer_name(name: str, threshold: float = 80) FuzzymatchResult | None#
Fuzzymatch search for close RAM manufacturer names from a dataset using fuzzy matching on name, variant and memory size. This method can return zero (None),one (
FuzzymatchSingleResult) or several matches (FuzzymatchMultipleResult). Returns the exact name of the RAM, making it suitable to use withRAMclass.- Parameters:
- Returns:
FuzzymatchSingleResultif a single good match is found.FuzzymatchMultipleResultif multiple results are above the threshold.None if no suitable match is found.
- Return type:
FuzzymatchResult| None
- impactshpc.src.core.find_close_ssd_manufacturer_name(name: str, threshold: float = 80) FuzzymatchResult | None#
Fuzzymatch search for close SSD manufacturer names from a dataset using fuzzy matching on name, variant and memory size. This method can return zero (None),one (
FuzzymatchSingleResult) or several matches (FuzzymatchMultipleResult). Returns the exact name of the SSD, making it suitable to use withSSDclass.- Parameters:
- Returns:
FuzzymatchSingleResultif a single good match is found.FuzzymatchMultipleResultif multiple results are above the threshold.None if no suitable match is found.
- Return type:
FuzzymatchResult| None
- impactshpc.src.core.naive_allocation(lifetime: ReplicableValue | str) AllocationMethod#
Naive allocation method consist of dividing the embodied impact of a component by its lifetime.
Functions#
|
Naive allocation method consist of dividing the embodied impact of a component by its lifetime. |
First year of commissioning is 50% of the embodied impact, second year is 25%, third year is 12.5%, etc. |
|
|
Fuzzymatch search for close CPU model names from a dataset using fuzzy matching on name, code name, and generation. |
|
Fuzzymatch search for close GPU model names from a dataset using fuzzy matching on name and variant. |
|
Fuzzymatch search for close RAM manufacturer names from a dataset using fuzzy matching on name, variant and memory size. |
|
Fuzzymatch search for close SSD manufacturer names from a dataset using fuzzy matching on name, variant and memory size. |
|
Get the energy intensity of the electrical mix in a specific location. |
Classes#
|
|
|
Abstract class Formatter defines a simple API for formatting the |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
ReplicableValue is a core class of ImpactsHPC for representing numerical values with associated uncertainties and provenance. |
|
Subclass of |
|
Subclass of |
|
Enumeration representing the correlation mode of a value. |