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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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
"""
Position-Aware Trajectory Model

Incorporates the finding that early flips hurt more than late flips.
Tests various position-weighted strategies.
"""

import json
import numpy as np
from pathlib import Path
from sklearn.model_selection import train_test_split
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import accuracy_score, roc_auc_score, brier_score_loss
from scipy.optimize import minimize
import warnings
warnings.filterwarnings('ignore')


def parse_trajectory(bitstring, n_meas, expect='0'):
    if len(bitstring) < n_meas + 1:
        return None

    final = bitstring[0]
    intermediate = bitstring[1:n_meas+1]

    n_flips = intermediate.count('1')
    flip_positions = [i for i, b in enumerate(intermediate) if b == '1']

    correct = 1 if final == expect else 0

    return {
        'n_flips': n_flips,
        'n_meas': n_meas,
        'flip_positions': flip_positions,
        'correct': correct,
        'intermediate': intermediate,
    }


def build_position_features(traj):
    """
    Build rich position-aware features.
    """
    n_flips = traj['n_flips']
    n_meas = traj['n_meas']
    positions = traj['flip_positions']

    features = {
        'n_flips': n_flips,
        'n_meas': n_meas,
        'flip_rate': n_flips / n_meas if n_meas > 0 else 0,
    }

    for i in range(16):
        features[f'pos_{i}'] = 1 if i in positions else 0

    if n_meas > 0:
        q1 = n_meas // 4
        q2 = n_meas // 2
        q3 = 3 * n_meas // 4

        features['flips_q1'] = sum(1 for p in positions if p < q1)
        features['flips_q2'] = sum(1 for p in positions if q1 <= p < q2)
        features['flips_q3'] = sum(1 for p in positions if q2 <= p < q3)
        features['flips_q4'] = sum(1 for p in positions if p >= q3)
    else:
        features['flips_q1'] = 0
        features['flips_q2'] = 0
        features['flips_q3'] = 0
        features['flips_q4'] = 0

    if positions:
        features['first_flip_pos'] = min(positions)
        features['last_flip_pos'] = max(positions)
        features['flip_span'] = max(positions) - min(positions)
        features['mean_flip_pos'] = np.mean(positions)
    else:
        features['first_flip_pos'] = n_meas
        features['last_flip_pos'] = -1
        features['flip_span'] = 0
        features['mean_flip_pos'] = n_meas / 2

    if n_meas > 0 and positions:
        features['weighted_flip_sum'] = sum((n_meas - p) / n_meas for p in positions)
    else:
        features['weighted_flip_sum'] = 0

    features['has_pos0_flip'] = 1 if 0 in positions else 0
    features['has_pos1_flip'] = 1 if 1 in positions else 0

    if n_flips >= 2 and len(positions) >= 2:
        sorted_pos = sorted(positions)
        gaps = [sorted_pos[i+1] - sorted_pos[i] for i in range(len(sorted_pos)-1)]
        features['mean_gap'] = np.mean(gaps)
        features['consecutive_flips'] = sum(1 for g in gaps if g == 1)
    else:
        features['mean_gap'] = 0
        features['consecutive_flips'] = 0

    return features


def load_data_with_positions():
    """Load data with rich position features."""
    samples = []

    results_dir = Path('D:/qiskit-zenodragging/results')

    traj_file = results_dir / 'trajectory_estimation' / 'trajectory_estimation.json'
    if traj_file.exists():
        with open(traj_file) as f:
            data = json.load(f)

        for circuit_name, circuit_data in data['data'].items():
            n_meas = circuit_data['n_meas']

            if 'freeze' in circuit_name or 'x_freeze' in circuit_name:
                expect = '0'
            elif 'drag' in circuit_name:
                expect = '1'
            else:
                expect = '0'

            for bs in circuit_data['bitstrings']:
                traj = parse_trajectory(bs, n_meas, expect)
                if traj:
                    features = build_position_features(traj)
                    features['circuit'] = circuit_name
                    features['correct'] = traj['correct']
                    features['flip_positions'] = traj['flip_positions']
                    samples.append(features)

    vqe_file = results_dir / 'vqe_trajectory_validation' / 'vqe_trajectory_validation.json'
    if vqe_file.exists():
        with open(vqe_file) as f:
            data = json.load(f)

        for result_name, result_data in data.get('results', {}).items():
            if 'bitstrings' not in result_data:
                continue
            if result_data.get('type') != 'zeno':
                continue

            n_meas = 8
            true_z = result_data.get('true_z', 0)
            expect = '0' if true_z >= 0 else '1'

            for bs in result_data['bitstrings']:
                traj = parse_trajectory(bs, n_meas, expect)
                if traj:
                    features = build_position_features(traj)
                    features['circuit'] = result_name
                    features['correct'] = traj['correct']
                    features['flip_positions'] = traj['flip_positions']
                    samples.append(features)

    return samples


