flamapy-z3 2.6.0.dev11__tar.gz → 2.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/PKG-INFO +5 -3
  2. flamapy_z3-2.9.0/flamapy/metamodels/z3_metamodel/__init__.py +36 -0
  3. flamapy_z3-2.9.0/flamapy/metamodels/z3_metamodel/operations/z3_backbone.py +53 -0
  4. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/transformations/fm_to_z3.py +137 -11
  5. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy_z3.egg-info/PKG-INFO +5 -3
  6. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy_z3.egg-info/SOURCES.txt +4 -0
  7. flamapy_z3-2.9.0/flamapy_z3.egg-info/entry_points.txt +2 -0
  8. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy_z3.egg-info/requires.txt +5 -2
  9. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/pyproject.toml +11 -3
  10. flamapy_z3-2.9.0/tests/test_cardinality_fallback.py +62 -0
  11. flamapy_z3-2.9.0/tests/test_conformance.py +79 -0
  12. flamapy_z3-2.9.0/tests/test_z3_backbone.py +57 -0
  13. flamapy_z3-2.9.0/tests/test_z3_metamodel.py +298 -0
  14. flamapy_z3-2.6.0.dev11/flamapy/metamodels/z3_metamodel/__init__.py +0 -0
  15. flamapy_z3-2.6.0.dev11/flamapy/metamodels/z3_metamodel/operations/z3_backbone.py +0 -70
  16. flamapy_z3-2.6.0.dev11/tests/test_z3_metamodel.py +0 -75
  17. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/README.md +0 -0
  18. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/models/__init__.py +0 -0
  19. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/models/z3_model.py +0 -0
  20. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/__init__.py +0 -0
  21. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/interfaces/__init__.py +0 -0
  22. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/interfaces/attribute_optimization.py +0 -0
  23. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_all_feature_bounds.py +0 -0
  24. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_attribute_optimization.py +0 -0
  25. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_configurations.py +0 -0
  26. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_configurations_number.py +0 -0
  27. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_core_features.py +0 -0
  28. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_dead_features.py +0 -0
  29. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_false_optional_features.py +0 -0
  30. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_feature_bounds.py +0 -0
  31. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_satisfiable.py +0 -0
  32. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_satisfiable_configuration.py +0 -0
  33. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/operations/z3_variable_bounds_complex.py +0 -0
  34. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy/metamodels/z3_metamodel/transformations/__init__.py +0 -0
  35. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy_z3.egg-info/dependency_links.txt +0 -0
  36. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/flamapy_z3.egg-info/top_level.txt +0 -0
  37. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/setup.cfg +0 -0
  38. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/setup.py +0 -0
  39. {flamapy_z3-2.6.0.dev11 → flamapy_z3-2.9.0}/tests/test_tseytin.py +0 -0
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flamapy-z3
3
- Version: 2.6.0.dev11
3
+ Version: 2.9.0
4
4
  Summary: z3-plugin for the automated analysis of feature models
5
5
  Author-email: Flamapy <flamapy@us.es>
6
6
  License-Expression: GPL-3.0-or-later
7
7
  Project-URL: Homepage, https://github.com/flamapy/z3_metamodel
8
8
  Requires-Python: >=3.11
9
9
  Description-Content-Type: text/markdown
10
- Requires-Dist: flamapy-fw~=2.6.0.dev11
11
- Requires-Dist: flamapy-fm~=2.6.0.dev11
10
+ Requires-Dist: flamapy-fw~=2.9.0
11
+ Requires-Dist: flamapy-fm~=2.9.0
12
12
  Requires-Dist: z3-solver~=4.14.1.0
13
13
  Provides-Extra: dev
14
14
  Requires-Dist: pytest; extra == "dev"
@@ -16,6 +16,8 @@ Requires-Dist: pytest-mock; extra == "dev"
16
16
  Requires-Dist: prospector; extra == "dev"
17
17
  Requires-Dist: mypy; extra == "dev"
18
18
  Requires-Dist: coverage; extra == "dev"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
19
21
 
20
22
  # flamapy-z3
21
23
 
@@ -0,0 +1,36 @@
1
+ from flamapy.core.manifest import OperationCapability, PluginManifest
2
+ from flamapy.core.models.language_level import LanguageLevel, MajorLevel, MinorLevel
3
+
4
+ # The SMT backend for typed/attributed feature models (TYPE major level). Costs are estimated
5
+ # milliseconds from the 2026-11-06 calibration (betty synthetic models at 1% and 30% constraint
6
+ # density, 20-10,000 features, plus JHipster and busybox; worst case, never decreasing): building
7
+ # the solver and the satisfiability/implication queries scale to 10,000 features, false-optional
8
+ # detection reaches 11 s there, and listing or counting configurations enumerates the models one
9
+ # by one (0.9 s already on the 20-feature calibration model).
10
+ _IMPLICATION_QUERIES = ((100, 1), (200, 3), (500, 9), (1000, 20), (5000, 41), (10000, 100))
11
+ _SAT_QUERY = ((200, 1), (500, 4), (1000, 6), (2000, 16), (10000, 40))
12
+
13
+ MANIFEST = PluginManifest(
14
+ name='z3',
15
+ calibration='2026-11-06',
16
+ extension='z3',
17
+ supported_level=LanguageLevel(MajorLevel.TYPE, {
18
+ MinorLevel.STRING_CONSTRAINTS, MinorLevel.AGGREGATE_FUNCTION,
19
+ MinorLevel.GROUP_CARDINALITY}),
20
+ transformation_cost_curve=((1000, 54), (2000, 88), (5000, 120), (10000, 250)),
21
+ operations={
22
+ 'satisfiable': OperationCapability(cost_curve=_SAT_QUERY),
23
+ 'satisfiable_configuration': OperationCapability(cost_curve=_SAT_QUERY),
24
+ 'core_features': OperationCapability(cost_curve=_IMPLICATION_QUERIES),
25
+ 'dead_features': OperationCapability(cost_curve=_IMPLICATION_QUERIES),
26
+ 'false_optional_features': OperationCapability(
27
+ cost_curve=((50, 2), (100, 3), (200, 8), (500, 29), (1000, 100), (2000, 420),
28
+ (5000, 2100), (10000, 11000))),
29
+ 'configurations_number': OperationCapability(max_features=30, cost=900),
30
+ 'configurations': OperationCapability(max_features=30, cost=900),
31
+ 'feature_bounds': OperationCapability(),
32
+ 'all_feature_bounds': OperationCapability(),
33
+ # Single- and multi-objective (Pareto) optimization over typed attributes.
34
+ 'attribute_optimization': OperationCapability(),
35
+ },
36
+ )
@@ -0,0 +1,53 @@
1
+ from typing import Any, cast
2
+
3
+ import z3
4
+
5
+ from flamapy.core.models import VariabilityModel
6
+ from flamapy.core.operations import Operation
7
+ from flamapy.metamodels.z3_metamodel.models import Z3Model
8
+
9
+
10
+ class Z3Backbone(Operation):
11
+
12
+ def __init__(self) -> None:
13
+ self._result: dict[str, list[Any]] = {"core": [], "dead": []}
14
+
15
+ def get_backbone(self) -> dict[str, list[Any]]:
16
+ return self.get_result()
17
+
18
+ def get_result(self) -> dict[str, list[Any]]:
19
+ return self._result
20
+
21
+ def execute(self, model: VariabilityModel) -> 'Z3Backbone':
22
+ z3_model = cast(Z3Model, model)
23
+ self._result = get_backbone(z3_model)
24
+ return self
25
+
26
+
27
+ def get_backbone(model: Z3Model) -> dict[str, list[Any]]:
28
+ """Core and dead features: the literals over the selection variables that the model implies.
29
+
30
+ `Solver.consequences` computes every implied literal among the given variables in one call,
31
+ inside the solver (models prune the candidates and unsatisfiable cores prove the rest), so no
32
+ per-feature check is needed. It also works on typed models, where the implications may
33
+ depend on the arithmetic and string constraints. An unsatisfiable model has no core
34
+ features and every feature dead, as in the SAT plugin.
35
+ """
36
+ solver = z3.Solver(ctx=model.ctx)
37
+ solver.add(model.constraints)
38
+ selections = [info.sel for info in model.features.values()]
39
+ names = {info.sel.get_id(): name for name, info in model.features.items()}
40
+ status, implied = solver.consequences([], selections)
41
+ if status != z3.sat:
42
+ return {"core": [], "dead": list(model.features.keys())}
43
+ core: list[Any] = []
44
+ dead: list[Any] = []
45
+ for consequence in implied: # each one is Implies(And(<assumptions>), literal)
46
+ literal = consequence.arg(1)
47
+ if z3.is_not(literal):
48
+ dead.append(names[literal.arg(0).get_id()])
49
+ else:
50
+ core.append(names[literal.get_id()])
51
+ order = {name: index for index, name in enumerate(model.features)}
52
+ return {"core": sorted(core, key=order.__getitem__),
53
+ "dead": sorted(dead, key=order.__getitem__)}
@@ -22,6 +22,7 @@ from flamapy.metamodels.fm_metamodel.models import (
22
22
  FeatureType,
23
23
  AttributeType
24
24
  )
