吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2619|回复: 36
收起左侧

[原创工具] 3-11更新了朱丽叶集和再次增加速度 py写的曼德博集图片生成器,附源码

[复制链接]
858983646 发表于 2025-2-26 21:46
本帖最后由 858983646 于 2025-3-11 21:01 编辑

py写的曼德博集图片生成器,写着玩的,主要用开学习,可以输出图片,收集了一帧帧可以手动合成视频
注意事项:浮点数计算时速度挺快的,放大到超出浮点数了(超过切换阈值会切换过去)就超级慢超级慢,技术有限无能为力,有没有大佬能帮忙解决


03-04更新了一下,1.高精度计算部分用c语言写了,测试了下速度快了6倍
3-11更新了下朱丽叶集的图片生成,高精度计算部分平滑区域采样后跳过计算,速度又快了40%,现在1080p的大概40秒(i5-12490f)
1.PNG
2.修复了精度问题,现在理论上应该可以无限精度了。实测800*600,10^50放大是97秒,慢还是挺慢的
Screenshot_2025-03-04-23-03-41-024_com.miui.gallery-edit.jpg Screenshot_2025-03-04-23-03-32-903_com.miui.gallery-edit.jpg Screenshot_2025-03-04-23-03-21-473_com.miui.gallery-edit.jpg

这个软件功能被Ultra Fractal等专业软件吊打,想玩可以下个去试试

参数说明:
1.分辨率就是图片输出分辨率,不是窗口显示的,显示的是缩放的
2.曼德博集方程 Zₐ₊₁ = Zₐ² + c,xy是复数c的实部和虚部,就是图片生成时的复平面坐标,下面6个按钮就预先设置的xy坐标
3.宽度数值就是图片复平面从左到右的轴长度数值,越小图片放大越大
4.最大迭代次数就是Zₐ₊₁ = Zₐ² + c,里的a,若a次迭代,Zₐ₊₁ 不超过2就认为属于曼德博集,不到a次就超过2就是不属于曼德博集,根据超过2时的次数来映射颜色。注意不是越大越好,数值会影响图像输出,自己调节
5.生成数量就是一次生成的图片张数,多次生成图片会后续继续编号,不覆盖之前图片
6.放大系数就是第二张图片比第一张放大的倍数,可以小于1来缩小,必须大于0
7.焦点位置坐标xy 这个就是焦点数值xy坐标所在图片中的位置,0,0是左下角,1,1是右上角
8.切换cpu的精度阈值  可以不改,这个就是数值越来越小,小了由于普通浮点数精度计算有限,会越来越糊,甚至算不出。计算数值太小,小数点后0位数大于这个位数就切gmpy2高精度计算,但是超级超级慢,算出来前会卡死,可以提前改个很高的避免切过去,这个问题没能力解决,不建议使用
9.颜色隐射 切换颜色模式,就是变色
10.保存路径和开始没啥好说的
11.右边图片点击可以改放大中心,拖动可以变这个中心的位置(就是把图片拖过来再放大)
12.图片上当前精度超出8那里的阈值,就切换高精度计算,就是gmpy2计算模式,其他像OpenCL等模式很快的
13.图片上的计算时间只是图片算出来的时间,其他显示保存图片啥的步骤没算进去
链接:https://pan.baidu.com/s/1fm6a9Z7BWYWwk4hDEpxjyg?pwd=813j
提取码:813j

5.PNG 4.PNG 3.PNG 2.PNG 1.PNG
[C] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
#include <windows.h>
#include <math.h>
#include <gmp.h>
#include <mpfr.h>
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>  // 添加时间头文件
 
// 定义比较函数
int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);  // 升序排序
}
 
// 定义 ThreadParams 结构体
typedef struct {
    int startRow;
    int endRow;
    BYTE* pBits;
    mpfr_t* mpfrVars;
    int iXmax;
    int iYmax;
    int IterationMax;
} ThreadParams;
 
int min_iter = 0;  // 最小迭代次数
double percentile = 0.98;  // 默认值为 0.98
 
// 默认参数
int NUM_THREADS = 4;  // 线程数量
int precision = 256;  // GMP/MPFR 精度(位数)
char* center_x = "-0.74515135254171761267617"// 中心点 x 坐标
char* center_y = "0.13019734207256549877521"// 中心点 y 坐标
char* width = "600";   // 图片宽度
char* height = "400"// 图片高度
char* scale = "1.25829116006878627409549e-15";     // 当前缩放比例
char* focus_x = "0.53665115566"; // 焦点 x 坐标
char* focus_y = "0.532158525855555"; // 焦点 y 坐标
char* max_iter = "800"; // 最大迭代次数
char* zhuliyax = "0.0"; // 新增参数
char* zhuliyay = "0.0"; // 新增参数
char* zhuliya = "0";    // 新增参数
const double EscapeRadius = 2;  // 逃逸半径
 
int* iterationArray;  // 全局变量,迭代次数数组
 
// 迭代写入二进制文件
void SaveIterationArrayAsBinary(const char* filename, int width, int height) {
    FILE* file = fopen(filename, "wb");
    if (!file) {
        printf("Failed to open file: %s\n", filename);
        return;
    }
 
    size_t bytesWritten = fwrite(iterationArray, sizeof(int), width * height, file);
    if (bytesWritten != (size_t)(width * height)) {
        printf("Failed to write all data to file: %s\n", filename);
    } else {
        printf("Successfully saved iteration array to %s\n", filename);
    }
 
    fclose(file);
}
 
 
// 处理 iterationArray 的函数
void ProcessIterationArray(int* array, int width, int height, int newMaxIter) {
    // 将数组中大于 newMaxIter 的值替换为 newMaxIter
    for (int iY = 0; iY < height; iY++) {
        for (int iX = 0; iX < width; iX++) {
            if (array[iY * width + iX] > newMaxIter) {
                array[iY * width + iX] = newMaxIter;
            }
        }
    }
 
    // 计算最小值 a 和最大值 max(忽略 -1)
    int a, max;
    int validCount = 0;
    int sum = 0;
 
    for (int iY = 0; iY < height; iY++) {
        for (int iX = 0; iX < width; iX++) {
            int value = array[iY * width + iX];
            if (value != -1) {
                sum += value;
                validCount++;
            }
        }
    }
 
    if (validCount == 0) {
        printf("No valid values in iterationArray\n");
        return;
    }
 
    a = newMaxIter;  // 初始化为最大值
    max = 0;
 
    for (int iY = 0; iY < height; iY++) {
        for (int iX = 0; iX < width; iX++) {
            int value = array[iY * width + iX];
            if (value != -1) {
                if (value < a) {
                    a = value;
                }
                if (value > max) {
                    max = value;
                }
            }
        }
    }
 
    // 计算 b
    int b = a + (max - a) * 0.2;
 
    // 对于每个 -1,检查其 3 格距离内的值是否都在 [a, b] 范围内或者都等于最大值
    for (int iY = 0; iY < height; iY++) {
        for (int iX = 0; iX < width; iX++) {
            if (array[iY * width + iX] == -1) {
                int count = 0;
                int total = 0;
                int valid = 1;
 
                // 检查 3 格距离内的值
                for (int dy = -3; dy <= 3; dy++) {
                    for (int dx = -3; dx <= 3; dx++) {
                        int ny = iY + dy;
                        int nx = iX + dx;
 
                        // 检查是否越界
                        if (ny >= 0 && ny < height && nx >= 0 && nx < width) {
                            int value = array[ny * width + nx];
                            if (value != -1) {
                                if ((value < a || value > b) && value != newMaxIter) {
                                    valid = 0;
                                    break;
                                }
                                total += value;
                                count++;
                            }
                        }
                    }
                    if (!valid) break;
                }
 
                if (valid && count > 0) {
                    int average = total / count;
                    array[iY * width + iX] = average;
                }
            }
        }
    }
}
 
 
 
 
 
 
// 采样函数
int CalculateNewMaxIter(int iXmax, int iYmax, mpfr_t* mpfrVars, int max_iter) {
    // 每次采样跳10个像素
    int step = 10;
 
    // 计算实际采样点的数量
    int sampleX = (iXmax + step - 1) / step;  // 向上取整
    int sampleY = (iYmax + step - 1) / step;  // 向上取整
    int totalSamples = sampleX * sampleY;
 
    // 动态分配内存存储采样结果
    int* sampleIterations = (int*)malloc(totalSamples * sizeof(int));
    if (!sampleIterations) {
        printf("Failed to allocate memory for sampleIterations\n");
        exit(1);
    }
 
    mpfr_t Cx, Cy, Cyy, Zx, Zy, Zx2, Zy2, temp, ER2;
    mpfr_inits2(precision, Cx, Cy, Cyy, Zx, Zy, Zx2, Zy2, temp, ER2, (mpfr_ptr)0);
    mpfr_set_d(ER2, EscapeRadius * EscapeRadius, MPFR_RNDN);
 
    int sampleIndex = 0;
    for (int iY = 0; iY < iYmax; iY += step) {  // 每次增加 step
        mpfr_set_ui(temp, iY, MPFR_RNDN);
        mpfr_mul(temp, temp, mpfrVars[5], MPFR_RNDN);  // pixel_height
        mpfr_add(Cyy, mpfrVars[2], temp, MPFR_RNDN);     // y_min + iY * pixel_height
 
        for (int iX = 0; iX < iXmax; iX += step) {
            mpfr_set(Cy, Cyy, MPFR_RNDN);
            mpfr_set_ui(temp, iX, MPFR_RNDN);
            mpfr_mul(temp, temp, mpfrVars[4], MPFR_RNDN);  // pixel_width
            mpfr_add(Cx, mpfrVars[0], temp, MPFR_RNDN);     // x_min + iX * pixel_width
 
            mpfr_set_d(Zx, 0.0, MPFR_RNDN);
            mpfr_set_d(Zy, 0.0, MPFR_RNDN);
            mpfr_set_d(Zx2, 0.0, MPFR_RNDN);
            mpfr_set_d(Zy2, 0.0, MPFR_RNDN);
 
            // 根据 zhuliya 的值决定是否改变 Cx 和 Cy 的值
            unsigned long zhuliya_val = mpfr_get_ui(mpfrVars[13], MPFR_RNDN); // 获取整数值.  
            if (zhuliya_val == 1) {
                mpfr_set(Zx, Cx, MPFR_RNDN);
                mpfr_set(Zy, Cy, MPFR_RNDN);
                mpfr_set_str(Cx, zhuliyax, 10, MPFR_RNDN);
                mpfr_set_str(Cy, zhuliyay, 10, MPFR_RNDN);
            }
 
            int Iteration = 0;
            mpfr_add(temp, Zx2, Zy2, MPFR_RNDN);  // temp = Zx2 + Zy2
            while (Iteration < max_iter && mpfr_cmp(temp, ER2) < 0) {
                mpfr_mul(temp, Zx, Zy, MPFR_RNDN);
                mpfr_mul(Zx2, Zx, Zx, MPFR_RNDN);
                mpfr_mul(Zy2, Zy, Zy, MPFR_RNDN);
                mpfr_mul_2exp(temp, temp, 1, MPFR_RNDN);  // temp = 2 * Zx * Zy
                mpfr_add(Zy, temp, Cy, MPFR_RNDN);
 
                mpfr_sub(temp, Zx2, Zy2, MPFR_RNDN);
                mpfr_add(Zx, temp, Cx, MPFR_RNDN);
 
                mpfr_add(temp, Zx2, Zy2, MPFR_RNDN);  // temp = Zx2 + Zy2
                Iteration++;
            }
 
 
            // 将采样结果存储到 iterationArray
            iterationArray[iY * iXmax + iX] = Iteration;
            sampleIterations[sampleIndex++] = Iteration;  // 保存迭代次数
        }
    }
 
    // 在采样循环结束后,找到最小迭代次数
    int minIteration = sampleIterations[0];
    for (int i = 0; i < totalSamples; i++) {
        if (sampleIterations[i] < minIteration) {
            minIteration = sampleIterations[i];
        }
    }
    min_iter = minIteration;  // 更新全局变量 min_iter
    printf("  Min Iterations: %d\n", min_iter);
 
    // 找到最大迭代次数并删除
    int maxIteration = 0;
    for (int i = 0; i < totalSamples; i++) {
        if (sampleIterations[i] > maxIteration) {
            maxIteration = sampleIterations[i];
        }
    }
 
    // 删除最大值
    int* filteredIterations = (int*)malloc((totalSamples - 1) * sizeof(int));
    if (!filteredIterations) {
        printf("Failed to allocate memory for filteredIterations\n");
        exit(1);
    }
 
    int filteredIndex = 0;
    for (int i = 0; i < totalSamples; i++) {
        if (sampleIterations[i] != maxIteration) {
            filteredIterations[filteredIndex++] = sampleIterations[i];
        }
    }
 
    // 使用过滤后的数组计算98%分位数
    int* sortedIterations = (int*)malloc(filteredIndex * sizeof(int));
    if (!sortedIterations) {
        printf("Failed to allocate memory for sortedIterations\n");
        exit(1);
    }
    memcpy(sortedIterations, filteredIterations, filteredIndex * sizeof(int));
    qsort(sortedIterations, filteredIndex, sizeof(int), compare);
 
    int newMaxIter = sortedIterations[(int)(percentile * filteredIndex)];
     
     
 
    // 将 newMaxIter 与 100 比较,取最大值
    newMaxIter = (newMaxIter > 100) ? newMaxIter : 100;
 
    printf("Sample Iterations Statistics:\n");
    printf("  Total Samples: %d\n", totalSamples);
    printf("  Min Iterations: %d\n", sortedIterations[0]);
    printf("  Max Iterations: %d\n", sortedIterations[filteredIndex - 1]);
    printf("  98%% Percentile Iterations: %d\n", newMaxIter);
 
    free(sampleIterations);
    free(sortedIterations);
    free(filteredIterations);
 
    mpfr_clears(Cx, Cy, Zx, Zy, Zx2, Zy2, temp, ER2, (mpfr_ptr)0);
 
    return newMaxIter;
}
 
 
//正式前采样后预先计算
 
