基于Python的服装企业缝纫机运行序列模式通用识别方案问询
The core challenge here is moving from a hardcoded rule (count runs of 3+ 2's) to a flexible system that can adapt to any user-defined sequence pattern. A state machine approach works perfectly here—it lets you model any sequence of signal patterns (single values, runs of values, repeated sub-sequences) and count how many times the full pattern is matched in the signal sequence.
Step 1: Define Pattern Structure
First, we'll represent patterns as a list of elements, where each element describes a segment of the sequence. Each element can be one of three types:
- Single: Match a single specific signal value.
- Run: Match a consecutive sequence of the same value (with optional min/max length constraints).
- Repeat Sequence: Match a sub-sequence repeated a minimum number of times (with optional max repeats).
We'll use helper functions to make pattern definition cleaner, but you can also write the raw dictionaries if you prefer.
Step 2: Implement the Pattern Matching Function
This function uses a state machine to iterate through the signal sequence, tracking progress through the pattern. Each time the full pattern is matched, we increment the count and reset to look for the next occurrence (non-overlapping, which makes sense for distinct production items).
def run_pattern(value, min_length=1, max_length=None): """Helper to create a run pattern element""" elem = {'type': 'run', 'value': value, 'min_length': min_length} if max_length is not None: elem['max_length'] = max_length return elem def single_pattern(value): """Helper to create a single value pattern element""" return {'type': 'single', 'value': value} def repeat_sequence_pattern(sequence, min_repeats=1, max_repeats=None): """Helper to create a repeated sub-sequence pattern element""" elem = {'type': 'repeat_sequence', 'sequence': sequence, 'min_repeats': min_repeats} if max_repeats is not None: elem['max_repeats'] = max_repeats return elem def count_production_items(signals, pattern): """Count occurrences of the pattern in the signal sequence""" count = 0 current_pattern_idx = 0 pattern_length = len(pattern) signal_length = len(signals) i = 0 while i < signal_length: current_elem = pattern[current_pattern_idx] current_signal = signals[i] # Handle single value match if current_elem['type'] == 'single': if current_signal == current_elem['value']: current_pattern_idx += 1 i += 1 else: current_pattern_idx = 0 i += 1 # Handle run of same value elif current_elem['type'] == 'run': target_val = current_elem['value'] min_len = current_elem['min_length'] max_len = current_elem.get('max_length', float('inf')) run_len = 0 # Count consecutive target values while i < signal_length and signals[i] == target_val: run_len += 1 i += 1 if min_len <= run_len <= max_len: current_pattern_idx += 1 else: current_pattern_idx = 0 if run_len == 0: i += 1 # Handle repeated sub-sequence elif current_elem['type'] == 'repeat_sequence': sub_seq = current_elem['sequence'] sub_seq_len = len(sub_seq) min_repeats = current_elem['min_repeats'] max_repeats = current_elem.get('max_repeats', float('inf')) repeats = 0 while i + sub_seq_len <= signal_length: # Check if next segment matches the sub-sequence match = True for j in range(sub_seq_len): if signals[i + j] != sub_seq[j]: match = False break if match: repeats += 1 i += sub_seq_len else: break if min_repeats <= repeats <= max_repeats: current_pattern_idx += 1 else: current_pattern_idx = 0 if repeats == 0: i += 1 # Check if we've completed the full pattern if current_pattern_idx == pattern_length: count += 1 current_pattern_idx = 0 # Reset to look for next occurrence return count
Step 3: Use the Function with Your DataFrame
First, extract the signal sequence from your DataFrame (this is faster than using iterrows for large datasets):
# Assuming your DataFrame is named df with a 'Signal' column signals = df['Signal'].tolist()
Then define your pattern based on the production sequence you want to count. Here are examples matching the scenarios you described:
Example 1: Original Hardcoded Rule (Runs of 3+ 2's)
original_pattern = [run_pattern(2, min_length=3)] production_count = count_production_items(signals, original_pattern) print(f"Production count: {production_count}")
Example 2: Sequence like "2... 43" (Run of 2's followed by 4 then 3)
pattern_2_43 = [run_pattern(2), single_pattern(4), single_pattern(3)] production_count = count_production_items(signals, pattern_2_43)
Example 3: Sequence like "2... 4343" (Run of 2's followed by [4,3] repeated twice)
pattern_2_43_twice = [run_pattern(2), repeat_sequence_pattern([4,3], min_repeats=2)] production_count = count_production_items(signals, pattern_2_43_twice)
Example 4: Repeating Sequence like "222 43 222 43..."
# Each item is a run of 2's (>=3) followed by 4 then 3 repeating_item_pattern = [run_pattern(2, min_length=3), single_pattern(4), single_pattern(3)] production_count = count_production_items(signals, repeating_item_pattern)
Key Advantages
- Flexibility: Adapt to any sequence pattern by modifying the pattern list—no need to rewrite core logic.
- Efficiency: Processing a list of signals is much faster than iterating over DataFrame rows.
- Readability: Helper functions make pattern definitions intuitive and easy to adjust.
This approach covers all the sequence variations you mentioned and can be extended further (e.g., adding optional elements or overlapping matches) if needed for edge cases.
内容的提问来源于stack exchange,提问作者johnson

