File size: 4,655 Bytes
024a02d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import os
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import itertools
import time

os.makedirs('images', exist_ok=True)

def draw_candle(ax, x, O, H, L, C):
    if C > O: color = 'green'
    elif C < O: color = 'red'
    else: color = 'black'
    
    # Draw wick
    ax.plot([x, x], [L, H], color=color, linewidth=2)
    
    # Draw body
    top = max(O, C)
    bottom = min(O, C)
    
    # Ensure Dojis (O == C) have a slight visual thickness
    height = max(top - bottom, 0.2) if top == bottom else (top - bottom)
    rect_y = bottom if top != bottom else bottom - 0.1
    
    rect = patches.Rectangle((x - 0.3, rect_y), 0.6, height, linewidth=1, edgecolor=color, facecolor=color)
    ax.add_patch(rect)

def normalize(tup):
    """

    Normalizes the raw integer sequence into pure structural ranks.

    E.g., (0, 7, 1, 6) and (2, 5, 3, 4) both normalize to (0, 3, 1, 2)

    """
    sorted_unique = sorted(list(set(tup)))
    mapping = {val: i for i, val in enumerate(sorted_unique)}
    return tuple(mapping[x] for x in tup)

def get_logic_string(p):
    """

    Converts a normalized tuple into a pure relational logic string.

    """
    labels = ['O1', 'H1', 'L1', 'C1', 'O2', 'H2', 'L2', 'C2']
    groups = {}
    
    for i, val in enumerate(p):
        if val not in groups:
            groups[val] = []
        groups[val].append(labels[i])
        
    logic_parts = []
    # Sort descending so the highest points are on the left
    for val in sorted(groups.keys(), reverse=True):
        logic_parts.append("(" + " = ".join(groups[val]) + ")")
        
    return " > ".join(logic_parts)

print("Calculating the universe of pure topological patterns...")
start_time = time.time()

valid_patterns = set()

# Since there are 8 points total, there can be at most 8 distinct levels.
# Iterating 0 to 7 covers all possible strict and equal relationships.
for p in itertools.product(range(8), repeat=8):
    O1, H1, L1, C1, O2, H2, L2, C2 = p
    
    # Intrinsic Rule: A candle's High must be the max, and Low must be the min
    if H1 != max(O1, H1, L1, C1) or L1 != min(O1, H1, L1, C1):
        continue
    if H2 != max(O2, H2, L2, C2) or L2 != min(O2, H2, L2, C2):
        continue
        
    valid_patterns.add(normalize(p))

patterns = sorted(list(valid_patterns))
total_patterns = len(patterns)
print(f"Found {total_patterns} mathematically unique 2-candle patterns in {time.time() - start_time:.2f} seconds.")

patterns_per_img = 10
markdown_lines = []
markdown_lines.append("# Exhaustive Pure Topological 2-Candle Patterns")
markdown_lines.append(f"**Total unique combinations:** {total_patterns}")
markdown_lines.append("")
markdown_lines.append("| Pattern ID | Mathematical Logic | Image Reference |")
markdown_lines.append("|---|---|---|")

print(f"Generating {(total_patterns // patterns_per_img) + 1} images... This might take a few minutes.")

for i in range(0, total_patterns, patterns_per_img):
    batch = patterns[i:i+patterns_per_img]
    
    fig, axes = plt.subplots(2, 5, figsize=(20, 8))
    fig.subplots_adjust(hspace=0.5, wspace=0.3)
    axes = axes.flatten()
    
    for ax in axes:
        ax.set_visible(False)
        
    for j, p in enumerate(batch):
        ax = axes[j]
        ax.set_visible(True)
        
        # Scale the ranks (0 to 7) by 5 for cleaner visualization on the Y-axis
        scale = 5.0
        O1, H1, L1, C1 = p[0]*scale, p[1]*scale, p[2]*scale, p[3]*scale
        O2, H2, L2, C2 = p[4]*scale, p[5]*scale, p[6]*scale, p[7]*scale
        
        draw_candle(ax, 1, O1, H1, L1, C1)
        draw_candle(ax, 2, O2, H2, L2, C2)
        
        # Fix axis limits so every image has identical scaling
        ax.set_ylim(-5, 40)
        ax.set_xlim(0, 3)
        ax.set_xticks([])
        ax.set_yticks([])
        
        pattern_id = f"P_{i+j:05d}"
        logic_str = get_logic_string(p)
        
        ax.set_title(f"{pattern_id}", fontsize=10)
        
        img_name = f"plot_{i//patterns_per_img + 1}.png"
        markdown_lines.append(f"| {pattern_id} | {logic_str} | {img_name} |")
        
    img_path = os.path.join('images', img_name)
    plt.savefig(img_path, bbox_inches='tight')
    plt.close(fig)

    # Basic progress tracker
    if (i // patterns_per_img) % 100 == 0 and i > 0:
        print(f"Processed {i} / {total_patterns} patterns...")

with open('2C_patterns.md', 'w') as f:
    f.write("\n".join(markdown_lines))

print(f"Success! Generated {total_patterns} patterns. Saved MD to 2C_patterns.md")