unsigned __stdcall MandelbrotThread2(void* param) {
    ThreadParams* params = (ThreadParams*)param;
    int startRow = params->startRow;
    int endRow = params->endRow;
    BYTE* pBits = params->pBits;
    mpfr_t* mpfrVars = params->mpfrVars;
    int iXmax = params->iXmax;
    int iYmax = params->iYmax;
    int IterationMax = params->IterationMax;
 
    mpfr_t Cx, Cy, Cyy, Zx, Zy, Zx2, Zy2, temp, ER2;
    mpfr_inits2(precision, Cx, Cy, Cyy, Zx, Zy, Zx2, Zy2, temp, ER2, (mpfr_ptr)0);
 
    mpfr_set_d(ER2, EscapeRadius * EscapeRadius, MPFR_RNDN);
 
    // 隔3行采样
    for (int iY = startRow; iY < endRow; iY += 3) {
        mpfr_set_ui(temp, iY, MPFR_RNDN);
        mpfr_mul(temp, temp, mpfrVars[5], MPFR_RNDN);  // pixel_height
        mpfr_add(Cyy, mpfrVars[2], temp, MPFR_RNDN);     // y_min + iY * pixel_height
 
        // 隔3格采样
        for (int iX = 0; iX < iXmax; iX += 3) {
            // 如果 iterationArray 中已经有值(不是 NaN),则跳过计算
            if (iterationArray[iY * iXmax + iX] != -1) {
                continue;
            }
 
            mpfr_set(Cy, Cyy, MPFR_RNDN);
            mpfr_set_ui(temp, iX, MPFR_RNDN);
            mpfr_mul(temp, temp, mpfrVars[4], MPFR_RNDN);  // pixel_width
            mpfr_add(Cx, mpfrVars[0], temp, MPFR_RNDN);     // x_min + iX * pixel_width
 
            mpfr_set_d(Zx, 0.0, MPFR_RNDN);
            mpfr_set_d(Zy, 0.0, MPFR_RNDN);
            mpfr_set_d(Zx2, 0.0, MPFR_RNDN);
            mpfr_set_d(Zy2, 0.0, MPFR_RNDN);
 
            // 根据 zhuliya 的值决定是否改变 Cx 和 Cy 的值
            unsigned long zhuliya_val = mpfr_get_ui(mpfrVars[13], MPFR_RNDN); // 获取整数值.  
            if (zhuliya_val == 1) {
                mpfr_set(Zx, Cx, MPFR_RNDN);
                mpfr_set(Zy, Cy, MPFR_RNDN);
                mpfr_set_str(Cx, zhuliyax, 10, MPFR_RNDN);
                mpfr_set_str(Cy, zhuliyay, 10, MPFR_RNDN);
            }
 
            int Iteration = 0;
            while (Iteration < IterationMax) {
                mpfr_mul(temp, Zx, Zy, MPFR_RNDN);
                mpfr_mul(Zx2, Zx, Zx, MPFR_RNDN);
                mpfr_mul(Zy2, Zy, Zy, MPFR_RNDN);
                mpfr_mul_2exp(temp, temp, 1, MPFR_RNDN);  // temp = 2 * Zx * Zy
                mpfr_add(Zy, temp, Cy, MPFR_RNDN);
 
                mpfr_sub(temp, Zx2, Zy2, MPFR_RNDN);
                mpfr_add(Zx, temp, Cx, MPFR_RNDN);
 
                // 只有在迭代次数达到 min_iter 次之后才开始判断是否逃逸
                if (Iteration >= min_iter) {
                    mpfr_add(temp, Zx2, Zy2, MPFR_RNDN);  // temp = Zx2 + Zy2
                    if (mpfr_cmp(temp, ER2) >= 0) {  // 如果逃逸,退出循环
                        break;
                    }
                }
                Iteration++;
            }
             
            // 迭代次数平滑
            double result = (Iteration < IterationMax)
                ? Iteration + 1 - log(log(sqrt(mpfr_get_d(Zx2, MPFR_RNDN) + mpfr_get_d(Zy2, MPFR_RNDN))) / log(2.0)) / log(2.0)
                : IterationMax;
 
            iterationArray[iY * iXmax + iX] = result;  // 保存迭代次数
        }
    }
 
    mpfr_clears(Cx, Cy, Zx, Zy, Zx2, Zy2, temp, ER2, (mpfr_ptr)0);
    _endthreadex(0);
    return 0;
}
 
 
 
 
 
 
 
// 线程函数
unsigned __stdcall MandelbrotThread(void* param) {
    ThreadParams* params = (ThreadParams*)param;
    int startRow = params->startRow;
    int endRow = params->endRow;
    BYTE* pBits = params->pBits;
    mpfr_t* mpfrVars = params->mpfrVars;
    int iXmax = params->iXmax;
    int iYmax = params->iYmax;
    int IterationMax = params->IterationMax;
 
    mpfr_t Cx, Cy, Cyy, Zx, Zy, Zx2, Zy2, temp, ER2;
    mpfr_inits2(precision, Cx, Cy, Cyy, Zx, Zy, Zx2, Zy2, temp, ER2, (mpfr_ptr)0);
 
    mpfr_set_d(ER2, EscapeRadius * EscapeRadius, MPFR_RNDN);
 
    for (int iY = startRow; iY < endRow; iY++) {
        mpfr_set_ui(temp, iY, MPFR_RNDN);
        mpfr_mul(temp, temp, mpfrVars[5], MPFR_RNDN);  // pixel_height
        mpfr_add(Cyy, mpfrVars[2], temp, MPFR_RNDN);     // y_min + iY * pixel_height
 
        for (int iX = 0; iX < iXmax; iX++) {
            // 如果 iterationArray 中已经有值(不是 NaN),则跳过计算
            if (iterationArray[iY * iXmax + iX] != -1) {
                continue;
            }
 
            mpfr_set(Cy, Cyy, MPFR_RNDN);
            mpfr_set_ui(temp, iX, MPFR_RNDN);
            mpfr_mul(temp, temp, mpfrVars[4], MPFR_RNDN);  // pixel_width
            mpfr_add(Cx, mpfrVars[0], temp, MPFR_RNDN);     // x_min + iX * pixel_width
 
            mpfr_set_d(Zx, 0.0, MPFR_RNDN);
            mpfr_set_d(Zy, 0.0, MPFR_RNDN);
            mpfr_set_d(Zx2, 0.0, MPFR_RNDN);
            mpfr_set_d(Zy2, 0.0, MPFR_RNDN);
 
            // 根据 zhuliya 的值决定是否改变 Cx 和 Cy 的值
            unsigned long zhuliya_val = mpfr_get_ui(mpfrVars[13], MPFR_RNDN); // 获取整数值.  
            if (zhuliya_val == 1) {
                mpfr_set(Zx, Cx, MPFR_RNDN);
                mpfr_set(Zy, Cy, MPFR_RNDN);
                mpfr_set_str(Cx, zhuliyax, 10, MPFR_RNDN);
                mpfr_set_str(Cy, zhuliyay, 10, MPFR_RNDN);
            }
 
            int Iteration = 0;
            while (Iteration < IterationMax) {
                mpfr_mul(temp, Zx, Zy, MPFR_RNDN);
                mpfr_mul(Zx2, Zx, Zx, MPFR_RNDN);
                mpfr_mul(Zy2, Zy, Zy, MPFR_RNDN);
                mpfr_mul_2exp(temp, temp, 1, MPFR_RNDN);  // temp = 2 * Zx * Zy
                mpfr_add(Zy, temp, Cy, MPFR_RNDN);
 
                mpfr_sub(temp, Zx2, Zy2, MPFR_RNDN);
                mpfr_add(Zx, temp, Cx, MPFR_RNDN);
 
                // 只有在迭代次数达到 min_iter 次之后才开始判断是否逃逸
                if (Iteration >= min_iter) {
                    mpfr_add(temp, Zx2, Zy2, MPFR_RNDN);  // temp = Zx2 + Zy2
                    if (mpfr_cmp(temp, ER2) >= 0) {  // 如果逃逸,退出循环
                        break;
                    }
                }
                Iteration++;
            }
             
            // 迭代次数平滑
            double result = (Iteration < IterationMax)
                ? Iteration + 1 - log(log(sqrt(mpfr_get_d(Zx2, MPFR_RNDN) + mpfr_get_d(Zy2, MPFR_RNDN))) / log(2.0)) / log(2.0)
                : IterationMax;
 
            iterationArray[iY * iXmax + iX] = result;  // 保存迭代次数
        }
    }
 
    mpfr_clears(Cx, Cy, Zx, Zy, Zx2, Zy2, temp, ER2, (mpfr_ptr)0);
    _endthreadex(0);
    return 0;
}
 