def position_weighted_score(positions, n_meas, weights):
    """
    Compute position-weighted penalty score.
    weights[i] = penalty for flip at position i
    """
    if not positions:
        return 0
    return sum(weights[min(p, len(weights)-1)] for p in positions)


def evaluate_weighting_fn(samples, weight_fn):
    """Evaluate a weighting function on samples."""
    total_weight = 0
    weighted_correct = 0

    for s in samples:
        w = weight_fn(s)
        total_weight += w
        weighted_correct += w * s['correct']

    if total_weight == 0:
        return {'fidelity': 0, 'utilization': 0, 'effective_yield': 0}

    fidelity = weighted_correct / total_weight
    utilization = total_weight / len(samples)
    effective_yield = fidelity * utilization

    return {
        'fidelity': fidelity,
        'utilization': utilization,
        'effective_yield': effective_yield,
    }


def optimize_position_weights(train_samples, n_positions=8):
    """
    Learn optimal position weights via optimization.
    """
    def objective(params):
        decay = params[0]
        pos_weights = params[1:n_positions+1]

        def weight_fn(s):
            n_flips = s['n_flips']
            positions = s['flip_positions']
            n_meas = s['n_meas']

            if n_flips == 0:
                return 1.0

            base_weight = np.exp(-decay * n_flips)

            pos_penalty = 0
            for p in positions:
                if p < n_positions:
                    pos_penalty += pos_weights[p]
                else:
                    pos_penalty += pos_weights[-1]

            return base_weight * np.exp(-pos_penalty)

        result = evaluate_weighting_fn(train_samples, weight_fn)
        return -result['effective_yield']

    x0 = [0.5] + [0.1] * n_positions

    bounds = [(0.01, 2.0)] + [(0.0, 1.0)] * n_positions

    result = minimize(objective, x0, method='L-BFGS-B', bounds=bounds)

    return result.x


