Coverage for src/seqrule/generators/core.py: 20%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-27 10:39 -0600

1""" 

2Core sequence generation functions. 

3 

4This module provides the main functions for generating sequences, 

5including generate_sequences and generate_counter_examples. 

6""" 

7 

8import random 

9from typing import List 

10 

11from ..core import AbstractObject, FormalRule, Sequence 

12 

13 

14def generate_counter_examples( 

15 rule: FormalRule, 

16 domain: List[AbstractObject], 

17 max_length: int, 

18 max_attempts: int = 1000, 

19) -> List[Sequence]: 

20 """ 

21 Generate sequences that don't satisfy the rule. 

22 

23 Args: 

24 rule: The rule to generate counter-examples for 

25 domain: Domain of objects to choose from 

26 max_length: Maximum length of generated sequences 

27 max_attempts: Maximum number of generation attempts 

28 

29 Returns: 

30 List of sequences that don't satisfy the rule 

31 """ 

32 counter_examples = [] 

33 attempts = 0 

34 

35 while attempts < max_attempts and len(counter_examples) < 5: 

36 # Generate a random sequence 

37 length = random.randint(1, max_length) 

38 sequence = random.choices(domain, k=length) 

39 

40 # Check if it's a counter-example 

41 if not rule(sequence): 

42 counter_examples.append(sequence) 

43 

44 attempts += 1 

45 

46 return counter_examples 

47 

48 

49def generate_sequences(domain, max_length=10, filter_rule=None): 

50 """ 

51 Generate sequences from a domain of objects. 

52 

53 Args: 

54 domain: List of objects to generate sequences from 

55 max_length: Maximum length of generated sequences 

56 filter_rule: Optional rule to filter generated sequences 

57 

58 Returns: 

59 List of valid sequences 

60 """ 

61 sequences = [] 

62 

63 # Empty sequence is always included if no filter or it passes the filter 

64 if not filter_rule or filter_rule([]): 

65 sequences.append([]) 

66 

67 # Generate sequences of length 1..max_length 

68 for length in range(1, max_length + 1): 

69 # Generate all sequences of this length 

70 for _ in range(min(100, 10**length)): # Limit number of sequences per length 

71 # Generate a random sequence of this length 

72 sequence = random.choices(domain, k=length) 

73 

74 # Apply filter if provided 

75 if not filter_rule or filter_rule(sequence): 

76 sequences.append(sequence) 

77 

78 # Stop if we have enough sequences 

79 if len(sequences) >= 100: 

80 return sequences 

81 

82 return sequences