// 读取文件函数
void ParseParametersFromFile(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (!file) {
        printf("Failed to open parameter file: %s\n", filename);
        exit(1);
    }
 
    char line[1048576];  // 假设每行的最大长度为1048576个字符
 
    // 动态分配内存以存储长字符串
    center_x = (char*)malloc(1048576);
    center_y = (char*)malloc(1048576);
    width = (char*)malloc(1048576);
    height = (char*)malloc(1048576);
    scale = (char*)malloc(1048576);
    focus_x = (char*)malloc(1048576);
    focus_y = (char*)malloc(1048576);
    max_iter = (char*)malloc(1048576);
    zhuliyax = (char*)malloc(1048576);
    zhuliyay = (char*)malloc(1048576);
    zhuliya = (char*)malloc(1048576);
 
    // 逐行读取参数
    fgets(line, sizeof(line), file);  // 读取线程数量
    sscanf(line, "%d", &NUM_THREADS);
 
    fgets(line, sizeof(line), file);  // 读取精度
    sscanf(line, "%d", &precision);
 
    fgets(line, sizeof(line), file);  // 读取中心点 X 坐标
    sscanf(line, "%s", center_x);
 
    fgets(line, sizeof(line), file);  // 读取中心点 Y 坐标
    sscanf(line, "%s", center_y);
 
    fgets(line, sizeof(line), file);  // 读取宽度
    sscanf(line, "%s", width);
 
    fgets(line, sizeof(line), file);  // 读取高度
    sscanf(line, "%s", height);
 
    fgets(line, sizeof(line), file);  // 读取缩放比例
    sscanf(line, "%s", scale);
 
    fgets(line, sizeof(line), file);  // 读取焦点 X 坐标
    sscanf(line, "%s", focus_x);
 
    fgets(line, sizeof(line), file);  // 读取焦点 Y 坐标
    sscanf(line, "%s", focus_y);
 
    fgets(line, sizeof(line), file);  // 读取最大迭代次数
    sscanf(line, "%s", max_iter);
 
    fgets(line, sizeof(line), file);  // 读取百分位数
    if (sscanf(line, "%lf", &percentile) != 1) {
        printf("Percentile not specified in file, using default value: 0.98\n");
        percentile = 0.98;  // 如果读取失败,使用默认值
    } else {
        printf("Percentile specified in file: %.2f\n", percentile);
    }
 
    fgets(line, sizeof(line), file);  // 读取 zhuliyax
    sscanf(line, "%s", zhuliyax);
 
    fgets(line, sizeof(line), file);  // 读取 zhuliyay
    sscanf(line, "%s", zhuliyay);
 
    fgets(line, sizeof(line), file);  // 读取 zhuliya
    sscanf(line, "%s", zhuliya);
 
    fclose(file);
 
    // 打印读取到的参数
    printf("Using parameters:\n");
    printf("  Threads: %d\n", NUM_THREADS);
    printf("  Precision: %d bits\n", precision);
    printf("  Center: (%s, %s)\n", center_x, center_y);
    printf("  Width: %s, Height: %s\n", width, height);
    printf("  Scale: %s\n", scale);
    printf("  Focus: (%s, %s)\n", focus_x, focus_y);
    printf("  Max Iterations: %s\n", max_iter);
    printf("  Percentile: %.2f\n", percentile);
    printf("  zhuliyax: %s\n", zhuliyax);
    printf("  zhuliyay: %s\n", zhuliyay);
    printf("  zhuliya: %s\n", zhuliya);
}
 