def main():
    print("=" * 70)
    print("POSITION-AWARE TRAJECTORY MODEL")
    print("=" * 70)

    print("\n[1/6] Loading data with position features...")
    samples = load_data_with_positions()
    print(f"  Samples: {len(samples)}")

    feature_cols = [k for k in samples[0].keys()
                    if k not in ['circuit', 'correct', 'flip_positions']]
    print(f"  Features: {len(feature_cols)}")

    print("\n[2/6] Train/test split...")
    train_samples, test_samples = train_test_split(
        samples, test_size=0.2, random_state=42,
        stratify=[s['correct'] for s in samples]
    )
    print(f"  Train: {len(train_samples)}, Test: {len(test_samples)}")

    print("\n[3/6] Analyzing position impact...")

    position_fidelity = {}
    for pos in range(16):
        with_flip = [s for s in samples if pos in s['flip_positions']]
        without_flip = [s for s in samples if pos not in s['flip_positions']]

        if with_flip and without_flip:
            fid_with = np.mean([s['correct'] for s in with_flip])
            fid_without = np.mean([s['correct'] for s in without_flip])
            impact = fid_without - fid_with
            position_fidelity[pos] = {
                'with_flip': fid_with,
                'without_flip': fid_without,
                'impact': impact,
                'n_with': len(with_flip),
            }

    print("\n  Position impact on fidelity:")
    print("  Pos | With Flip | Without | Impact | N")
    print("  " + "-" * 45)
    for pos in sorted(position_fidelity.keys()):
        pf = position_fidelity[pos]
        if pf['n_with'] > 100:
            print(f"   {pos:2d} |   {pf['with_flip']:5.1%}   |  {pf['without_flip']:5.1%}  | {pf['impact']:+5.1%} | {pf['n_with']}")

    print("\n[4/6] Optimizing position weights...")
    optimal_params = optimize_position_weights(train_samples, n_positions=8)
    optimal_decay = optimal_params[0]
    optimal_pos_weights = optimal_params[1:9]

    print(f"\n  Optimal decay: {optimal_decay:.3f}")
    print("  Optimal position weights:")
    for i, w in enumerate(optimal_pos_weights):
        print(f"    pos_{i}: {w:.3f}")

    print("\n[5/6] Training gradient boosting model...")

    X_train = np.array([[s[f] for f in feature_cols] for s in train_samples])
    y_train = np.array([s['correct'] for s in train_samples])
    X_test = np.array([[s[f] for f in feature_cols] for s in test_samples])
    y_test = np.array([s['correct'] for s in test_samples])

    model = GradientBoostingClassifier(n_estimators=200, max_depth=6, random_state=42)
    model.fit(X_train, y_train)

    y_proba = model.predict_proba(X_test)[:, 1]

    print(f"  Accuracy: {accuracy_score(y_test, (y_proba > 0.5).astype(int)):.3f}")
    print(f"  AUC: {roc_auc_score(y_test, y_proba):.3f}")

    print("\n[6/6] Comparing all strategies...")

    def hard_weight(s):
        return 1.0 if s['n_flips'] == 0 else 0.0

    def soft_k2_weight(s):
        return 1.0 if s['n_flips'] <= 2 else 0.0

    def exp_weight(s):
        return np.exp(-s['n_flips'])

    def optimal_position_weight(s):
        if s['n_flips'] == 0:
            return 1.0
        base = np.exp(-optimal_decay * s['n_flips'])
        pos_penalty = sum(optimal_pos_weights[min(p, 7)] for p in s['flip_positions'])
        return base * np.exp(-pos_penalty)

    def linear_position_weight(s):
        if s['n_flips'] == 0:
            return 1.0
        n_meas = s['n_meas']
        penalty = sum((n_meas - p) / n_meas for p in s['flip_positions'])
        return np.exp(-0.5 * penalty)

    def early_penalty_weight(s):
        if s['n_flips'] == 0:
            return 1.0
        early_flips = sum(1 for p in s['flip_positions'] if p < s['n_meas'] // 2)
        late_flips = s['n_flips'] - early_flips
        return np.exp(-1.5 * early_flips - 0.3 * late_flips)

    def threshold_position_weight(s):
        if s['n_flips'] == 0:
            return 1.0
        if s['n_flips'] > 3:
            return 0.0
        if 0 in s['flip_positions']:
            if s['n_flips'] > 1:
                return 0.0
            return 0.5
        if s['n_flips'] <= 2:
            return 1.0
        return 0.3

    for i, s in enumerate(test_samples):
        s['model_proba'] = y_proba[i]

    def model_weight(s):
        return s['model_proba']

    strategies = {
        'Hard (k=0)': hard_weight,
        'Soft (k<=2)': soft_k2_weight,
        'Exp(-n)': exp_weight,
        'Learned Position': optimal_position_weight,
        'Linear Position': linear_position_weight,
        'Early Penalty': early_penalty_weight,
        'Threshold+Position': threshold_position_weight,
        'GBM Model': model_weight,
    }

    print("\n" + "=" * 70)
    print("RESULTS")
    print("=" * 70)

    print("\n{:<20} | {:>10} | {:>10} | {:>12}".format(
        "Strategy", "Fidelity", "Util.", "Eff. Yield"))
    print("-" * 58)

    results = {}
    for name, weight_fn in strategies.items():
        r = evaluate_weighting_fn(test_samples, weight_fn)
        results[name] = r
        print("{:<20} | {:>9.1%} | {:>9.1%} | {:>11.1%}".format(
            name, r['fidelity'], r['utilization'], r['effective_yield']))

    best_name = max(results.keys(), key=lambda k: results[k]['effective_yield'])
    best_yield = results[best_name]['effective_yield']
    exp_yield = results['Exp(-n)']['effective_yield']

    print("\n" + "=" * 70)
    print("SUMMARY")
    print("=" * 70)

    print(f"\nBest strategy: {best_name}")
    print(f"  Effective yield: {best_yield:.1%}")

    improvement = (best_yield - exp_yield) / exp_yield * 100
    print(f"\nImprovement over Exp(-n): {improvement:+.1f}%")

    soft_yield = results['Soft (k<=2)']['effective_yield']
    improvement_soft = (best_yield - soft_yield) / soft_yield * 100
    print(f"Improvement over Soft (k<=2): {improvement_soft:+.1f}%")

    print("\n" + "-" * 70)
    print("KEY INSIGHT")
    print("-" * 70)
    print("""
Position 0 (first measurement) has outsized impact.
A flip at position 0 corrupts ALL subsequent evolution.
A flip at position N-1 only affects the final readout.

Optimal strategy: threshold + position awareness
- Accept k<=2 flips IF none at position 0
- Heavily penalize position 0 flips
- Lightly penalize late flips
""")

    output = {
        'dataset_size': len(samples),
        'position_impact': {str(k): v for k, v in position_fidelity.items()},
        'optimal_decay': float(optimal_decay),
        'optimal_position_weights': [float(w) for w in optimal_pos_weights],
        'results': {name: {k: float(v) for k, v in r.items()} for name, r in results.items()},
        'best_strategy': best_name,
        'improvement_over_exp': improvement,
    }

    out_file = Path('D:/kishka/data/position_aware_model_results.json')
    with open(out_file, 'w') as f:
        json.dump(output, f, indent=2)

    print(f"\nSaved: {out_file}")

    return output


if __name__ == "__main__":
    main()