25
+ from flamapy.metamodels.fm_metamodel.transformations.uvl_writer import UVL_OPERATORS
25
26
 
26
27
  from flamapy.metamodels.z3_metamodel.models import Z3Model, FeatureInfo
27
28
 
@@ -41,7 +42,9 @@ _BINARY_OPS: dict[ASTOperation, Any] = {
41
42
  ASTOperation.ADD: lambda lhs, rhs: (lhs + rhs),
42
43
  ASTOperation.SUB: lambda lhs, rhs: (lhs - rhs),
43
44
  ASTOperation.MUL: lambda lhs, rhs: (lhs * rhs),
44
- ASTOperation.DIV: lambda lhs, rhs: (lhs / rhs),
45
+ ASTOperation.DIV: lambda lhs, rhs: (
46
+ (z3.ToReal(lhs) if z3.is_int(lhs) else lhs)
47
+ / (z3.ToReal(rhs) if z3.is_int(rhs) else rhs)),
45
48
  ASTOperation.EQUALS: lambda lhs, rhs: (lhs == rhs),
46
49
  ASTOperation.LOWER: lambda lhs, rhs: (lhs < rhs),
47
50
  ASTOperation.GREATER: lambda lhs, rhs: (lhs > rhs),
@@ -51,6 +54,30 @@ _BINARY_OPS: dict[ASTOperation, Any] = {
51
54
  }
52
55
 
53
56
 
57
+ # Operators whose operands must be numbers; the comparisons also order two strings, and
58
+ # == and != compare any two operands of the same kind.
59
+ _NUMERIC_ONLY_OPS = (ASTOperation.ADD, ASTOperation.SUB, ASTOperation.MUL, ASTOperation.DIV)
60
+ _SAME_KIND_OPS = (ASTOperation.EQUALS, ASTOperation.NOT_EQUALS)
61
+
62
+
63
+ def _kind(expr: Any) -> str:
64
+ """The kind of value a Z3 expression holds, in the words of a UVL modeller."""
65
+ if z3.is_bool(expr) or isinstance(expr, bool):
66
+ return 'Boolean'
67
+ if z3.is_arith(expr) or isinstance(expr, (int, float)): # z3.Sum([]) is the int 0
68
+ return 'numeric'
69
+ if z3.is_string(expr):
70
+ return 'String'
71
+ return str(expr.sort())
72
+
73
+
74
+ def _describe(node: Node) -> str:
75
+ """How an operand is named in an error message."""
76
+ if node.is_term():
77
+ return f"'{node.data}'"
78
+ return f"the '{UVL_OPERATORS.get(node.data, node.data)}' expression"
79
+
80
+
54
81
  class FmToZ3(ModelToModel):
55
82
 
56
83
  @staticmethod
@@ -71,6 +98,10 @@ class FmToZ3(ModelToModel):
71
98
  # internally, so this exists for cross-backend uniformity/experimentation, not speed.
72
99
  self.cnf_method = cnf_method
73
100
  self._aux_counter: int = 0
101
+ # Conditions under which the constraint being translated is defined (e.g. an avg
102
+ # needs at least one selected feature declaring its attribute); see
103
+ # _add_constraint_formula.
104
+ self._definedness: list[Any] = []
74
105
 
75
106
  def transform(self) -> Z3Model:
76
107
  self.destination_model = Z3Model()
@@ -140,7 +171,9 @@ class FmToZ3(ModelToModel):
140
171
  self._add_alternative_formula(relation)
141
172
  elif relation.is_mutex():
142
173
  self._add_mutex_formula(relation)
143
- elif relation.is_cardinal():
174
+ else:
175
+ # Any other [min..max], including one-child groups such as [0..0] or [1..2] that
176
+ # Relation.is_cardinal() does not cover (it needs two children), as ClauseSet does.
144
177
  self._add_cardinality_formula(relation)
145
178
 
146
179
  def _add_mandatory_formula(self, relation: Relation) -> None:
@@ -234,8 +267,10 @@ class FmToZ3(ModelToModel):
234
267
  if val < card_min or val > card_max:
235
268
  for combination in itertools.combinations(children, val):
236
269
  literals = self._build_literals(children, combination)
270
+ # A group without children that still needs one cannot have its parent.
237
271
  self.destination_model.add_constraint(
238
- z3.Implies(parent, z3.Not(z3.And(*literals)))
272
+ z3.Implies(parent, z3.Not(z3.And(*literals))) if literals
273
+ else z3.Not(parent)
239
274
  )
240
275
 
241
276
  def _add_inactive_parent_constraints(self, parent: Any, children: list[Any]) -> None:
@@ -267,7 +302,11 @@ class FmToZ3(ModelToModel):
267
302
  if self.cnf_method == 'tseytin' and self._is_propositional_boolean(ctc):
268
303
  self._add_tseytin_constraint(ctc)
269
304
  return
305
+ self._definedness = []
270
306
  expr = self._get_expression(ctc.ast.root, None)
307
+ if self._definedness:
308
+ # An undefined term (the average of nothing) makes the whole constraint false.
309
+ expr = z3.And(expr, *self._definedness)
271
310
  self.destination_model.add_constraint(expr)
272
311
 
273
312
  def _is_propositional_boolean(self, ctc: Constraint) -> bool:
@@ -320,6 +359,7 @@ class FmToZ3(ModelToModel):
320
359
  if node.is_unary_op():
321
360
  left_expr = self._get_expression(node.left, node)
322
361
  if node.data == ASTOperation.NOT:
362
+ self._check_operand_kinds(node, [(node.left, left_expr)])
323
363
  return z3.Not(left_expr)
324
364
  raise FlamaException(f'Unsupported unary operator: {node.data}')
325
365
  if node.is_aggregate_op():
@@ -351,11 +391,19 @@ class FmToZ3(ModelToModel):
351
391
 
352
392
  def _get_str_term_expression(self, node: Node, parent: Node) -> z3.ExprRef:
353
393
  """Handle a terminal string node that has a parent operator."""
394
+ if node.is_literal():
395
+ # A quoted string literal is a constant, even when it contains '.', so resolve it
396
+ # before interpreting the text as a feature or a Feature.Attribute reference.
397
+ return z3.StringVal(str(node.data).strip("'\""), ctx=self.destination_model.ctx)
354
398
  variable = self.destination_model.get_variable(node.data)
355
399
  if variable is not None:
356
400
  return self._get_feature_term_expression(variable, parent)
357
401
  if '.' in node.data:
358
402
  return self._get_attribute_term_expression(node.data)
403
+ if node.is_feature() and parent.data not in (ASTOperation.SUM, ASTOperation.AVG):
404
+ # A reference that names nothing (e.g. a misspelled feature). Only sum/avg take a
405
+ # bare name that is not a feature: the attribute they aggregate.
406
+ raise FlamaException(f"'{node.data}' is not a feature of the model")
359
407
  return z3.StringVal(node.data.strip("'\""), ctx=self.destination_model.ctx)
360
408
 
361
409
  def _get_feature_term_expression(self,
@@ -365,6 +413,12 @@ class FmToZ3(ModelToModel):
365
413
  if parent.data in LOGICAL_OPERATORS:
366
414
  return variable.sel
367
415
  if parent.data in ARITHMETIC_OPERATORS:
416
+ if variable.val is None:
417
+ raise FlamaException(
418
+ f"Boolean feature '{variable.name}' cannot be used with "
419
+ f"'{UVL_OPERATORS.get(parent.data, parent.data)}': arithmetic and "
420
+ "comparison operators need a typed (Integer/Real/String) feature "
421
+ "or an attribute")
368
422
  return variable.val
369
423
  if parent.data in AGGREGATION_OPERATORS:
370
424
  return variable
@@ -396,8 +450,34 @@ class FmToZ3(ModelToModel):
396
450
  op_fn = _BINARY_OPS.get(node.data)
397
451
  if op_fn is None:
398
452
  raise FlamaException(f'Unsupported binary operator: {node.data}')
453
+ self._check_operand_kinds(node, [(node.left, left_expr), (node.right, right_expr)])
399
454
  return op_fn(left_expr, right_expr)
400
455
 
456
+ @staticmethod
457
+ def _check_operand_kinds(node: Node, operands: list[tuple[Node, Any]]) -> None:
458
+ """Reject operands an operator cannot take, which Z3 reports as a sort mismatch."""
459
+ symbol = UVL_OPERATORS.get(node.data, node.data)
460
+ kinds = [_kind(expr) for _, expr in operands]
461
+ if node.data in LOGICAL_OPERATORS:
462
+ needed = ['Boolean']
463
+ elif node.data in _NUMERIC_ONLY_OPS:
464
+ needed = ['numeric']
465
+ elif node.data in _SAME_KIND_OPS:
466
+ needed = ['Boolean', 'numeric', 'String']
467
+ else:
468
+ needed = ['numeric', 'String']
469
+ for (operand, _), kind in zip(operands, kinds):
470
+ if kind not in needed:
471
+ hint = ('; compare it with a value to get a condition'
472
+ if needed == ['Boolean'] else '')
473
+ raise FlamaException(
474
+ f"'{symbol}' needs {' or '.join(needed)} operands: "
475
+ f"{_describe(operand)} is {kind}{hint}")
476
+ if len(set(kinds)) > 1:
477
+ raise FlamaException(
478
+ f"'{symbol}' cannot combine {_describe(operands[0][0])} ({kinds[0]}) with "
479
+ f"{_describe(operands[1][0])} ({kinds[1]})")
480
+
401
481
  def _get_aggregate_op_expression(self, node: Node) -> z3.ExprRef:
402
482
  """Build a Z3 expression for an aggregation operator node."""
403
483
  left_expr = self._get_expression(node.left, node)
@@ -408,6 +488,23 @@ class FmToZ3(ModelToModel):
408
488
  return self._get_sum_avg_expression(node, left_expr, right_expr)
409
489
  if node.data == ASTOperation.LEN:
410
490
  return self._get_len_expression(left_expr)
491
+ if node.data in (ASTOperation.FLOOR, ASTOperation.CEIL):
492
+ name = UVL_OPERATORS.get(node.data, node.data)
493
+ if isinstance(left_expr, FeatureInfo):
494
+ # A feature reference under an aggregate arrives as its FeatureInfo.
495
+ if left_expr.ftype not in (FeatureType.INTEGER, FeatureType.REAL):
496
+ raise FlamaException(
497
+ f"{name} needs a numeric feature or attribute: "
498
+ f"'{left_expr.name}' is {left_expr.ftype.value}")
499
+ left_expr = left_expr.val
500
+ elif not z3.is_arith(left_expr):
501
+ raise FlamaException(
502
+ f"{name} needs a numeric feature or attribute: "
503
+ f"got {left_expr}")
504
+ operand = z3.ToReal(left_expr) if z3.is_int(left_expr) else left_expr
505
+ if node.data == ASTOperation.FLOOR:
506
+ return z3.ToReal(z3.ToInt(operand))
507
+ return z3.ToReal(-z3.ToInt(-operand))
411
508
  raise FlamaException(f'Unsupported aggregation operator: {node.data}')
412
509
 
413
510
  def _get_sum_avg_expression(self,
@@ -415,23 +512,47 @@ class FmToZ3(ModelToModel):
415
512
  left_expr: Any,
416
513
  right_expr: Optional[Any]) -> z3.ExprRef:
417
514
  """Build a Z3 expression for SUM or AVG aggregation."""
418
- attr_name = str(left_expr).strip("'\"")
515
+ if isinstance(left_expr, FeatureInfo):
516
+ attr_name = left_expr.name
517
+ else:
518
+ attr_name = str(left_expr).strip("'\"")
519
+ if self.source_model.get_attribute_by_name(attr_name) is None:
520
+ raise FlamaException(
521
+ f"'{attr_name}' is not a declared attribute: sum/avg take (attribute) or "
522
+ "(attribute, rootFeature); use '+' to add feature values")
419
523
  if right_expr is not None:
524
+ if not isinstance(right_expr, FeatureInfo):
525
+ root_name = str(right_expr).strip("'\"")
526
+ raise FlamaException(
527
+ f"'{root_name}' is not a feature: the second argument of sum/avg "
528
+ "must be the root feature of the subtree")
420
529
  feature = self.source_model.get_feature_by_name(right_expr.name)
421
530
  if feature is None:
422
531
  raise FlamaException(f'Unsupported feature: {right_expr.name}')
423
- attributes_vars = self._collect_attribute_vars(attr_name, feature)
424
532
  else:
425
- attributes_vars = self._collect_attribute_vars(attr_name, self.source_model.root)
533
+ feature = self.source_model.root
534
+ attributes_vars, selectors = self._collect_attribute_vars(attr_name, feature)
426
535
  if node.data == ASTOperation.SUM:
427
536
  return z3.Sum(attributes_vars)
428
537
  if not attributes_vars:
429
538
  raise FlamaException('Cannot compute average over empty set')
430
- return z3.Sum(attributes_vars) / len(attributes_vars)
431
-
432
- def _collect_attribute_vars(self, attr_name: str, root_feature: Feature) -> list[Any]:
433
- """Collect Z3 attribute variables from the subtree rooted at root_feature."""
539
+ # The average is taken over the *selected* features declaring the attribute, with
540
+ # real division. With none selected it is undefined, so the constraint is false.
541
+ ctx = self.destination_model.ctx
542
+ count = z3.Sum([z3.If(sel, z3.IntVal(1, ctx=ctx), z3.IntVal(0, ctx=ctx))
543
+ for sel in selectors])
544
+ self._definedness.append(count > 0)
545
+ total = z3.Sum(attributes_vars)
546
+ if z3.is_int(total):
547
+ total = z3.ToReal(total)
548
+ return total / z3.ToReal(count)
549
+
550
+ def _collect_attribute_vars(self, attr_name: str,
551
+ root_feature: Feature) -> tuple[list[Any], list[Any]]:
552
+ """Collect the Z3 attribute values (0 when the feature is not selected) declared in
553
+ the subtree rooted at root_feature, and the selectors of the declaring features."""
434
554
  attributes_vars = []
555
+ selectors = []
435
556
  for feat in get_subtree(root_feature):
436
557
  variable = self.destination_model.get_variable(feat.name)
437
558
  if variable is None:
@@ -444,7 +565,8 @@ class FmToZ3(ModelToModel):
444
565
  else:
445
566
  zero_val = z3.RealVal(0.0, ctx=self.destination_model.ctx)
446
567
  attributes_vars.append(z3.If(variable.sel, attr_info['var'], zero_val))
447
- return attributes_vars
568
+ selectors.append(variable.sel)
569
+ return attributes_vars, selectors
448
570
 
449
571
  def _get_len_expression(self, left_expr: Any) -> z3.ExprRef:
450
572
  """Build a Z3 expression for the LEN aggregation operator."""
@@ -452,6 +574,10 @@ class FmToZ3(ModelToModel):
452
574
  variable = self.destination_model.get_variable(left_expr.name)
453
575
  if variable is None:
454
576
  raise FlamaException(f'Unsupported feature: {left_expr.name}')
577
+ if variable.ftype != FeatureType.STRING:
578
+ raise FlamaException(
579
+ f"len needs a String feature or attribute: '{variable.name}' is "
580
+ f"{variable.ftype.value}")
455
581
  return z3.Length(variable.val)
456
582
  if '.' in str(left_expr):
457
583
  return self._get_len_attribute_expression(str(left_expr))
@@ -1,14 +1,14 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flamapy-z3
3
- Version: 2.6.0.dev11
3
+ Version: 2.9.0
4
4
  Summary: z3-plugin for the automated analysis of feature models
5
5
  Author-email: Flamapy <flamapy@us.es>
6
6
  License-Expression: GPL-3.0-or-later
7
7
  Project-URL: Homepage, https://github.com/flamapy/z3_metamodel
8
8
  Requires-Python: >=3.11
9
9
  Description-Content-Type: text/markdown
10
- Requires-Dist: flamapy-fw~=2.6.0.dev11
11
- Requires-Dist: flamapy-fm~=2.6.0.dev11
10
+ Requires-Dist: flamapy-fw~=2.9.0
11
+ Requires-Dist: flamapy-fm~=2.9.0
12
12
  Requires-Dist: z3-solver~=4.14.1.0
13
13
  Provides-Extra: dev
14
14
  Requires-Dist: pytest; extra == "dev"
@@ -16,6 +16,8 @@ Requires-Dist: pytest-mock; extra == "dev"
16
16
  Requires-Dist: prospector; extra == "dev"
17
17
  Requires-Dist: mypy; extra == "dev"
18
18
  Requires-Dist: coverage; extra == "dev"
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
19
21
 
20
22
  # flamapy-z3
21
23
 
@@ -24,7 +24,11 @@ flamapy/metamodels/z3_metamodel/transformations/fm_to_z3.py
24
24
  flamapy_z3.egg-info/PKG-INFO
25
25
  flamapy_z3.egg-info/SOURCES.txt
26
26
  flamapy_z3.egg-info/dependency_links.txt
27
+ flamapy_z3.egg-info/entry_points.txt
27
28
  flamapy_z3.egg-info/requires.txt
28
29
  flamapy_z3.egg-info/top_level.txt
30
+ tests/test_cardinality_fallback.py
31
+ tests/test_conformance.py
29
32
  tests/test_tseytin.py
33
+ tests/test_z3_backbone.py
30
34
  tests/test_z3_metamodel.py
@@ -0,0 +1,2 @@
1
+ [flamapy.plugins]
2
+ z3 = flamapy.metamodels.z3_metamodel
@@ -1,5 +1,5 @@
1
- flamapy-fw~=2.6.0.dev11
2
- flamapy-fm~=2.6.0.dev11
1
+ flamapy-fw~=2.9.0
2
+ flamapy-fm~=2.9.0
3
3
  z3-solver~=4.14.1.0
4
4
 
5
5
  [dev]
@@ -8,3 +8,6 @@ pytest-mock
8
8
  prospector
9
9
  mypy
10
10
  coverage
11
+
12
+ [test]
13
+ pytest
@@ -4,15 +4,15 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "flamapy-z3"
7
- version = "2.6.0.dev11"
7
+ version = "2.9.0"
8
8
  description = "z3-plugin for the automated analysis of feature models"
9
9
  readme = "README.md"
10
10
  license = "GPL-3.0-or-later"
11
11
  authors = [{ name = "Flamapy", email = "flamapy@us.es" }]
12
12
  requires-python = ">=3.11"
13
13
  dependencies = [
14
- "flamapy-fw~=2.6.0.dev11",
15
- "flamapy-fm~=2.6.0.dev11",
14
+ "flamapy-fw~=2.9.0",
15
+ "flamapy-fm~=2.9.0",
16
16
  "z3-solver~=4.14.1.0",
17
17
  ]
18
18
 
@@ -25,6 +25,14 @@ dev = [
25
25
  "coverage",
26
26
  ]
27
27
 
28
+ # The suite needs no sibling plugin beyond flamapy-fm.
29
+ test = [
30
+ "pytest",
31
+ ]
32
+
33
+ [project.entry-points."flamapy.plugins"]
34
+ z3 = "flamapy.metamodels.z3_metamodel"
35
+
28
36
  [project.urls]
29
37
  Homepage = "https://github.com/flamapy/z3_metamodel"
30
38
 
@@ -0,0 +1,62 @@
1
+ """Relations outside the standard shapes still need cardinality constraints."""
2
+
3
+ import pytest
4
+
5
+ from flamapy.metamodels.fm_metamodel.models import Feature, FeatureModel, Relation
6
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
7
+ from flamapy.metamodels.z3_metamodel.operations import (
8
+ Z3ConfigurationsNumber,
9
+ Z3DeadFeatures,
10
+ Z3Satisfiable,
11
+ )
12
+ from flamapy.metamodels.z3_metamodel.transformations import FmToZ3
13
+
14
+
15
+ def _model(card_min: int, card_max: int, children: int = 1,
16
+ optional_parent: bool = False) -> FeatureModel:
17
+ root = Feature("Root")
18
+ parent = root
19
+ if optional_parent:
20
+ parent = Feature("Parent", parent=root)
21
+ root.add_relation(Relation(root, [parent], 0, 1))
22
+ members = [Feature(f"F{i}", parent=parent) for i in range(children)]
23
+ parent.add_relation(Relation(parent, members, card_min, card_max))
24
+ return FeatureModel(root)
25
+
26
+
27
+ @pytest.mark.parametrize("card_min,card_max,children,expected", [
28
+ (0, 0, 1, 1), # Reported [0..0] case.
29
+ (0, 1, 1, 2), # Standard optional relation.
30
+ (1, 1, 1, 1), # Standard mandatory relation.
31
+ (1, 2, 1, 1), # Upper bound above child count.
32
+ (2, 2, 1, 0), # Impossible lower bound: the model is void.
33
+ (0, 3, 1, 2), # Extra upper range must not cause an error.
34
+ (0, -1, 1, 2), # Internal unbounded upper-bound sentinel.
35
+ (0, 0, 2, 1), # Ordinary two-child cardinality group.
36
+ (0, 0, 0, 1), # Empty, vacuous relation.
37
+ (1, 1, 0, 0), # Empty, impossible relation.
38
+ ])
39
+ def test_cardinality_counts(card_min, card_max, children, expected):
40
+ z3_model = FmToZ3(_model(card_min, card_max, children)).transform()
41
+ assert Z3ConfigurationsNumber().execute(z3_model).get_result() == expected
42
+ assert Z3Satisfiable().execute(z3_model).get_result() == (expected > 0)
43
+
44
+
45
+ @pytest.mark.parametrize("cardinality, expected", [
46
+ ("0..0", 1), # z3_metamodel#2: the child can never be selected
47
+ ("1..2", 1), # the child is required
48
+ ("2..2", 0), # impossible: the model is void
49
+ ("0..3", 2), # the child is optional
50
+ ])
51
+ def test_one_child_cardinality_groups_from_uvl(tmp_path, cardinality, expected):
52
+ path = tmp_path / "one_child.uvl"
53
+ path.write_text(f"features\n Root\n [{cardinality}]\n F0\n")
54
+ z3_model = FmToZ3(UVLReader(str(path)).transform()).transform()
55
+ assert Z3ConfigurationsNumber().execute(z3_model).get_result() == expected
56
+ assert Z3Satisfiable().execute(z3_model).get_result() == (expected > 0)
57
+
58
+
59
+ def test_unary_zero_group_under_optional_parent() -> None:
60
+ z3_model = FmToZ3(_model(0, 0, optional_parent=True)).transform()
61
+ assert Z3ConfigurationsNumber().execute(z3_model).get_result() == 2
62
+ assert Z3DeadFeatures().execute(z3_model).get_result() == ["F0"]
@@ -0,0 +1,79 @@
1
+ """UVL conformance regression suite.
2
+
3
+ Checks the Z3 backend's satisfiability result against an independently established answer for one
4
+ small, hand-verified model per UVL construct/level (Boolean, group cardinality, arithmetic,
5
+ aggregate, string, typed features). It is the *ground truth*: every case asserts the correct answer,
6
+ with no tolerance for the current open bugs — so until those are fixed this suite is RED on the
7
+ cases below, and goes green as each fix lands.
8
+
9
+ Expected values were computed with an independent reference oracle (enumeration + Z3) and checked by
10
+ hand. Models live in ``resources/models/conformance/``.
11
+ """
12
+ import os
13
+
14
+ import pytest
15
+
16
+ from flamapy.core.exceptions import FlamaException
17
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
18
+ from flamapy.metamodels.z3_metamodel.transformations import FmToZ3
19
+ from flamapy.metamodels.z3_metamodel.operations import Z3Satisfiable
20
+
21
+ MODELS = "resources/models/conformance"
22
+
23
+
24
+ def _satisfiable(name: str) -> bool:
25
+ z3_model = FmToZ3(UVLReader(os.path.join(MODELS, name)).transform()).transform()
26
+ return Z3Satisfiable().execute(z3_model).get_result()
27
+
28
+
29
+ # (model, expected_satisfiable). All values are the correct answer; the cases that currently fail
30
+ # correspond to open issues (noted inline) and will pass once those are fixed.
31
+ CASES = [
32
+ # Boolean
33
+ ("bool_or.uvl", True),
34
+ ("bool_alternative.uvl", True),
35
+ ("bool_requires.uvl", True),
36
+ ("bool_contradiction.uvl", False),
37
+ # group cardinality
38
+ ("group_card_1_2.uvl", True),
39
+ # arithmetic
40
+ ("arith_sum.uvl", True),
41
+ ("arith_div_exact.uvl", True),
42
+ ("div_real.uvl", True), # 12 / 8 == 1.5 — integer division would make this UNSAT (#3)
43
+ # aggregate: avg divides by the number of SELECTED bearers (#5), so the result is
44
+ # selection-sensitive, not the constant declaring-feature count.
45
+ ("agg_avg_clean.uvl", True),
46
+ ("agg_avg_selected_sat.uvl", True), # avg(X)==9 only when the optional bearer is selected
47
+ ("agg_avg_selected_unsat.uvl", False), # avg(X)==5 holds in no configuration
48
+ ("agg_avg_two_optionals.uvl", True), # avg(X)==6 only when both bearers are selected
49
+ # functions
50
+ ("floor_ceil.uvl", True), # floor()/ceil() must be supported (#4)
51
+ # string
52
+ ("string_equality.uvl", True),
53
+ ("string_dot_literal.uvl", True), # literal 'a.b' must be a constant, not a reference (#9)
54
+ # typed features
55
+ ("type_int_bounded.uvl", True),
56
+ ("type_int_unbounded.uvl", True),
57
+ ("type_string_free.uvl", True),
58
+ ]
59
+
60
+
61
+ @pytest.mark.parametrize("name, expected", CASES)
62
+ def test_conformance_satisfiable(name: str, expected: bool):
63
+ assert _satisfiable(name) == expected
64
+
65
+
66
+ # Ill-formed models: the reference oracle reports a model-error (a constraint over an attribute or a
67
+ # feature that does not exist). The backend must reject these with a FlamaException, not return a
68
+ # satisfiability result for a model it cannot faithfully encode.
69
+ INVALID = [
70
+ "invalid_avg_undeclared_attribute.uvl", # avg() over an attribute no feature declares
71
+ "invalid_dangling_feature_reference.uvl", # a constraint names a feature that does not exist
72
+ "invalid_dotted_unknown_feature.uvl", # Feature.Attribute whose feature does not exist
73
+ ]
74
+
75
+
76
+ @pytest.mark.parametrize("name", INVALID)
77
+ def test_conformance_invalid_is_rejected(name: str):
78
+ with pytest.raises(FlamaException):
79
+ _satisfiable(name)
@@ -0,0 +1,57 @@
1
+ """Backbone (core and dead features) through z3's consequences API, on Boolean and typed models.
2
+
3
+ The expected values were produced by the previous implementation (one check per candidate
4
+ literal) and cross-checked by hand on the small models.
5
+ """
6
+ import pytest
7
+
8
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
9
+ from flamapy.metamodels.z3_metamodel.transformations import FmToZ3
10
+ from flamapy.metamodels.z3_metamodel.operations import (
11
+ Z3Backbone,
12
+ Z3CoreFeatures,
13
+ Z3DeadFeatures,
14
+ )
15
+
16
+
17
+ MODELS = 'resources/models/uvl_models/'
18
+
19
+ ELECTRICITY_CORE = ['DATE', 'DAY', 'DAY_NAME', 'DEMAND', 'Electricity_price', 'INFORMATION_TYPE',
20
+ 'MONTH', 'Period', 'USEP', 'YEAR']
21
+
22
+
23
+ @pytest.mark.parametrize('path, core, dead', [
24
+ (MODELS + 'Electricity.uvl', ELECTRICITY_CORE, []),
25
+ (MODELS + 'Electricity_with_deadfeature.uvl', ELECTRICITY_CORE, ['ok']),
26
+ (MODELS + 'Electricity_with_no_deadfeature.uvl', [*ELECTRICITY_CORE, 'ok'], []),
27
+ (MODELS + 'Pizza_z3.uvl',
28
+ ['Dough', 'Normal', 'Pizza', 'Size', 'SpicyLvl', 'Topping'], ['Big', 'Name']),
29
+ (MODELS + 'fm03_integer_conditional_bounded.uvl', ['Container', 'Icecream', 'Scoops'], ['Stick']),
30
+ (MODELS + 'fm04_integer_dead_feature.uvl', ['Container', 'Icecream'], ['Scoops']),
31
+ (MODELS + 'fm13_feature_cardinality_bounded_refactored.uvl', ['R'], ['D']),
32
+ (MODELS + 'numerical_core_feature.uvl', ['Electricity_price', 'Period', 'ok'], []),
33
+ (MODELS + 'group_cardinalities.uvl', ['root'], []),
34
+ (MODELS + 'mutex.uvl', ['root'], []),
35
+ ])
36
+ def test_backbone(path: str, core: list, dead: list):
37
+ z3_model = FmToZ3(UVLReader(path).transform()).transform()
38
+ backbone = Z3Backbone().execute(z3_model).get_result()
39
+ assert sorted(backbone['core']) == sorted(core)
40
+ assert sorted(backbone['dead']) == sorted(dead)
41
+ assert Z3CoreFeatures().execute(z3_model).get_result() == backbone['core']
42
+ assert Z3DeadFeatures().execute(z3_model).get_result() == backbone['dead']
43
+
44
+
45
+ def test_backbone_follows_the_feature_order():
46
+ z3_model = FmToZ3(UVLReader(MODELS + 'Pizza_z3.uvl').transform()).transform()
47
+ order = list(z3_model.features)
48
+ backbone = Z3Backbone().execute(z3_model).get_result()
49
+ assert backbone['core'] == sorted(backbone['core'], key=order.index)
50
+ assert backbone['dead'] == sorted(backbone['dead'], key=order.index)
51
+
52
+
53
+ def test_void_model_has_no_core_and_every_feature_dead():
54
+ z3_model = FmToZ3(UVLReader(MODELS + 'Electricity_unsat.uvl').transform()).transform()
55
+ backbone = Z3Backbone().execute(z3_model).get_result()
56
+ assert backbone['core'] == []
57
+ assert backbone['dead'] == list(z3_model.features)
@@ -0,0 +1,298 @@
1
+ import pytest
2
+
3
+ from flamapy.core.exceptions import FlamaException
4
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
5
+ from flamapy.metamodels.z3_metamodel.models import Z3Model
6
+ from flamapy.metamodels.z3_metamodel.transformations import FmToZ3
7
+ from flamapy.metamodels.z3_metamodel.operations import (
8
+ Z3Satisfiable,
9
+ Z3ConfigurationsNumber,
10
+ Z3AttributeOptimization
11
+ )
12
+ from flamapy.metamodels.z3_metamodel.operations.interfaces import OptimizationGoal
13
+
14
+
15
+ PRECISION = 4
16
+
17
+
18
+ def _read_model(path: str) -> Z3Model:
19
+ z3_model = None # Initialize z3_model to None
20
+ if path.endswith('.uvl'):
21
+ feature_model = UVLReader(path).transform()
22
+ z3_model = FmToZ3(feature_model).transform()
23
+ else:
24
+ raise ValueError(f"Unsupported file extension for path: {path}")
25
+ return z3_model
26
+
27
+ @pytest.mark.parametrize("path, expected", [
28
+ ('resources/models/uvl_models/Electricity.uvl', True),
29
+ ('resources/models/uvl_models/fm01_integer_unbounded.uvl', True),
30
+ ('resources/models/uvl_models/fm02_integer_bounded.uvl', True),
31
+ ('resources/models/uvl_models/fm03_integer_conditional_bounded.uvl', True),
32
+ ('resources/models/uvl_models/fm04_integer_dead_feature.uvl', True),
33
+ ('resources/models/uvl_models/fm05_string_unbounded.uvl', True),
34
+ ('resources/models/uvl_models/fm06_string_bounded.uvl', True),
35
+ ('resources/models/uvl_models/fm07_string_conditional_bounded.uvl', True),
36
+ ('resources/models/uvl_models/fm08_real_unbounded.uvl', True),
37
+ ('resources/models/uvl_models/fm09_real_bounded.uvl', True),
38
+ ('resources/models/uvl_models/fm10_real_conditional_bounded.uvl', True),
39
+ ('resources/models/uvl_models/fm11_real_bounded_infinite.uvl', True),
40
+ ('resources/models/uvl_models/icecream_attributes.uvl', True),
41
+ ('resources/models/uvl_models/group_cardinalities.uvl', True),
42
+ # Division must be real (12 / 8 == 1.5); integer division would make this UNSAT.
43
+ ('resources/models/uvl_models/real_division.uvl', True),
44
+ # floor(10.5) == 10 and ceil(10.5) == 11 must be supported, not rejected.
45
+ ('resources/models/uvl_models/floor_ceil.uvl', True),
46
+ # A string literal containing '.' must be a constant, not parsed as Feature.Attribute.
47
+ ('resources/models/uvl_models/string_literal_with_dot.uvl', True)
48
+ ])
49
+ def test_z3_satisfiable(path: str, expected: bool):
50
+ z3_model = _read_model(path)
51
+ result = Z3Satisfiable().execute(z3_model).get_result()
52
+ assert result == expected
53
+
54
+ @pytest.mark.parametrize("path, expected", [
55
+ ('resources/models/uvl_models/fm02_integer_bounded.uvl', 9),
56
+ ('resources/models/uvl_models/fm03_integer_conditional_bounded.uvl', 4),
57
+ ('resources/models/uvl_models/fm04_integer_dead_feature.uvl', 3),
58
+ ('resources/models/uvl_models/fm06_string_bounded.uvl', 6),
59
+ ('resources/models/uvl_models/fm07_string_conditional_bounded.uvl', 5),
60
+ ('resources/models/uvl_models/fm09_real_bounded.uvl', 6),
61
+ ('resources/models/uvl_models/fm10_real_conditional_bounded.uvl', 3),
62
+ ('resources/models/uvl_models/icecream_attributes.uvl', 15),
63
+ ('resources/models/uvl_models/group_cardinalities.uvl', 16),
64
+ ('resources/models/uvl_models/mutex.uvl', 6)
65
+ ])
66
+ def test_nconfigs(path: str, expected: int):
67
+ z3_model = _read_model(path)
68
+ n_configs = Z3ConfigurationsNumber().execute(z3_model).get_result()
69
+ assert n_configs == expected
70
+
71
+ @pytest.mark.parametrize("path, expected", [
72
+ ('resources/models/uvl_models/icecream_attributes.uvl', 7)
73
+ ])
74
+ def test_pareto_front_nconfigs(path: str, expected: int):
75
+ z3_model = _read_model(path)
76
+ attribute_optimization_op = Z3AttributeOptimization()
77
+ attributes = {'Price': OptimizationGoal.MAXIMIZE,
78
+ 'Cost': OptimizationGoal.MINIMIZE}
79
+ attribute_optimization_op.set_attributes(attributes)
80
+ configs = attribute_optimization_op.execute(z3_model).get_result()
81
+ assert len(configs) == expected
82
+
83
+
84
+ _AGGREGATE_MODEL = ("features\n Root\n mandatory\n Integer f1\n"
85
+ " Integer f2\n A {Price 2}\n B\n"
86
+ "constraints\n {constraint}\n")
87
+
88
+
89
+ @pytest.mark.parametrize("constraint, message", [
90
+ # z3_metamodel#8: sum/avg take (attribute[, rootFeature]), not a list of feature values.
91
+ ("avg(f1, f2) == 1.0", "'f1' is not a declared attribute"),
92
+ ("sum(f1, f2) > 0", "'f1' is not a declared attribute"),
93
+ ("sum(Price, Nope) > 0", "'Nope' is not a feature"),
94
+ ])
95
+ def test_malformed_aggregate_is_rejected(tmp_path, constraint, message):
96
+ path = tmp_path / "aggregate.uvl"
97
+ path.write_text(_AGGREGATE_MODEL.replace("{constraint}", constraint))
98
+ with pytest.raises(FlamaException, match=message):
99
+ _read_model(str(path))
100
+
101
+
102
+ @pytest.mark.parametrize("constraint, expected", [
103
+ ("sum(Price, A) == 2", True),
104
+ ("avg(Price, A) == 2.0", True),
105
+ ("sum(Price) == 2", True),
106
+ # Price is declared in the model but by no feature under B: the sum is 0.
107
+ ("sum(Price, B) == 0", True),
108
+ ("sum(Price, B) > 0", False),
109
+ ])
110
+ def test_aggregate_over_attribute(tmp_path, constraint, expected):
111
+ path = tmp_path / "aggregate.uvl"
112
+ path.write_text(_AGGREGATE_MODEL.replace("{constraint}", constraint))
113
+ assert Z3Satisfiable().execute(_read_model(str(path))).get_result() == expected
114
+
115
+
116
+ _AVG_MODEL = """features
117
+ Root
118
+ optional
119
+ A {X 12}
120
+ B {X 6}
121
+ C
122
+ constraints
123
+ {constraint}
124
+ """
125
+
126
+
127
+ @pytest.mark.parametrize("constraint, expected", [
128
+ # z3_metamodel#5: avg divides by the *selected* features declaring the attribute.
129
+ ("avg(X) == 12", True), # {A}
130
+ ("avg(X) == 9", True), # {A, B}
131
+ ("avg(X) == 6", True), # {B} only: {A} would be 12 / 1, not 12 / 2
132
+ ("avg(X) == 6 & A", False),
133
+ ("avg(X) == 4", False),
134
+ # With no declaring feature selected the average is undefined: the constraint is false.
135
+ ("avg(X) == 0", False),
136
+ ("avg(X) == 12 & !A & !B", False),
137
+ ("!(avg(X) == 12) & !A & !B", False),
138
+ # Real division: (12 + 6) / 2 compared with a non-integer, and 12 / 1 with an integer.
139
+ ("avg(X) > 8.5 & avg(X) < 9.5", True),
140
+ ])
141
+ def test_avg_over_selected_features(tmp_path, constraint, expected):
142
+ path = tmp_path / "avg.uvl"
143
+ path.write_text(_AVG_MODEL.replace("{constraint}", constraint))
144
+ assert Z3Satisfiable().execute(_read_model(str(path))).get_result() == expected
145
+
146
+
147
+ def test_avg_integer_attributes_use_real_division(tmp_path):
148
+ path = tmp_path / "avg.uvl"
149
+ path.write_text("features\n Root\n mandatory\n A {X 1}\n"
150
+ " B {X 2}\nconstraints\n avg(X) == 1.5\n")
151
+ assert Z3Satisfiable().execute(_read_model(str(path))).get_result() is True
152
+
153
+
154
+ _TYPED_OPERAND_MODEL = """features
155
+ Root
156
+ optional
157
+ Scoop {Price 2}
158
+ B
159
+ Integer I
160
+ String S
161
+ constraints
162
+ {constraint}
163
+ """
164
+
165
+
166
+ @pytest.mark.parametrize("constraint, message", [
167
+ # A Boolean feature has no value: it used to reach Z3 as None ('parser error').
168
+ ("Scoop <= 3", "Boolean feature 'Scoop' cannot be used with '<='"),
169
+ ("Scoop + 1 > 0", "Boolean feature 'Scoop' cannot be used with '\\+'"),
170
+ ("I == Scoop", "Boolean feature 'Scoop' cannot be used with '=='"),
171
+ # None == None / None != None made these a silent tautology / contradiction.
172
+ ("Scoop == B", "Boolean feature 'Scoop' cannot be used with '=='"),
173
+ ("Scoop != B", "Boolean feature 'Scoop' cannot be used with '!='"),
174
+ ("len(Scoop) > 0", "len needs a String feature or attribute: 'Scoop' is Boolean"),
175
+ ("len(I) > 0", "len needs a String feature or attribute: 'I' is Integer"),
176
+ ])
177
+ def test_untyped_operand_is_rejected(tmp_path, constraint, message):
178
+ path = tmp_path / "operand.uvl"
179
+ path.write_text(_TYPED_OPERAND_MODEL.replace("{constraint}", constraint))
180
+ with pytest.raises(FlamaException, match=message):
181
+ _read_model(str(path))
182
+
183
+
184
+ @pytest.mark.parametrize("constraint, expected", [
185
+ ("Scoop <=> B", True),
186
+ ("Scoop => B & !B", True),
187
+ ("Scoop & !Scoop", False),
188
+ ("I > 1 & Scoop", True),
189
+ ("I + 1 <= 3 & I > 2", False),
190
+ ("Scoop.Price <= 3", True),
191
+ ("len(S) == 3", True),
192
+ ("S == 'abc'", True),
193
+ ])
194
+ def test_typed_operand_is_accepted(tmp_path, constraint, expected):
195
+ path = tmp_path / "operand.uvl"
196
+ path.write_text(_TYPED_OPERAND_MODEL.replace("{constraint}", constraint))
197
+ assert Z3Satisfiable().execute(_read_model(str(path))).get_result() == expected
198
+
199
+
200
+ _FLOOR_CEIL_MODEL = """features
201
+ Root
202
+ mandatory
203
+ Integer I
204
+ Real R
205
+ String S
206
+ B {Price 10.5, Name 'x'}
207
+ constraints
208
+ {constraint}
209
+ """
210
+
211
+
212
+ @pytest.mark.parametrize("constraint, expected", [
213
+ # floor/ceil of a typed feature (not only of an attribute).
214
+ ("R == 2.5 & floor(R) == 2 & ceil(R) == 3", True),
215
+ ("R == 2.5 & floor(R) == 3", False),
216
+ ("R == -2.5 & floor(R) == -3 & ceil(R) == -2", True),
217
+ ("I == 7 & floor(I) == 7 & ceil(I) == 7", True),
218
+ ("floor(B.Price) == 10 & ceil(B.Price) == 11", True),
219
+ ])
220
+ def test_floor_ceil(tmp_path, constraint, expected):
221
+ path = tmp_path / "floor_ceil.uvl"
222
+ path.write_text(_FLOOR_CEIL_MODEL.replace("{constraint}", constraint))
223
+ assert Z3Satisfiable().execute(_read_model(str(path))).get_result() == expected
224
+
225
+
226
+ @pytest.mark.parametrize("constraint, message", [
227
+ ("floor(B) == 1", "floor needs a numeric feature or attribute: 'B' is"),
228
+ ("ceil(S) == 1", "ceil needs a numeric feature or attribute: 'S' is"),
229
+ ("floor(B.Name) == 1", "floor needs a numeric feature or attribute"),
230
+ ])
231
+ def test_floor_ceil_non_numeric_is_rejected(tmp_path, constraint, message):
232
+ path = tmp_path / "floor_ceil.uvl"
233
+ path.write_text(_FLOOR_CEIL_MODEL.replace("{constraint}", constraint))
234
+ with pytest.raises(FlamaException, match=message):
235
+ _read_model(str(path))
236
+
237
+
238
+ _KINDS_MODEL = """features
239
+ Root
240
+ optional
241
+ A {Price 2, Name 'x', Flag true}
242
+ B {Flag false}
243
+ Integer I
244
+ Real R
245
+ String S
246
+ constraints
247
+ {constraint}
248
+ """
249
+
250
+
251
+ @pytest.mark.parametrize("constraint, message", [
252
+ # A reference that names nothing used to become a string constant.
253
+ ("Scop <= 3", "'Scop' is not a feature of the model"),
254
+ ("A & Scop", "'Scop' is not a feature of the model"),
255
+ ("len(Scop) > 0", "'Scop' is not a feature of the model"),
256
+ # A String mixed with numbers.
257
+ ("S + 1 > 0", "'\\+' needs numeric operands: 'S' is String"),
258
+ ("S > 1", "'>' cannot combine 'S' \\(String\\) with '1' \\(numeric\\)"),
259
+ ("I == 'abc'", "'==' cannot combine 'I' \\(numeric\\) with 'abc' \\(String\\)"),
260
+ ("A.Name * 2 > 1", "'\\*' needs numeric operands: 'A.Name' is String"),
261
+ ("S - S == S", "'-' needs numeric operands: 'S' is String"),
262
+ # A value where a condition is expected.
263
+ ("A.Price & B", "'&' needs Boolean operands: 'A.Price' is numeric; compare it"),
264
+ ("B => A.Name", "'=>' needs Boolean operands: 'A.Name' is String"),
265
+ ("!A.Price", "'!' needs Boolean operands: 'A.Price' is numeric"),
266
+ ("I + 1 == 'abc'",
267
+ "'==' cannot combine the '\\+' expression \\(numeric\\) with 'abc' \\(String\\)"),
268
+ # A condition where a value is expected.
269
+ ("A.Flag + 1 > 0", "'\\+' needs numeric operands: 'A.Flag' is Boolean"),
270
+ ("A.Flag < 1", "'<' needs numeric or String operands: 'A.Flag' is Boolean"),
271
+ ("A.Flag == 1", "'==' cannot combine 'A.Flag' \\(Boolean\\) with '1' \\(numeric\\)"),
272
+ ])
273
+ def test_ill_typed_constraint_is_rejected(tmp_path, constraint, message):
274
+ path = tmp_path / "kinds.uvl"
275
+ path.write_text(_KINDS_MODEL.replace("{constraint}", constraint))
276
+ with pytest.raises(FlamaException, match=message):
277
+ _read_model(str(path))
278
+
279
+
280
+ @pytest.mark.parametrize("constraint, expected", [
281
+ ("I + R > 1.5 & I * 2 - 1 == 3", True), # Integer and Real mix freely
282
+ ("I / 2 == 1.5", True),
283
+ ("S == 'abc' & S != 'abd'", True),
284
+ ("S < 'b' & S > 'a'", True), # strings are ordered
285
+ ("A.Name == 'x' & A", True),
286
+ ("A.Name == 'y' & A", False),
287
+ ("A.Flag == B.Flag & A & B", False), # two Boolean attributes compare
288
+ ("A.Flag != B.Flag & A & B", True),
289
+ ("A.Flag & A", True), # and a Boolean attribute is a condition
290
+ ("B.Flag & B", False),
291
+ ("A.Price > 1 & !(I > 3) & (A => S == 'abc')", True),
292
+ ("sum(Price) == 2 & avg(Price) == 2", True),
293
+ ("len(S) == 3 & len(A.Name) == 1 & A", True),
294
+ ])
295
+ def test_well_typed_constraint_is_accepted(tmp_path, constraint, expected):
296
+ path = tmp_path / "kinds.uvl"
297
+ path.write_text(_KINDS_MODEL.replace("{constraint}", constraint))
298
+ assert Z3Satisfiable().execute(_read_model(str(path))).get_result() == expected
@@ -1,70 +0,0 @@
1
- from typing import Any, cast
2
-
3
- import z3
4
-
5
- from flamapy.core.models import VariabilityModel
6
- from flamapy.core.operations import Operation
7
- from flamapy.metamodels.z3_metamodel.models import Z3Model
8
-
9
-
10
- class Z3Backbone(Operation):
11
-
12
- def __init__(self) -> None:
13
- self._result: dict[str, list[Any]] = {"core": [], "dead": []}
14
-
15
- def get_backbone(self) -> dict[str, list[Any]]:
16
- return self.get_result()
17
-
18
- def get_result(self) -> dict[str, list[Any]]:
19
- return self._result
20
-
21
- def execute(self, model: VariabilityModel) -> 'Z3Backbone':
22
- z3_model = cast(Z3Model, model)
23
- self._result = get_backbone(z3_model)
24
- return self
25
-
26
-
27
- def get_backbone(model: Z3Model) -> dict[str, list[Any]]:
28
- solver = z3.Solver(ctx=model.ctx)
29
- solver.add(model.constraints)
30
-
31
- vars_to_features = {f_info.sel: name for name, f_info in model.features.items()}
32
-
33
- # (out, C) <- SAT(phi)
34
- if solver.check() != z3.sat:
35
- return {"core": [], "dead": list(model.features.keys())}
36
-
37
- m = solver.model()
38
- # C <- filter(C)
39
- core_candidates = {var for var in vars_to_features.keys() if z3.is_true(m[var])}
40
- dead_candidates = {var for var in vars_to_features.keys() if z3.is_false(m[var])}
41
-
42
- backbone_core = []
43
- backbone_dead = []
44
-
45
- while core_candidates or dead_candidates:
46
- if core_candidates:
47
- literal = next(iter(core_candidates))
48
- check_lit = z3.Not(literal)
49
- is_core = True
50
- else:
51
- literal = next(iter(dead_candidates))
52
- check_lit = literal
53
- is_core = False
54
-
55
- # (out, S) <- SAT(phi U {not l})
56
- if solver.check([check_lit]) == z3.unsat:
57
- if is_core:
58
- backbone_core.append(vars_to_features[literal])
59
- solver.add(literal)
60
- core_candidates.remove(literal)
61
- else:
62
- backbone_dead.append(vars_to_features[literal])
63
- solver.add(z3.Not(literal))
64
- dead_candidates.remove(literal)
65
- else:
66
- new_model = solver.model()
67
- core_candidates = {var for var in core_candidates if z3.is_true(new_model[var])}
68
- dead_candidates = {var for var in dead_candidates if z3.is_false(new_model[var])}
69
-
70
- return {"core": backbone_core, "dead": backbone_dead}
@@ -1,75 +0,0 @@
1
- import pytest
2
-
3
- from flamapy.metamodels.fm_metamodel.transformations import UVLReader
4
- from flamapy.metamodels.z3_metamodel.models import Z3Model
5
- from flamapy.metamodels.z3_metamodel.transformations import FmToZ3
6
- from flamapy.metamodels.z3_metamodel.operations import (
7
- Z3Satisfiable,
8
- Z3ConfigurationsNumber,
9
- Z3AttributeOptimization
10
- )
11
- from flamapy.metamodels.z3_metamodel.operations.interfaces import OptimizationGoal
12
-
13
-
14
- PRECISION = 4
15
-
16
-
17
- def _read_model(path: str) -> Z3Model:
18
- z3_model = None # Initialize z3_model to None
19
- if path.endswith('.uvl'):
20
- feature_model = UVLReader(path).transform()
21
- z3_model = FmToZ3(feature_model).transform()
22
- else:
23
- raise ValueError(f"Unsupported file extension for path: {path}")
24
- return z3_model
25
-
26
- @pytest.mark.parametrize("path, expected", [
27
- ('resources/models/uvl_models/Electricity.uvl', True),
28
- ('resources/models/uvl_models/fm01_integer_unbounded.uvl', True),
29
- ('resources/models/uvl_models/fm02_integer_bounded.uvl', True),
30
- ('resources/models/uvl_models/fm03_integer_conditional_bounded.uvl', True),
31
- ('resources/models/uvl_models/fm04_integer_dead_feature.uvl', True),
32
- ('resources/models/uvl_models/fm05_string_unbounded.uvl', True),
33
- ('resources/models/uvl_models/fm06_string_bounded.uvl', True),
34
- ('resources/models/uvl_models/fm07_string_conditional_bounded.uvl', True),
35
- ('resources/models/uvl_models/fm08_real_unbounded.uvl', True),
36
- ('resources/models/uvl_models/fm09_real_bounded.uvl', True),
37
- ('resources/models/uvl_models/fm10_real_conditional_bounded.uvl', True),
38
- ('resources/models/uvl_models/fm11_real_bounded_infinite.uvl', True),
39
- ('resources/models/uvl_models/icecream_attributes.uvl', True),
40
- ('resources/models/uvl_models/group_cardinalities.uvl', True)
41
- ])
42
- def test_z3_satisfiable(path: str, expected: bool):
43
- z3_model = _read_model(path)
44
- result = Z3Satisfiable().execute(z3_model).get_result()
45
- assert result == expected
46
-
47
- @pytest.mark.parametrize("path, expected", [
48
- ('resources/models/uvl_models/fm02_integer_bounded.uvl', 9),
49
- ('resources/models/uvl_models/fm03_integer_conditional_bounded.uvl', 4),
50
- ('resources/models/uvl_models/fm04_integer_dead_feature.uvl', 3),
51
- ('resources/models/uvl_models/fm06_string_bounded.uvl', 6),
52
- ('resources/models/uvl_models/fm07_string_conditional_bounded.uvl', 5),
53
- ('resources/models/uvl_models/fm09_real_bounded.uvl', 6),
54
- ('resources/models/uvl_models/fm10_real_conditional_bounded.uvl', 3),
55
- ('resources/models/uvl_models/icecream_attributes.uvl', 15),
56
- ('resources/models/uvl_models/group_cardinalities.uvl', 16),
57
- ('resources/models/uvl_models/mutex.uvl', 6)
58
- ])
59
- def test_nconfigs(path: str, expected: int):
60
- z3_model = _read_model(path)
61
- n_configs = Z3ConfigurationsNumber().execute(z3_model).get_result()
62
- assert n_configs == expected
63
-
64
- @pytest.mark.parametrize("path, expected", [
65
- ('resources/models/uvl_models/icecream_attributes.uvl', 7)
66
- ])
67
- def test_pareto_front_nconfigs(path: str, expected: int):
68
- z3_model = _read_model(path)
69
- attribute_optimization_op = Z3AttributeOptimization()
70
- attributes = {'Price': OptimizationGoal.MAXIMIZE,
71
- 'Cost': OptimizationGoal.MINIMIZE}
72
- attribute_optimization_op.set_attributes(attributes)
73
- configs = attribute_optimization_op.execute(z3_model).get_result()
74
- assert len(configs) == expected
75
-
File without changes
File without changes
File without changes