// 主函数
int main(int argc, char* argv[]) {
    if (argc != 2) {
        printf("Usage: Mandelbrot.exe <parameter_file>\n");
        return -1;
    }
 
    const char* paramFile = argv[1];
 
    ParseParametersFromFile(paramFile);  // 从文件读取参数
 
    // 初始化 GMP/MPFR 精度
    mpfr_set_default_prec(precision);
 
    // 解析输入参数
    mpfr_t center_x_mp, center_y_mp, scale_mp, focus_x_mp, focus_y_mp;
    mpfr_inits2(precision, center_x_mp, center_y_mp, scale_mp, focus_x_mp, focus_y_mp, (mpfr_ptr)0);
 
    mpfr_set_str(center_x_mp, center_x, 10, MPFR_RNDN);  // 中心点 X 坐标
    mpfr_set_str(center_y_mp, center_y, 10, MPFR_RNDN);  // 中心点 Y 坐标
    mpfr_set_str(scale_mp, scale, 10, MPFR_RNDN);        // 缩放比例
    mpfr_set_str(focus_x_mp, focus_x, 10, MPFR_RNDN);    // 焦点 X 坐标
    mpfr_set_str(focus_y_mp, focus_y, 10, MPFR_RNDN);    // 焦点 Y 坐标
 
    int iXmax = atoi(width);    // 图片宽度
    int iYmax = atoi(height);   // 图片高度
    int IterationMax = atoi(max_iter);  // 最大迭代次数
 
    // 为全局变量 iterationArray 分配内存,并初始化为 -1(模拟 NaN)
    iterationArray = (int*)malloc(iYmax * iXmax * sizeof(int));
    if (!iterationArray) {
        printf("Failed to allocate memory for iterationArray\n");
        return -1;
    }
    memset(iterationArray, -1, iYmax * iXmax * sizeof(int));  // 初始化为 -1
 
    // 计算像素宽度和高度
    mpfr_t pixel_width, pixel_height, iXmax_mp, iYmax_mp;
    mpfr_inits(pixel_width, pixel_height, iXmax_mp, iYmax_mp, (mpfr_ptr)0);
    mpfr_set_ui(iXmax_mp, iXmax, MPFR_RNDN);
    mpfr_set_ui(iYmax_mp, iYmax, MPFR_RNDN);
 
    mpfr_t x_min, x_max, y_min, y_max, x_range, y_range;
    mpfr_inits(x_min, x_max, y_min, y_max, x_range, y_range, (mpfr_ptr)0);
 
    mpfr_t temp, mp_one, mp_two;
    mpfr_inits(temp, mp_one, mp_two, (mpfr_ptr)0);
 
    mpfr_set_ui(mp_one, 1, MPFR_RNDN);
    mpfr_set_ui(mp_two, 2, MPFR_RNDN);
 
    // 计算复平面的 X 范围
    mpfr_mul(temp, scale_mp, focus_x_mp, MPFR_RNDN);
    mpfr_sub(x_min, center_x_mp, temp, MPFR_RNDN);
    mpfr_sub(temp, scale_mp, temp, MPFR_RNDN);
    mpfr_add(x_max, center_x_mp, temp, MPFR_RNDN);
 
    // 计算复平面的 Y 范围
    mpfr_div(temp, iYmax_mp, iXmax_mp, MPFR_RNDN);
    mpfr_mul(temp, temp, focus_y_mp, MPFR_RNDN);
    mpfr_mul(temp, scale_mp, temp, MPFR_RNDN);
    mpfr_sub(y_min, center_y_mp, temp, MPFR_RNDN);
 
    mpfr_sub(temp, mp_one, focus_y_mp, MPFR_RNDN);
    mpfr_mul(temp, temp, scale_mp, MPFR_RNDN);
    mpfr_div(mp_one, iYmax_mp, iXmax_mp, MPFR_RNDN);
    mpfr_mul(temp, temp, mp_one, MPFR_RNDN);
    mpfr_add(y_max, center_y_mp, temp, MPFR_RNDN);
 
    mpfr_clears(temp, mp_one, mp_two, (mpfr_ptr)0);
 
    // 计算复平面的 X 和 Y 范围
    mpfr_sub(x_range, x_max, x_min, MPFR_RNDN);
    mpfr_sub(y_range, y_max, y_min, MPFR_RNDN);
 
    // 计算每个像素对应的复平面宽度和高度
    mpfr_div(pixel_width, x_range, iXmax_mp, MPFR_RNDN);
    mpfr_div(pixel_height, y_range, iYmax_mp, MPFR_RNDN);
 
    // 初始化线程参数
    ThreadParams threadParams[NUM_THREADS];
    mpfr_t* mpfrVars = (mpfr_t*)malloc(14 * sizeof(mpfr_t));  // 增加一个变量用于存储 zhuliya
    for (int i = 0; i < 14; i++) {
        mpfr_init(mpfrVars[i]);
    }
 
    mpfr_set(mpfrVars[0], x_min, MPFR_RNDN);
    mpfr_set(mpfrVars[1], x_max, MPFR_RNDN);
    mpfr_set(mpfrVars[2], y_min, MPFR_RNDN);
    mpfr_set(mpfrVars[3], y_max, MPFR_RNDN);
    mpfr_set(mpfrVars[4], pixel_width, MPFR_RNDN);
    mpfr_set(mpfrVars[5], pixel_height, MPFR_RNDN);
    mpfr_set(mpfrVars[6], center_x_mp, MPFR_RNDN);
    mpfr_set(mpfrVars[7], center_y_mp, MPFR_RNDN);
    mpfr_set(mpfrVars[8], scale_mp, MPFR_RNDN);
    mpfr_set(mpfrVars[9], focus_x_mp, MPFR_RNDN);
    mpfr_set(mpfrVars[10], focus_y_mp, MPFR_RNDN);
    mpfr_set(mpfrVars[11], iXmax_mp, MPFR_RNDN);
    mpfr_set(mpfrVars[12], iYmax_mp, MPFR_RNDN);
    mpfr_set_str(mpfrVars[13], zhuliya, 10, MPFR_RNDN);  // 存储 zhuliya 的值
 
    // 计算采样点的迭代次数并确定新的最大迭代次数
    int newMaxIter = CalculateNewMaxIter(iXmax, iYmax, mpfrVars, IterationMax);
    printf("New Max Iterations based on sampling: %d\n", newMaxIter);
     
        // 使用新的最大迭代次数重新计算整个图像
    int rowsPerThread = iYmax / NUM_THREADS;
    HANDLE hThreads2[NUM_THREADS];
 
    for (int i = 0; i < NUM_THREADS; i++) {
        int startRow = i * rowsPerThread;
        int endRow = (i == NUM_THREADS - 1) ? iYmax : startRow + rowsPerThread;
 
        threadParams[i].startRow = startRow;
        threadParams[i].endRow = endRow;
        threadParams[i].pBits = NULL;  // 不使用位图,设置为 NULL
        threadParams[i].mpfrVars = mpfrVars;
        threadParams[i].iXmax = iXmax;
        threadParams[i].iYmax = iYmax;
        threadParams[i].IterationMax = newMaxIter;
 
        hThreads2[i] = (HANDLE)_beginthreadex(NULL, 0, MandelbrotThread2, (void*)&threadParams[i], 0, NULL);
    }
 
    // 等待线程完成
    WaitForMultipleObjects(NUM_THREADS, hThreads2, TRUE, INFINITE);
    for (int i = 0; i < NUM_THREADS; i++) {
        CloseHandle(hThreads2[i]);
    }
     
     
     
 
    // 在调用 ProcessIterationArray 函数前记录开始时间
    time_t start_time, end_time;
    time(&start_time);
    printf("Processing iterationArray started at %s", ctime(&start_time));
 
    // 调用 ProcessIterationArray 函数
    ProcessIterationArray(iterationArray, iXmax, iYmax, newMaxIter);
 
    // 在调用 ProcessIterationArray 函数后记录结束时间
    time(&end_time);
    printf("Processing iterationArray finished at %s", ctime(&end_time));
 
 
    // 使用新的最大迭代次数重新计算整个图像
    HANDLE hThreads[NUM_THREADS];
 
    for (int i = 0; i < NUM_THREADS; i++) {
        int startRow = i * rowsPerThread;
        int endRow = (i == NUM_THREADS - 1) ? iYmax : startRow + rowsPerThread;
 
        threadParams[i].startRow = startRow;
        threadParams[i].endRow = endRow;
        threadParams[i].pBits = NULL;  // 不使用位图,设置为 NULL
        threadParams[i].mpfrVars = mpfrVars;
        threadParams[i].iXmax = iXmax;
        threadParams[i].iYmax = iYmax;
        threadParams[i].IterationMax = newMaxIter;
 
        hThreads[i] = (HANDLE)_beginthreadex(NULL, 0, MandelbrotThread, (void*)&threadParams[i], 0, NULL);
    }
 
    // 等待线程完成
    WaitForMultipleObjects(NUM_THREADS, hThreads, TRUE, INFINITE);
    for (int i = 0; i < NUM_THREADS; i++) {
        CloseHandle(hThreads[i]);
    }
 
    // 清理 MPFR 变量
    for (int i = 0; i < 14; i++) {
        mpfr_clear(mpfrVars[i]);
    }
    free(mpfrVars);
 
    // 保存迭代次数数组
    SaveIterationArrayAsBinary("iteration_array.bin", iXmax, iYmax);
 
    // 释放全局变量 iterationArray
    free(iterationArray);
 
    // 清理 MPFR 变量
    mpfr_clears(center_x_mp, center_y_mp, scale_mp, focus_x_mp, focus_y_mp,
                pixel_width, pixel_height, iXmax_mp, iYmax_mp,
                x_min, x_max, y_min, y_max, x_range, y_range, (mpfr_ptr)0);
 
    return 0;
}
[Python] 纯文本查看 复制代码
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093
0094
0095
0096
0097
0098
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138
0139
0140
0141
0142
0143
0144
0145
0146
0147
0148
0149
0150
0151
0152
0153
0154
0155
0156
0157
0158
0159
0160
0161
0162
0163
0164
0165
0166
0167
0168
0169
0170
0171
0172
0173
0174
0175
0176
0177
0178
0179
0180
0181
0182
0183
0184
0185
0186
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207
0208
0209
0210
0211
0212
0213
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226
0227
0228
0229
0230
0231
0232
0233
0234
0235
0236
0237
0238
0239
0240
0241
0242
0243
0244
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255
0256
0257
0258
0259
0260
0261
0262
0263
0264
0265
0266
0267
0268
0269
0270
0271
0272
0273
0274
0275
0276
0277
0278
0279
0280
0281
0282
0283
0284
0285
0286
0287
0288
0289
0290
0291
0292
0293
0294
0295
0296
0297
0298
0299
0300
0301
0302
0303
0304
0305
0306
0307
0308
0309
0310
0311
0312
0313
0314
0315
0316
0317
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328
0329
0330
0331
0332
0333
0334
0335
0336
0337
0338
0339
0340
0341
0342
0343
0344
0345
0346
0347
0348
0349
0350
0351
0352
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377
0378
0379
0380
0381
0382
0383
0384
0385
0386
0387
0388
0389
0390
0391
0392
0393
0394
0395
0396
0397
0398
0399
0400
0401
0402
0403
0404
0405
0406
0407
0408
0409
0410
0411
0412
0413
0414
0415
0416
0417
0418
0419
0420
0421
0422
0423
0424
0425
0426
0427
0428
0429
0430
0431
0432
0433
0434
0435
0436
0437
0438
0439
0440
0441
0442
0443
0444
0445
0446
0447
0448
0449
0450
0451
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479
0480
0481
0482
0483
0484
0485
0486
0487
0488
0489
0490
0491
0492
0493
0494
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514
0515
0516
0517
0518
0519
0520
0521
0522
0523
0524
0525
0526
0527
0528
0529
0530
0531
0532
0533
0534
0535
0536
0537
0538
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554
0555
0556
0557
0558
0559
0560
0561
0562
0563
0564
0565
0566
0567
0568
0569
0570
0571
0572
0573
0574
0575
0576
0577
0578
0579
0580
0581
0582
0583
0584
0585
0586
0587
0588
0589
0590
0591
0592
0593
0594
0595
0596
0597
0598
0599
0600
0601
0602
0603
0604
0605
0606
0607
0608
0609
0610
0611
0612
0613
0614
0615
0616
0617
0618
0619
0620
0621
0622
0623
0624
0625
0626
0627
0628
0629
0630
0631
0632
0633
0634
0635
0636
0637
0638
0639
0640
0641
0642
0643
0644
0645
0646
0647
0648
0649
0650
0651
0652
0653
0654
0655
0656
0657
0658
0659
0660
0661
0662
0663
0664
0665
0666
0667
0668
0669
0670
0671
0672
0673
0674
0675
0676
0677
0678
0679
0680
0681
0682
0683
0684
0685
0686
0687
0688
0689
0690
0691
0692
0693
0694
0695
0696
0697
0698
0699
0700
0701
0702
0703
0704
0705
0706
0707
0708
0709
0710
0711
0712
0713
0714
0715
0716
0717
0718
0719
0720
0721
0722
0723
0724
0725
0726
0727
0728
0729
0730
0731
0732
0733
0734
0735
0736
0737
0738
0739
0740
0741
0742
0743
0744
0745
0746
0747
0748
0749
0750
0751
0752
0753
0754
0755
0756
0757
0758
0759
0760
0761
0762
0763
0764
0765
0766
0767
0768
0769
0770
0771
0772
0773
0774
0775
0776
0777
0778
0779
0780
0781
0782
0783
0784
0785
0786
0787
0788
0789
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804
0805
0806
0807
0808
0809
0810
0811
0812
0813
0814
0815
0816
0817
0818
0819
0820
0821
0822
0823
0824
0825
0826
0827
0828
0829
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862
0863
0864
0865
0866
0867
0868
0869
0870
0871
0872
0873
0874
0875
0876
0877
0878
0879
0880
0881
0882
0883
0884
0885
0886
0887
0888
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919
0920
0921
0922
0923
0924
0925
0926
0927
0928
0929
0930
0931
0932
0933
0934
0935
0936
0937
0938
0939
0940
0941
0942
0943
0944
0945
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956
0957
0958
0959
0960
0961
0962
0963
0964
0965
0966
0967
0968
0969
0970
0971
0972
0973
0974
0975
0976
0977
0978
0979
0980
0981
0982
0983
0984
0985
0986
0987
0988
0989
0990
0991
0992
0993
0994
0995
0996
0997
0998
0999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from tkinter import (
    Tk,
    Label,
    Entry,
    Button,
    StringVar,
    filedialog,
    messagebox,
    OptionMenu,
    Frame,
)
import time
import traceback
import gmpy2
from gmpy2 import mpfr, mpc, get_context, log10
import pyopencl as cl
from pyopencl import array
from multiprocessing import Process, Queue, cpu_count
import tempfile
 
import subprocess  # 确保导入 subprocess 模块
 
from threading import Thread
from tkinter import BooleanVar
from tkinter import Checkbutton
 
 
# 并行计算配置
WORKERS = max(cpu_count() - 1, 1# 使用CPU核心-1
 
# 配置Matplotlib
plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False
 
# 全局控制变量
generating = False
current_task = 0
total_tasks = 0
 
 
# 获取可用的CPU核心数
MAX_WORKERS = WORKERS
 
 
# ================== 核心计算模块 =======
 
 
def initialize_opencl():
    """初始化 OpenCL 环境并编译内核"""
    platforms = cl.get_platforms()
    if not platforms:
        raise RuntimeError("没有找到可用的 OpenCL 平台")
 
    platform = platforms[0]
    print(f"选择的 OpenCL 平台: {platform.name}")
 
    devices = platform.get_devices()
    if not devices:
        raise RuntimeError("没有找到可用的 OpenCL 设备")
 
    device = devices[0]
    print(f"选择的 OpenCL 设备: {device.name}")
 
    ctx = cl.Context(devices=[device])
    queue = cl.CommandQueue(
        ctx, properties=cl.command_queue_properties.PROFILING_ENABLE
    )
 
    # 编译内核代码
    kernel_code = """
    #pragma OPENCL EXTENSION cl_khr_fp64 : enable
    __kernel void mandelbrot(
        __global float *output,
        const double x_min, const double x_max,
        const double y_min, const double y_max,
        const int width, const int height,
        const int max_iter,const double c_x, const double c_y, const int Julia)
         
         
         
    {
        int j = get_global_id(0);
        int i = get_global_id(1);
         
        if (i >= height || j >= width) return;
         
        double x = x_min + (double)j / (width - 1) * (x_max - x_min);
        double y = y_min + (double)i / (height - 1) * (y_max - y_min);
                
         
        // 根据 Julia 参数决定 c_x 和 c_y 的值
        double cr = (Julia == 0) ? c_x : x;
        double ci = (Julia == 0) ? c_y : y;
     
        double zr = x;
        double zi = y;
        int n = 0;
        double zr2, zi2;
         
        while (n < max_iter) {
            zr2 = zr * zr;
            zi2 = zi * zi;
            if (zr2 + zi2 > 4.0) break;
             
            zi = 2 * zr * zi + ci;
            zr = zr2 - zi2 + cr;
            n++;
        }
         
        float result = (n < max_iter) ? n + 1 - log(log(sqrt(zr2 + zi2)) / log(2.0)) / log(2.0) : max_iter;
        output[i * width + j] = result;
    }
    """
    prg = cl.Program(ctx, kernel_code).build()
 
    print("内核编译完成")
 
    return ctx, queue, prg
 
 
# ================== GUI界面模块 ==================
class MandelbrotGenerator:
 
    def gmp_high_precision_compute(
        self,
        x_min,
        x_max,
        y_min,
        y_max,
        width,
        height,
        max_iter,
        precision,
        current_task,
    ):
        """高精度计算 Mandelbrot 集"""
        # 从 MandelbrotGenerator 类的实例中获取当前参数
        current_params = self.validate_parameters()  # 获取当前参数
        if current_params is None:
            raise ValueError("参数验证失败")
 
        # 计算二进制精度
        binary_precision = int(precision * 3.324) + 16
        print(f"二进制精度: {binary_precision}")
 
        thread_count = WORKERS
        print(f"线程数: {thread_count}")
        print(f"初始缩放比例: {current_params['initial_scale']}")
 
        # 计算当前缩放比例
        current_scale2 = mpfr(current_params["initial_scale"]) / (
            mpfr(current_params["zoom_factor"]) ** (current_task - 1)
        )
 
        percentile3 = float(self.percentile_entry.get())  # 从输入框获取百分位数
 
        percentile2 = log10(percentile3) / 2  # 使用 gmpy2 的 log10 函数
        if self.julia_var.get():
            julia = 1
        else:
            julia = 0
 
        # 将参数写入临时文件
        script_dir = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(script_dir, "mandelbrot.txt")
 
        with open(file_path, "w") as temp_file:
            temp_file.write(f"{thread_count}\n")
            temp_file.write(f"{binary_precision}\n")
            temp_file.write(f"{current_params['center_x']}\n")
            temp_file.write(f"{current_params['center_y']}\n")
            temp_file.write(f"{width}\n")
            temp_file.write(f"{height}\n")
            temp_file.write(f"{str(current_scale2)}\n")
            temp_file.write(f"{current_params['focus_x']}\n")
            temp_file.write(f"{current_params['focus_y']}\n")
            temp_file.write(f"{current_params['max_iter']}\n")
            temp_file.write(f"{percentile2}\n")
            temp_file.write(f"{current_params['c_x']}\n")
            temp_file.write(f"{current_params['c_y']}\n")
            temp_file.write(f"{julia}\n")
 
            temp_file.flush()  # 确保内容写入磁盘
 
        # 切换工作目录到文件所在路径
        os.chdir(script_dir)  # 切换到脚本目录
 
        # 调用 Mandelbrot.exe 并传递临时文件路径
        command = f"Mandelbrot.exe mandelbrot.txt"
        print(f"执行命令: {command}")
 
        self.mandelbrot_process = subprocess.Popen(command, shell=True# 保存进程对象
        while self.mandelbrot_process.poll() is None:
            if not generating:
                # 强行终止 Mandelbrot.exe 进程
                subprocess.run("taskkill /F /IM Mandelbrot.exe", shell=True)
                raise Exception("计算已终止")
            time.sleep(0.2)
        # 处理结果...
 
        print("命令完成")
 
        # 加载结果文件
        output = self.load_iteration_array_from_file(width, height)
        if output is None:
            raise FileNotFoundError("未找到 iteration_array.bin 文件或文件格式不正确")
        return output
 
    def load_iteration_array_from_file(self, width, height):
        """从文件中加载迭代次数数组"""
        file_path = "iteration_array.bin"
        if not os.path.exists(file_path):
            print(f"文件 {file_path} 不存在")
            return None
 
        try:
            # 打开文件并读取数据
            with open(file_path, "rb") as file:
                # 假设文件存储的是整数的二维数组
                data = np.fromfile(file, dtype=np.int32)
                if len(data) != width * height:
                    print(f"文件 {file_path} 的数据大小与预期不符")
                    return None
                # 将数据重塑为二维数组
                output = data.reshape((height, width))
 
                return output
        except Exception as e:
            print(f"读取文件 {file_path} 时出错: {str(e)}")
            return None
 
    def create_buttons(self, parent):
        """创建区域切换按钮"""
        buttons_frame = Frame(parent, padx=10, pady=5)
        buttons_frame.grid(row=3, column=0, sticky="ew", padx=5)
 
        regions = [
            (
                "海马谷",
                -0.74515135254160040270968367987368282086820830812505531306383690724472274612043,
                0.1301973420730631518534562967071010595298732429535045571757108286281891077748,
            ),
            ("花", -0.3906731935564842, 0.6243239460184142),
            ("螺丝线", -1.999944284562545, 7.674460749033766e-16),
            ("羽毛", -1.49005323192932, 0.00119631499924505),
            ("螺旋", -0.6888873943437659, 0.2810053792512903),
            ("螺旋2", 0.2513567236163006, -9.220290965617807e-05),
        ]
 
        for idx, (name, x, y) in enumerate(regions):
            btn = Button(
                buttons_frame,
                text=name,
                width=3,
                command=lambda x=x, y=y: self.set_focus(x, y),
            )
            btn.grid(row=idx // 2, column=idx % 2, padx=3, pady=1.5)
 
    # 新增设置焦点坐标的方法(直接传递x和y数值)
    def set_focus(self, x_val, y_val):
        """直接设置焦点坐标并更新图像"""
        try:
            # 强制保留15位小数(根据需求可调整)
            self.center_x_entry.delete(0, "end")
            self.center_x_entry.insert(0, f"{x_val}")
 
            self.center_y_entry.delete(0, "end")
            self.center_y_entry.insert(0, f"{y_val}")
 
        except Exception as e:
            messagebox.showerror("输入错误", f"坐标设置失败: {str(e)}")
 
    def safe_compute_mandelbrot(
        self,
        x_min,
        x_max,
        y_min,
        y_max,
        width,
        height,
        max_iter,
        precision_threshold,
        current_task,
        c_x,
        c_y,
        precision=50,
    ):
        # """智能计算分发函数"""
        try:
            if precision > precision_threshold:
                # 高精度并行模式(原有实现)
                self.current_method = "gmp高精度计算"  # 高精度模式
                # 从 MandelbrotGenerator 类的实例中获取当前参数
                return self.gmp_high_precision_compute(
                    x_min,
                    x_max,
                    y_min,
                    y_max,
                    width,
                    height,
                    max_iter,
                    precision,
                    current_task,
                )
 
            else:
                try:
                    # 尝试使用 GPU 加速
                    self.current_method = "OpenCL"  # 尝试OpenCL
                    return self.opencl_mandelbrot(
                        x_min, x_max, y_min, y_max, width, height, max_iter, c_x, c_y
                    )
                except:
                    # 使用普通 CPU 计算
                    self.current_method = "opencl失败,切gmp高精度计算"
                    return self.gmp_high_precision_compute(
                        x_min,
                        x_max,
                        y_min,
                        y_max,
                        width,
                        height,
                        max_iter,
                        precision,
                        current_task,
                    )
 
        except Exception as e:
            print(f"计算错误: {str(e)}")
            raise
 
    def opencl_mandelbrot(
        self, x_min, x_max, y_min, y_max, width, height, max_iter, c_x, c_y
    ):
        """使用 OpenCL 计算 Mandelbrot 集 (同步优化版)"""
 
        if self.julia_var.get():
            julia = 0
        else:
            julia = 1
 
        print("开始opencl计算")
        # 创建输出缓冲区和映射
        output = np.empty((height, width), dtype=np.float32)
        output_buf = cl.Buffer(
            self.ctx,
            cl.mem_flags.WRITE_ONLY | cl.mem_flags.ALLOC_HOST_PTR,
            size=output.nbytes,
        )
 
        # 预计算:缩小 10 倍的宽度和高度
        pre_width = max(width // 10, 1# 防止宽度或高度为 0
        pre_height = max(height // 10, 1# 防止宽度或高度为 0
        pre_output = np.empty((pre_height, pre_width), dtype=np.float32)
        pre_output_buf = cl.Buffer(
            self.ctx,
            cl.mem_flags.WRITE_ONLY | cl.mem_flags.ALLOC_HOST_PTR,
            size=pre_output.nbytes,
        )
        print("准备发内核")
        # 同步执行预计算内核
        global_size = (pre_width, pre_height)  # 使用2D全局工作尺寸
        pre_kernel_event = self.prg.mandelbrot(
            self.queue,
            global_size,
            None# 自动选择工作组大小
            pre_output_buf,
            np.float64(x_min),
            np.float64(x_max),
            np.float64(y_min),
            np.float64(y_max),
            np.int32(pre_width),
            np.int32(pre_height),
            np.int32(max_iter),
            np.float64(c_x),
            np.float64(c_y),
            np.int32(julia),
        )
 
        print("数据已发送内核")
        pre_kernel_event.wait()  # 等待内核完成
        # 映射预计算结果
        mapped_pre_data, _ = cl.enqueue_map_buffer(
            self.queue,
            pre_output_buf,
            cl.map_flags.READ,
            0,
            pre_output.shape,
            pre_output.dtype,
        )
        np.copyto(pre_output, mapped_pre_data)
 
        # 去除所有重复的最大值
        max_iter_value = np.max(pre_output)  # 获取最大迭代次数的值
        pre_output[pre_output == max_iter_value] = 0  # 将最大值替换为 NaN
 
        percentile = float(self.percentile_entry.get())  # 从输入框获取百分位数
 
        percentile_log = log10(percentile) * 50  # 使用 gmpy2 的 log10 函数并校准
        percentile_log = float(percentile_log)  # 从输入框获取百分位数
 
        # 计算新的最大迭代次数(取 98% 的位置)
        new_max_iter = int(np.percentile(pre_output, percentile_log))
 
        new_max_iter = max(new_max_iter, 100# 确保 new_max_iter 不小于 100
        print(f"预计算完成,新的最大迭代次数: {new_max_iter}")
 
        # 正式计算:使用新的最大迭代次数
        global_size = (width, height)  # 使用2D全局工作尺寸
        kernel_event = self.prg.mandelbrot(
            self.queue,
            global_size,
            None# 自动选择工作组大小
            output_buf,
            np.float64(x_min),
            np.float64(x_max),
            np.float64(y_min),
            np.float64(y_max),
            np.int32(width),
            np.int32(height),
            np.int32(new_max_iter),
            np.float64(c_x),
            np.float64(c_y),
            np.int32(julia),
        )
        kernel_event.wait()  # 等待内核完成
 
        # 映射正式计算结果
        mapped_data, _ = cl.enqueue_map_buffer(
            self.queue, output_buf, cl.map_flags.READ, 0, output.shape, output.dtype
        )
        np.copyto(output, mapped_data)
 
        return output
 
    def get_zoom_factor(self):
        """从输入框中获取最新的放大系数"""
        try:
            zoom_factor = float(self.zoom_factor_entry.get())
            if zoom_factor <= 0:
                raise ValueError("放大系数必须大于0")
            return zoom_factor
        except ValueError as e:
            messagebox.showerror("输入错误", f"放大系数无效: {str(e)}")
            raise
 
    def on_canvas_release(self, event):
        """处理画布上的鼠标松开事件"""
        if not generating and event.inaxes:
            x_pixel, y_pixel = event.xdata, event.ydata  # 获取鼠标松开时的坐标
            # 获取当前显示范围
            # x_min, x_max = self.current_metadata['x_range']
            # y_min, y_max = self.current_metadata['y_range']
 
            # 将像素坐标转换为复平面上的实际坐标
            # center_x = x_pixel
            # center_y = y_pixel
 
            default_width = int(self.width_entry.get())  # 从输入框获取宽度
            default_height = int(self.height_entry.get())  # 从输入框获取高度
 
            # 更新焦点位置
            focus_x = x_pixel / default_width
            focus_y = y_pixel / default_height
 
            if self.select_c_var.get():  # 如果勾选了“画布选择c坐标”
                pass  # 如果没有具体逻辑,可以用 pass 占位
            else:
 
                # 更新焦点位置输入框
                self.focus_x_entry.delete(0, "end")
                self.focus_x_entry.insert(0, f"{focus_x}")
 
                self.focus_y_entry.delete(0, "end")
                self.focus_y_entry.insert(0, f"{focus_y}")
 
                # 可选:自动重新生成 Mandelbrot 集
                self.start_generation()
 
    def on_canvas_click(self, event):
        """处理画布上的鼠标点击事件"""
        if not generating and event.inaxes:
            # 获取点击位置的数据坐标
            x_pixel, y_pixel = event.xdata, event.ydata
 
            # 获取当前显示范围
            x_min, x_max = self.current_metadata["x_range"]
            y_min, y_max = self.current_metadata["y_range"]
            # 将像素坐标转换为复平面上的实际坐标
            center_x = x_pixel
            center_y = y_pixel
 
            current_scalex = mpfr(x_max) - mpfr(x_min)  # 当前显示范围的宽度
            current_scaley = mpfr(y_max) - mpfr(y_min)  # 当前显示范围的高度
 
            default_width = int(self.width_entry.get())  # 从输入框获取宽度
            default_height = int(self.height_entry.get())  # 从输入框获取高度
 
            # 更新焦点位置
            cc_x = mpfr(x_pixel) / mpfr(default_width) * 4 - 2
            cc_y = mpfr(y_pixel) / mpfr(default_height) * 4 - 2
 
            # 计算点击位置的实际坐标
            center_x = mpfr(x_pixel) * mpfr(current_scalex) / mpfr(
                default_width
            ) + mpfr(x_min)
            center_y = mpfr(y_pixel) * mpfr(current_scaley) / mpfr(
                default_height
            ) + mpfr(y_min)
 
            # 检查是否启用了“画布选择c坐标”选项
            if self.select_c_var.get():  # 如果勾选了“画布选择c坐标”
                # 更新 c_x 和 c_y 的值
                self.c_x_entry.delete(0, "end")
                self.c_x_entry.insert(0, str(cc_x))
 
                self.c_y_entry.delete(0, "end")
                self.c_y_entry.insert(0, str(cc_y))
                self.start_generation()
 
            else:
                # 否则更新焦点数值坐标
 
                # 更新宽度数值
 
                current_scale = current_scalex / mpfr(
                    self.get_zoom_factor()
                # 再除以一次放大系数
 
                self.scale_entry.delete(0, "end")
                self.scale_entry.insert(0, str(current_scale))
                self.center_x_entry.delete(0, "end")
                self.center_x_entry.insert(0, str(center_x))
 
                self.center_y_entry.delete(0, "end")
                self.center_y_entry.insert(0, str(center_y))
                # self.start_generation()
 
            # 可选:自动重新生成 Mandelbrot 集
            # self.start_generation()
 
    def __init__(self, root):
        self.root = root
        self.current_image = None  # 初始化为 None 或其他默认值
        self.current_metadata = {}  # 初始化为一个空字典
        self.mandelbrot_process = None  # 用于存储 Mandelbrot.exe 的进程对象
 
        self.setup_ui()
        self.setup_plot()
        # 初始化 OpenCL 环境
        self.ctx, self.queue, self.prg = initialize_opencl()
        self.current_method = "OpenCL"  # 默认使用Numba
        self.last_click_time = 0  # 上一次点击的时间
        self.is_double_click = False  # 是否为双击
 
    def setup_ui(self):
        """初始化用户界面"""
        self.root.title("Mandelbrot集图片生成器")
        self.root.geometry("1200x800")
        self.root.grid_columnconfigure(1, weight=1)
        self.root.grid_rowconfigure(0, weight=1)
 
        # 控制面板(改为Frame容器)
        control_frame = Frame(self.root, padx=10, pady=10)
        control_frame.grid(row=0, column=0, sticky="nsew")
        control_frame.grid_columnconfigure(1, weight=1# 新增列权重配置
 
        # 参数输入控件
        self.create_inputs(control_frame)
 
        # 状态栏
        self.status_var = StringVar()
        self.status_var.set("就绪")
        status_bar = Label(
            self.root,
            textvariable=self.status_var,
            bd=1,
            relief="sunken",
            anchor="w",
            font=("微软雅黑", 9),
            bg="#f0f0f0",
        )
        status_bar.grid(row=1, column=0, columnspan=2, sticky="ew")
 
    def create_inputs(self, parent):
        """创建输入控件"""
        row = 0
        Label(parent, text="分辨率", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.width_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.width_entry.insert(0, "800")
        self.width_entry.grid(row=row, column=1, padx=2)
        Label(parent, text="×", font=("微软雅黑", 10)).grid(row=row, column=2)
        self.height_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.height_entry.insert(0, "600")
        self.height_entry.grid(row=row, column=3, padx=2)
 
        row += 1
        Label(parent, text="焦点数值坐标 X", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.center_x_entry = Entry(parent, width=20, font=("微软雅黑", 10))
        self.center_x_entry.insert(
            0,
            "-0.74515135254160040270968367987368282086820830812505531306383690724472274612043",
        )
        self.center_x_entry.grid(row=row, column=1, columnspan=3, padx=2)
 
        row += 1
        Label(parent, text="焦点数值坐标 Y", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.center_y_entry = Entry(parent, width=20, font=("微软雅黑", 10))
        self.center_y_entry.insert(
            0,
            "0.1301973420730631518534562967071010595298732429535045571757108286281891077748",
        )
        self.center_y_entry.grid(row=row, column=1, columnspan=3, padx=2)
 
        # 添加朱利亚开关
        row += 2
        self.julia_var = BooleanVar()
        self.julia_checkbox = Checkbutton(
            parent,
            text="启用朱利亚集",
            variable=self.julia_var,
            command=self.toggle_julia_mode,
            font=("微软雅黑", 10),
        )
        self.julia_checkbox.grid(row=row, column=0, columnspan=5, sticky="w", pady=2)
        row += 1
        # 添加“画布上选择c坐标”开关
        self.select_c_var = BooleanVar()  # 创建一个布尔变量
        self.select_c_checkbox = Checkbutton(
            parent,
            text="画布上选择c坐标",
            variable=self.select_c_var,
            font=("微软雅黑", 10),
        )
        self.select_c_checkbox.grid(row=row, column=0, columnspan=5, sticky="w", pady=2)
 
        row += 1
        self.copy_button = Button(
            parent,
            text="复制焦点坐标到 c 坐标",
            command=self.copy_center_to_c,
            font=("微软雅黑", 10),
        )
        self.copy_button.grid(row=row, column=0, columnspan=5, pady=5, sticky="we")
 
        row += 1
 
        Label(parent, text="c坐标 X", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.c_x_entry = Entry(parent, width=20, font=("微软雅黑", 10))
        self.c_x_entry.insert(
            0,
            "-0.74515135254160040270968367987368282086820830812505531306383690724472274612043",
        )
        self.c_x_entry.grid(row=row, column=1, columnspan=3, padx=2)
        self.c_x_entry.config(state="disabled"# 默认禁用
 
        row += 1
        Label(parent, text="c坐标 Y", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.c_y_entry = Entry(parent, width=20, font=("微软雅黑", 10))
        self.c_y_entry.insert(
            0,
            "0.1301973420730631518534562967071010595298732429535045571757108286281891077748",
        )
        self.c_y_entry.grid(row=row, column=1, columnspan=3, padx=2)
        self.c_y_entry.config(state="disabled"# 默认禁用
 
        row += 1
        Label(parent, text="宽度数值", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.scale_entry = Entry(parent, width=20, font=("微软雅黑", 10))
        self.scale_entry.insert(0, "3.0000000")
        self.scale_entry.grid(row=row, column=1, columnspan=3, padx=2)
 
        row += 1
        Label(parent, text="动态迭代数上限", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.max_iter_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.max_iter_entry.insert(0, "9999")
        self.max_iter_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="动态迭代阈值(0-100)", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.percentile_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.percentile_entry.insert(0, "90"# 默认值为 90
        self.percentile_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="生成数量", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.num_images_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.num_images_entry.insert(0, "4")
        self.num_images_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="放大系数", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.zoom_factor_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.zoom_factor_entry.insert(0, "1.5")
        self.zoom_factor_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="焦点位置坐标 X", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.focus_x_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.focus_x_entry.insert(0, "0.5"# 默认值为 0.5
        self.focus_x_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="焦点位置坐标 Y", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.focus_y_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.focus_y_entry.insert(0, "0.5"# 默认值为 0.5
        self.focus_y_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="切换cpu阈值", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.precision_threshold_entry = Entry(parent, width=8, font=("微软雅黑", 10))
        self.precision_threshold_entry.insert(0, "11"# 默认值为 11
        self.precision_threshold_entry.grid(row=row, column=1, padx=2)
 
        row += 1
        Label(parent, text="颜色映射", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.colormap_var = StringVar()
        self.colormap_var.set("jet"# 默认值
        colormaps = [
            "Accent",
            "Accent_r",
            "Blues",
            "Blues_r",
            "BrBG",
            "BrBG_r",
            "BuGn",
            "BuGn_r",
            "BuPu",
            "BuPu_r",
            "CMRmap",
            "CMRmap_r",
            "Dark2",
            "Dark2_r",
            "GnBu",
            "GnBu_r",
            "Grays",
            "Greens",
            "Greens_r",
            "Greys",
            "Greys_r",
            "OrRd",
            "OrRd_r",
            "Oranges",
            "Oranges_r",
            "PRGn",
            "PRGn_r",
            "Paired",
            "Paired_r",
            "Pastel1",
            "Pastel1_r",
            "Pastel2",
            "Pastel2_r",
            "PiYG",
            "PiYG_r",
            "PuBu",
            "PuBuGn",
            "PuBuGn_r",
            "PuBu_r",
            "PuOr",
            "PuOr_r",
            "PuRd",
            "PuRd_r",
            "Purples",
            "Purples_r",
            "RdBu",
            "RdBu_r",
            "RdGy",
            "RdGy_r",
            "RdPu",
            "RdPu_r",
            "RdYlBu",
            "RdYlBu_r",
            "RdYlGn",
            "RdYlGn_r",
            "Reds",
            "Reds_r",
            "Set1",
            "Set1_r",
            "Set2",
            "Set2_r",
            "Set3",
            "Set3_r",
            "Spectral",
            "Spectral_r",
            "Wistia",
            "Wistia_r",
            "YlGn",
            "YlGnBu",
            "YlGnBu_r",
            "YlGn_r",
            "YlOrBr",
            "YlOrBr_r",
            "YlOrRd",
            "YlOrRd_r",
            "afmhot",
            "afmhot_r",
            "autumn",
            "autumn_r",
            "binary",
            "binary_r",
            "bone",
            "bone_r",
            "brg",
            "brg_r",
            "bwr",
            "bwr_r",
            "cividis",
            "cividis_r",
            "cool",
            "cool_r",
            "coolwarm",
            "coolwarm_r",
            "copper",
            "copper_r",
            "cubehelix",
            "cubehelix_r",
            "flag",
            "flag_r",
            "gist_earth",
            "gist_earth_r",
            "gist_gray",
            "gist_gray_r",
            "gist_grey",
            "gist_heat",
            "gist_heat_r",
            "gist_ncar",
            "gist_ncar_r",
            "gist_rainbow",
            "gist_rainbow_r",
            "gist_stern",
            "gist_stern_r",
            "gist_yarg",
            "gist_yarg_r",
            "gist_yerg",
            "gnuplot",
            "gnuplot2",
            "gnuplot2_r",
            "gnuplot_r",
            "gray",
            "gray_r",
            "grey",
            "hot",
            "hot_r",
            "hsv",
            "hsv_r",
            "inferno",
            "inferno_r",
            "jet",
            "jet_r",
            "magma",
            "magma_r",
            "nipy_spectral",
            "nipy_spectral_r",
            "ocean",
            "ocean_r",
            "pink",
            "pink_r",
            "plasma",
            "plasma_r",
            "prism",
            "prism_r",
            "rainbow",
            "rainbow_r",
            "seismic",
            "seismic_r",
            "spring",
            "spring_r",
            "summer",
            "summer_r",
            "tab10",
            "tab10_r",
            "tab20",
            "tab20_r",
            "tab20b",
            "tab20b_r",
            "tab20c",
            "tab20c_r",
            "terrain",
            "terrain_r",
            "turbo",
            "turbo_r",
            "twilight",
            "twilight_r",
            "twilight_shifted",
            "twilight_shifted_r",
            "viridis",
            "viridis_r",
            "winter",
            "winter_r",
        ]
        self.colormap_menu = OptionMenu(parent, self.colormap_var, *colormaps)
        self.colormap_menu.grid(
            row=row, column=1, padx=2, sticky="ew"
        # 添加sticky参数
 
        row += 1
        Label(parent, text="保存路径", font=("微软雅黑", 10)).grid(
            row=row, column=0, sticky="w", pady=2
        )
        self.save_path_var = StringVar()
        Entry(
            parent,
            textvariable=self.save_path_var,
            state="readonly",
            width=20,
            font=("微软雅黑", 10),
        ).grid(row=row, column=1, columnspan=3, padx=2)
        self.browse_button = Button(
            parent, text="浏览...", command=self.select_save_path, font=("微软雅黑", 9)
        )
        self.browse_button.grid(row=row, column=4, padx=2)
 
        row += 1
        self.generate_button = Button(
            parent,
            text="开始生成",
            command=self.toggle_generation,
            font=("微软雅黑", 10, "bold"),
            bg="#4CAF50",
            fg="white",
        )
        self.generate_button.grid(row=row, column=0, columnspan=5, pady=10, sticky="we")
 
        # 创建区域切换按钮
        self.create_buttons(parent)
 
    def copy_center_to_c(self):
        """将焦点数值坐标复制到 c 坐标输入框"""
        try:
            # 获取焦点数值坐标
            center_x = self.center_x_entry.get()
            center_y = self.center_y_entry.get()
 
            # 将焦点数值坐标设置到 c 坐标输入框
            self.c_x_entry.config(state="normal")
            self.c_x_entry.delete(0, "end")
            self.c_x_entry.insert(0, center_x)
 
            self.c_y_entry.config(state="normal")
            self.c_y_entry.delete(0, "end")
            self.c_y_entry.insert(0, center_y)
 
            # 如果朱利亚模式未启用,自动启用
            if not self.julia_var.get():
                self.julia_var.set(True)
                self.toggle_julia_mode()
 
            messagebox.showinfo("复制成功", "焦点坐标已复制到 c 坐标")
        except Exception as e:
            messagebox.showerror("复制失败", f"复制坐标时出错: {str(e)}")
 
    def toggle_julia_mode(self):
        """切换朱利亚模式"""
        if self.julia_var.get():
            # 启用c坐标输入框
            self.c_x_entry.config(state="normal")
            self.c_y_entry.config(state="normal")
        else:
            # 禁用c坐标输入框
            self.c_x_entry.config(state="disabled")
            self.c_y_entry.config(state="disabled")
 
    def setup_plot(self):
        """初始化绘图区域"""
        self.fig = plt.figure(figsize=(8, 6), dpi=200)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        self.canvas.get_tk_widget().grid(
            row=0, column=1, sticky="nsew", padx=10, pady=10
        )
        self.canvas.mpl_connect("resize_event", self.on_resize)  # 添加窗口大小调整事件
        self.canvas.mpl_connect(
            "button_press_event", self.on_canvas_click
        # 添加鼠标点击事件
        self.canvas.mpl_connect(
            "button_release_event", self.on_canvas_release
        # 鼠标松开事件
 
    def toggle_inputs(self, state):
        """切换输入控件状态"""
        entries = [
            self.width_entry,
            self.height_entry,
            self.center_x_entry,
            self.center_y_entry,
            self.c_x_entry,
            self.c_y_entry,
            self.scale_entry,
            self.max_iter_entry,
            self.num_images_entry,
            self.zoom_factor_entry,
            self.focus_x_entry,
            self.focus_y_entry,
            self.percentile_entry,
            self.precision_threshold_entry,
        ]
        for entry in entries:
            entry.config(state="normal" if state else "disabled")
        self.browse_button.config(state="normal" if state else "disabled")
 
    def select_save_path(self):
        """选择保存路径"""
        path = filedialog.askdirectory()
        if path:
            self.save_path_var.set(path)
 
    def update_progress(self):
        if not generating:
            return
        self.root.after(
            0, lambda: self.status_var.set(f"进度: {current_task}/{total_tasks}")
        )
 
        if current_task == total_tasks:
            self.status_var.set("生成完成")
        self.root.update_idletasks()
 
    def update_canvas(self, output, metadata):
        """更新画布显示"""
        if output is None or "x_range" not in metadata or "y_range" not in metadata:
            print("跳过更新画布:缺少必要的数据或元数据。")
            return
        try:
            self.fig.clear()
            print("清除画布成功")
            selected_colormap = self.colormap_var.get()  # 获取用户选择的颜色映射
 
            ax = self.fig.add_subplot(111)
            # 使用默认值
            default_width = int(self.width_entry.get())  # 从输入框获取宽度
            default_height = int(self.height_entry.get())  # 从输入框获取高度
 
            ax.imshow(
                output,
                cmap=selected_colormap,
                extent=[0, default_width, 0, default_height],  # 使用默认的宽度和高度
                origin="lower",
            )
 
            # 计算迭代次数范围
            outmin_iter = int(np.min(output))
            outmax_iter = int(np.max(output))
 
            title = f"当前计算方法: {self.current_method}"
            title += f"点击放大,拖动移动\n"
            title += f"实际迭代范围: [{outmin_iter}, {outmax_iter}]\n"
            title += f"计算时间: {metadata['compute_time']:.2f}s | 当前精度: {metadata['precision']}位 (第{metadata['task_id']}帧)"
 
            ax.set_title(title)
            # ax.set_xlabel("实部")
            # ax.set_ylabel("虚部")
            self.canvas.draw()
        except Exception as e:
            messagebox.showerror("界面更新错误", str(e))
        self.root.update()
 
    def on_resize(self, event):
        """窗口大小调整时的回调函数"""
        self.update_canvas(self.current_image, self.current_metadata)
        if self.current_image is not None and self.current_metadata:
            self.update_canvas(self.current_image, self.current_metadata)
 
    def toggle_generation(self):
        """启动/停止生成"""
        global generating
        if generating:
            generating = False
            self.generate_button.config(text="开始生成", state="normal")
            self.status_var.set("已终止")
            self.toggle_inputs(True)
            self.toggle_julia_mode()
            # 强行终止 Mandelbrot.exe 进程
            if self.mandelbrot_process and self.mandelbrot_process.poll() is None:
                subprocess.run("taskkill /F /IM Mandelbrot.exe", shell=True)
 
        else:
            self.start_generation()
 
    def start_generation(self):
        """开始生成任务"""
        global generating, current_task, total_tasks
 
        try:
            # 验证用户输入的参数
            params = self.validate_parameters()
            print("参数验证完成,参数如下:")
            for key, value in params.items():
                print(f"    {key}: {value}")
 
            # 初始化生成任务
            self.initialize_generation(params)
            print("生成任务初始化完成。")
 
            # 创建任务队列
            tasks = self.create_tasks(params)
            print(f"任务队列创建完成,共有 {len(tasks)} 个任务。")
 
            # 处理任务队列
            # 启动后台线程
            self.generation_thread = Thread(
                target=self.process_tasks, args=(tasks, params)
            )
            self.generation_thread.start()
 
            print("所有任务处理完成。")
 
        except Exception as e:
            # 捕获异常并显示错误信息
            error_message = f"发生错误:\n{str(e)}\n{traceback.format_exc()}"
            print(f"生成过程中发生错误:\n{error_message}")
            messagebox.showerror("错误", error_message)
            self.cleanup_after_error()
 
    def validate_parameters(self):
        """验证输入参数"""
        params = {
            "width": self.width_entry.get(),  # 获取用户输入的图像宽度
            "height": self.height_entry.get(),  # 获取用户输入的图像高度
            "center_x": self.center_x_entry.get(),  # 获取用户输入的中心点 X 坐标
            "center_y": self.center_y_entry.get(),  # 获取用户输入的中心点 Y 坐标
            "c_x": self.c_x_entry.get(),  # 获取用户输入的中心点 X 坐标
            "c_y": self.c_y_entry.get(),  # 获取用户输入的中心点 Y 坐标
            "initial_scale": self.scale_entry.get(),  # 获取用户输入的初始缩放比例
            "max_iter": self.max_iter_entry.get(),  # 获取用户输入的最大迭代次数
            "num_images": self.num_images_entry.get(),  # 获取用户输入的生成图像数量
            "zoom_factor": self.zoom_factor_entry.get(),  # 获取用户输入的放大系数
            "save_path": self.save_path_var.get(),  # 获取用户选择的保存路径
            "focus_x": self.focus_x_entry.get(),  # 获取用户输入的焦点位置 X 比例
            "focus_y": self.focus_y_entry.get(),  # 获取用户输入的焦点位置 Y 比例
        }
 
        if any(
            v <= 0
            for v in [
                int(params["width"]),
                int(params["height"]),
                float(params["initial_scale"]),
                int(params["max_iter"]),
            ]
        ):
            raise ValueError("参数必须大于0")
        # if params['zoom_factor'] <= 1.0:
        # raise ValueError("放大系数必须大于1.0")
        if not os.path.exists(params["save_path"]):
            os.makedirs(params["save_path"], exist_ok=True)
        self.params = params  # 将 params 存储为类的属性
        return params
 
    def initialize_generation(self, params):
        """初始化生成任务"""
        global generating, current_task, total_tasks
        generating = True
        current_task = 0
        total_tasks = int(params["num_images"])
        self.generate_button.config(text="终止", state="normal")
        self.status_var.set("初始化中...")
        self.toggle_inputs(False)
        self.root.update()
 
    def create_tasks(self, params):
        """创建任务队列"""
        tasks = []
        current_scale = mpfr(params["initial_scale"])  # 使用 mpfr 类型
        zoom_factor = mpfr(params["zoom_factor"])
        focus_x = mpfr(params["focus_x"])
        focus_y = mpfr(params["focus_y"])
 
        # 设置 mpfr 的精度(可以根据需要调整)
        get_context().precision = 262144  # 例如,设置为 128 位二进制精度
 
        for i in range(int(params["num_images"])):
            # 使用 mpfr 进行高精度计算
            mpfr_scale = mpfr(current_scale) * mpfr(0.9)
            mpfr_log10 = log10(mpfr_scale)
            precision = max(1, int(-mpfr_log10))
 
            # 打印当前精度计算结果
            print(int(-mpfr_log10))
 
            # 重新设置 mpfr 的精度,多10位
            if (precision * 3.3) > 0:
                get_context().precision = int(precision * 3.324) + 16
 
            # 创建任务字典,所有数值均使用 mpfr 类型
            task = {
                "task_id": i + 1,
                "width": int(params["width"]),  # 整数类型保持不变
                "height": int(params["height"]),  # 整数类型保持不变
                "x_min": mpfr(params["center_x"])
                - current_scale / 2
                + (mpfr(0.5) - focus_x) * current_scale,
                "x_max": mpfr(params["center_x"])
                + current_scale / 2
                + (mpfr(0.5) - focus_x) * current_scale,
                "y_min": mpfr(params["center_y"])
                - current_scale / (2 * mpfr(params["width"]) / mpfr(params["height"]))
                + (mpfr(0.5) - focus_y)
                * current_scale
                / (mpfr(params["width"]) / mpfr(params["height"])),
                "y_max": mpfr(params["center_y"])
                + current_scale / (2 * mpfr(params["width"]) / mpfr(params["height"]))
                + (mpfr(0.5) - focus_y)
                * current_scale
                / (mpfr(params["width"]) / mpfr(params["height"])),
                "max_iter": int(params["max_iter"]),  # 整数类型保持不变
                "c_x": mpfr(params["c_x"]),
                "c_y": mpfr(params["c_y"]),
                "precision": precision,
            }
            current_scale /= mpfr(self.get_zoom_factor())
            print("task创建成功")
            tasks.append(task)  # 确保任务被添加到任务列表中
        return tasks
 
    def process_tasks(self, tasks, params):
        """处理任务队列"""
        global generating, current_task
        for task in tasks:
            if not generating:
                break
 
            current_task += 1
            self.status_var.set(f"正在生成第{current_task}帧...")
            self.update_progress()
 
            # 执行计算
            print("计算开始时间")
            print(time.time())
            start_time = time.time()
            precision_threshold = int(self.precision_threshold_entry.get())
            output = self.safe_compute_mandelbrot(
                task["x_min"],
                task["x_max"],
                task["y_min"],
                task["y_max"],
                task["width"],
                task["height"],
                task["max_iter"],
                precision_threshold,
                current_task,
                task["c_x"],
                task["c_y"],
                task["precision"],
            )
            compute_time = time.time() - start_time
            print("计算完成时间")
            print(time.time())
            # 保存结果
            print("保存前时间")
            print(time.time())
            # 假设 params 和 task 已经定义,output 是要保存的图像数据
            filename_base = os.path.join(params["save_path"], "Mandelbrot")
            file_extension = ".png"
            filename = f"{filename_base}{file_extension}"
            counter = 1
 
            # 检查文件是否存在,如果存在则添加后缀
            while os.path.exists(filename):
                filename = f"{filename_base}_{str(counter).zfill(7)}{file_extension}"
                counter += 1
 
                selected_colormap = self.colormap_var.get()  # 获取用户选择的颜色映射
 
            # 保存图像
            plt.imsave(filename, output, cmap=selected_colormap, origin="lower")
            print(f"图像已保存为: {filename}")
            print("保存完成时间")
            print(time.time())
 
            # 更新界面
            print("更新界面开始时间")
            print(time.time())
            metadata = {
                "x_range": (task["x_min"], task["x_max"]),
                "y_range": (task["y_min"], task["y_max"]),
                "task_id": task["task_id"],
                "compute_time": compute_time,
                "precision": task["precision"],
            }
            self.current_image = output
            self.current_metadata = metadata
 
            # 更新界面使用after方法
            self.root.after(0, self.update_canvas, output, metadata)
 
            print("更新完界面时间")
            print(time.time())
        # 清理状态
        generating = False
        self.status_var.set("生成完成" if current_task == total_tasks else "已终止")
        self.generate_button.config(text="开始生成", state="normal")
        self.toggle_inputs(True)
        self.toggle_julia_mode()
 
    def cleanup_after_error(self):
        """出错后清理"""
        global generating
        generating = False
        if hasattr(self, "generation_thread"):
            self.generation_thread.join(0)
        self.generate_button.config(text="开始生成", state="normal")
        self.status_var.set("就绪")
        self.toggle_inputs(True)
        self.toggle_julia_mode()
 
 
if __name__ == "__main__":
 
    root = Tk()
    app = MandelbrotGenerator(root)
 
    def on_close():
        global generating  # 明确声明使用全局变量
        generating = False
        root.destroy()
        # 强制退出进程(针对某些终端环境)
        os._exit(0)
 
    root.protocol("WM_DELETE_WINDOW", on_close)  # 使用自定义的关闭函数
    root.mainloop()

免费评分

参与人数 4吾爱币 +10 热心值 +4 收起 理由
fllc + 2 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
风之暇想 + 7 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!
wwr21 + 1 + 1 谢谢@Thanks!
confiant + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

lujucom 发表于 2025-2-27 10:46
majianping 发表于 2025-2-26 22:30
大佬 我AI写了一个PY代码  正常能用了,怎么转化成这种 EXE的文件呢

将 Python 代码转换成 EXE 文件可以让你在没有安装 Python 环境的 Windows 系统上直接运行程序,常见的工具有 PyInstaller、cx_Freeze 和 Nuitka,下面分别介绍使用这些工具的具体方法。
使用 PyInstaller
1. 安装 PyInstaller
打开命令提示符(CMD)或 PowerShell,执行以下命令来安装 PyInstaller:
bash
pip install pyinstaller
2. 转换代码
在命令行中,切换到包含 Python 代码文件的目录,然后执行以下命令:
bash
pyinstaller your_script.py
your_script.py 是你要转换的 Python 脚本文件名。
执行上述命令后,PyInstaller 会在当前目录下创建一个 dist 文件夹和一个 build 文件夹。dist 文件夹中包含生成的 EXE 文件,build 文件夹包含构建过程中产生的临时文件。
3. 常用选项
生成单个 EXE 文件:如果你希望生成一个单独的 EXE 文件,而不是包含多个依赖文件的文件夹,可以使用 --onefile 选项:
bash
pyinstaller --onefile your_script.py
隐藏命令行窗口:对于 GUI 程序,你可能不希望在运行时显示命令行窗口,可以使用 --noconsole 选项:
bash
pyinstaller --onefile --noconsole your_script.py
mycc11 发表于 2025-2-26 21:56
majianping 发表于 2025-2-26 22:30
大佬 我AI写了一个PY代码  正常能用了,怎么转化成这种 EXE的文件呢
2911 发表于 2025-2-27 01:25
可以制作分形艺术图片
 楼主| 858983646 发表于 2025-2-27 02:01
majianping 发表于 2025-2-26 22:30
大佬 我AI写了一个PY代码  正常能用了,怎么转化成这种 EXE的文件呢

nuitka,pyinstaller等 编译,也可以问ai,编译命令代码保存bat同目录运行
dk19910806 发表于 2025-2-27 06:59
感谢楼主分享
wzyzhuce 发表于 2025-2-27 08:13
感谢楼主分享,学习
神秘伞 发表于 2025-2-27 08:17
感谢分享!
lovehfs 发表于 2025-2-27 08:27
感谢楼主的分享,试了一下很有趣。
deewangs 发表于 2025-2-27 08:30
感谢分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-4-3 03:46

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表