forked from agranitsa-star/Scientific-Data-Analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
974 lines (694 loc) · 37.1 KB
/
main.py
File metadata and controls
974 lines (694 loc) · 37.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import numpy as np
import ast
class DataTableApp:
def __init__(self, root):
self.root = root
self.root.title("Редактор экспериментальных данных")
self.root.geometry("1000x700")
self.root.attributes('-fullscreen', True)
self.root.bind('<Escape>', lambda e: self.root.attributes('-fullscreen', False))
self.root.bind('<F11>', self.toggle_fullscreen)
self.last_click_x = 0
self.last_click_y = 0
self.columns = {}
self.column_names = []
self.constants = {}
self.history = []
self.history_index = -1
self.max_history = 50
self.root.bind('<Control-z>', self.undo)
self.root.bind('<Control-y>', self.redo)
self.root.bind('<Command-z>', self.undo)
self.root.bind('<Command-y>', self.redo)
self.create_widgets()
def toggle_fullscreen(self, event=None):
"""Переключает полноэкранный режим"""
is_fullscreen = self.root.attributes('-fullscreen')
self.root.attributes('-fullscreen', not is_fullscreen)
def create_widgets(self):
self.main_pane = ttk.PanedWindow(self.root, orient=tk.HORIZONTAL)
self.main_pane.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
data_frame = ttk.Frame(self.main_pane)
self.data_frame = data_frame
control_frame = ttk.Frame(data_frame)
control_frame.pack(fill=tk.X, padx=10, pady=5)
ttk.Button(control_frame, text="Загрузить файл", command=self.load_file).pack(side=tk.LEFT, padx=5)
ttk.Button(control_frame, text="Сохранить изменения", command=self.save_changes).pack(side=tk.LEFT, padx=5)
ttk.Button(control_frame, text="Константы", command=self.show_constants_dialog).pack(side=tk.LEFT, padx=5)
ttk.Button(control_frame, text="Новая колонка", command=self.create_new_column).pack(side=tk.LEFT, padx=5)
ttk.Button(control_frame, text="Графики", command=self.open_plot_window).pack(side=tk.RIGHT, padx=5)
table_frame = ttk.Frame(data_frame)
table_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
self.tree = ttk.Treeview(table_frame, show="headings")
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
v_scroll = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=self.tree.yview)
v_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.tree.configure(yscrollcommand=v_scroll.set)
h_scroll = ttk.Scrollbar(data_frame, orient=tk.HORIZONTAL, command=self.tree.xview)
h_scroll.pack(fill=tk.X, padx=10, pady=(0, 5))
self.tree.configure(xscrollcommand=h_scroll.set)
constants_frame = ttk.Frame(self.main_pane, width=180)
self.constants_frame = constants_frame
ttk.Label(constants_frame, text="Константы", font=("Arial", 10, "bold")).pack(pady=(10, 5))
constants_list_frame = ttk.Frame(constants_frame)
constants_list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
self.constants_tree = ttk.Treeview(constants_list_frame, columns=("name", "value"), show="headings", height=10)
self.constants_tree.heading("name", text="Имя")
self.constants_tree.heading("value", text="Значение")
self.constants_tree.column("name", width=70, anchor=tk.CENTER)
self.constants_tree.column("value", width=80, anchor=tk.CENTER)
self.constants_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
const_scroll = ttk.Scrollbar(constants_list_frame, orient=tk.VERTICAL, command=self.constants_tree.yview)
const_scroll.pack(side=tk.RIGHT, fill=tk.Y)
self.constants_tree.configure(yscrollcommand=const_scroll.set)
const_buttons_frame = ttk.Frame(constants_frame)
const_buttons_frame.pack(fill=tk.X, padx=10, pady=5)
ttk.Button(const_buttons_frame, text="+", width=3, command=self.add_constant).pack(side=tk.LEFT, padx=2)
ttk.Button(const_buttons_frame, text="-", width=3, command=self.remove_constant).pack(side=tk.LEFT, padx=2)
self.main_pane.add(data_frame, weight=1)
self.tree.bind("<Double-1>", self.on_double_click)
self.tree.bind("<Button-3>", self.show_context_menu)
self.context_menu = tk.Menu(self.root, tearoff=0)
self.context_menu.add_command(label="Изменить значение", command=self.edit_cell)
self.context_menu.add_command(label="Удалить колонку", command=self.delete_selected_column)
self.constants_tree.bind("<Double-1>", self.edit_constant)
def show_constants_dialog(self):
"""Показывает диалог для добавления новой константы"""
dialog = tk.Toplevel(self.root)
dialog.title("Добавить константу")
dialog.geometry("350x180")
dialog.transient(self.root)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Имя константы:").pack(pady=(10, 0))
name_var = tk.StringVar()
name_entry = ttk.Entry(dialog, textvariable=name_var)
name_entry.pack(pady=5, padx=20, fill=tk.X)
ttk.Label(dialog, text="Значение константы:").pack(pady=(10, 0))
value_var = tk.StringVar()
value_entry = ttk.Entry(dialog, textvariable=value_var)
value_entry.pack(pady=5, padx=20, fill=tk.X)
def add_and_close():
name = name_var.get().strip()
value_str = value_var.get().strip()
if not name or not value_str:
messagebox.showwarning("Предупреждение", "Имя и значение константы не могут быть пустыми")
return
if name in self.column_names:
messagebox.showerror("Ошибка", f"Имя '{name}' уже используется как название столбца")
return
if name in self.constants:
messagebox.showerror("Ошибка", f"Константа с именем '{name}' уже существует")
return
if not name.isidentifier():
messagebox.showerror(
"Ошибка",
"Имя константы должно быть корректным идентификатором:\n"
"— не может начинаться с цифры\n"
"— не может содержать пробелы или спецсимволы\n"
"— допускаются буквы, цифры и подчёркивания"
)
return
try:
value = float(value_str)
self.constants[name] = value
self.update_constants_display()
dialog.destroy()
except ValueError:
messagebox.showerror("Ошибка", "Неверный формат числа")
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Добавить", command=add_and_close).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
name_entry.focus_set()
def add_constant(self):
"""Добавляет новую константу через диалоговое окно"""
self.show_constants_dialog()
def remove_constant(self):
"""Удаляет выбранную константу"""
selected_item = self.constants_tree.focus()
if not selected_item:
messagebox.showinfo("Информация", "Выберите константу для удаления")
return
values = self.constants_tree.item(selected_item, "values")
if values:
name = values[0]
if name in self.constants:
del self.constants[name]
self.update_constants_display()
def edit_constant(self, event=None):
"""Редактирует значение выбранной константы"""
selected_item = self.constants_tree.focus()
if not selected_item:
return
values = self.constants_tree.item(selected_item, "values")
if not values:
return
name = values[0]
current_value = values[1]
new_value = simpledialog.askstring(
"Редактировать константу",
f"Введите новое значение для константы '{name}':",
initialvalue=current_value,
parent=self.root
)
if new_value is not None:
try:
float_value = float(new_value)
self.constants[name] = float_value
self.update_constants_display()
except ValueError:
messagebox.showerror("Ошибка", "Неверный формат числа")
def update_constants_display(self):
"""Обновляет отображение констант и управляет видимостью панели"""
for item in self.constants_tree.get_children():
self.constants_tree.delete(item)
for name, value in self.constants.items():
self.constants_tree.insert("", tk.END, values=(name, value))
current_panes = self.main_pane.panes()
if self.constants:
if str(self.constants_frame) not in [str(p) for p in current_panes]:
self.main_pane.add(self.constants_frame, weight=0)
else:
if str(self.constants_frame) in [str(p) for p in current_panes]:
self.main_pane.forget(self.constants_frame)
self.root.update_idletasks()
def load_file(self):
filename = filedialog.askopenfilename(
title="Выберите файл с данными",
filetypes=[("Text files", "*.txt"), ("All files", "*.*"), ("Data files", "*.dat")]
)
if not filename:
return
if self.columns:
self._save_state("Перед загрузкой нового файла")
new_columns = load_columns_dynamically(filename)
if not new_columns:
return
all_cyrillic = ['А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М',
'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ',
'Ы', 'Ь', 'Э', 'Ю', 'Я']
used_names = set(self.columns.keys())
next_letter_idx = 0
for name in all_cyrillic:
if name not in used_names:
break
next_letter_idx += 1
renamed_new_columns = {}
for old_name in new_columns.keys():
if next_letter_idx < len(all_cyrillic):
new_name = all_cyrillic[next_letter_idx]
next_letter_idx += 1
else:
new_name = f"СТОЛБЕЦ_{len(self.columns) + len(renamed_new_columns) + 1}"
renamed_new_columns[new_name] = new_columns[old_name]
self.columns.update(renamed_new_columns)
self.column_names = list(self.columns.keys())
self._normalize_column_lengths()
self.display_data()
self._save_state("Загрузка файла")
def _normalize_column_lengths(self):
"""Обрезает все колонки до минимальной длины"""
if not self.columns:
return
min_length = min(len(col) for col in self.columns.values())
for name in self.columns:
self.columns[name] = self.columns[name][:min_length]
if min_length == 0:
messagebox.showwarning("Предупреждение", "Один из файлов пуст!")
def display_data(self):
"""Отображает данные в таблице с колонкой индексов"""
self.tree.delete(*self.tree.get_children())
self.tree["columns"] = []
if self.columns:
self.tree["columns"] = ["index"] + self.column_names
self.tree.heading("index", text="№", anchor=tk.CENTER)
self.tree.column("index", width=40, anchor=tk.CENTER, stretch=False)
for col in self.column_names:
self.tree.heading(col, text=col, anchor=tk.CENTER)
self.tree.column(col, width=100, anchor=tk.CENTER)
num_rows = len(next(iter(self.columns.values())))
for i in range(num_rows):
row_values = [str(i + 1)]
for col in self.column_names:
value = self.columns[col][i]
if np.isnan(value):
row_values.append("NaN")
elif np.isinf(value):
row_values.append("inf" if value > 0 else "-inf")
else:
row_values.append(f"{value:.6f}")
self.tree.insert("", tk.END, values=row_values, iid=str(i))
def on_double_click(self, event):
"""Обработка двойного клика для редактирования ячейки"""
region = self.tree.identify("region", event.x, event.y)
if region == "heading":
col_id = self.tree.identify_column(event.x)
col_index = int(col_id.replace('#', '')) - 2
if 0 <= col_index < len(self.column_names):
self.rename_column_dialog(self.column_names[col_index])
elif region == "cell":
self.edit_cell(event)
def edit_cell(self, event=None):
"""Редактирование значения в ячейке"""
if not event:
selected_item = self.tree.focus()
if not selected_item:
return
selected_col = self.tree.identify_column(event.x) if event else '#1'
col_index = int(selected_col.replace('#', '')) - 2
row_id = selected_item
else:
row_id = self.tree.identify_row(event.y)
col_id = self.tree.identify_column(event.x)
col_index = int(col_id.replace('#', '')) - 2
if not row_id or col_index < 0:
return
current_value = self.tree.set(row_id, self.column_names[col_index])
entry = ttk.Entry(self.tree, width=10)
entry.insert(0, current_value)
entry.select_range(0, tk.END)
entry.focus()
x, y, width, height = self.tree.bbox(row_id, self.column_names[col_index])
entry.place(x=x, y=y, width=width, height=height)
def save_edit(event=None):
new_value = entry.get()
try:
float_value = float(new_value.replace(',', '.'))
col_name = self.column_names[col_index]
row_idx = int(row_id)
self.columns[col_name][row_idx] = float_value
self._save_state(f"Изменение ячейки [{row_idx + 1}, {col_name}]")
formatted_value = f"{float_value:.6f}"
self.tree.set(row_id, self.column_names[col_index], formatted_value)
except ValueError:
messagebox.showerror("Ошибка", "Введите корректное числовое значение")
finally:
entry.destroy()
def cancel_edit(event=None):
entry.destroy()
entry.bind("<Return>", save_edit)
entry.bind("<FocusOut>", save_edit)
entry.bind("<Escape>", lambda e: cancel_edit())
def delete_selected_column(self):
"""Удаляет выбранную колонку"""
region = self.tree.identify("region", self.last_click_x, self.last_click_y)
if region != "heading":
messagebox.showinfo("Информация", "Выберите заголовок колонки для удаления")
return
col_id = self.tree.identify_column(self.last_click_x)
col_index = int(col_id.replace('#', '')) - 2
if col_index < 0 or col_index >= len(self.column_names):
return
col_name = self.column_names[col_index]
result = messagebox.askyesno(
"Подтверждение",
f"Вы действительно хотите удалить колонку '{col_name}'?\nДля отмены действия воспользуйтесь Ctrl + Z."
)
if not result:
return
self._save_state(f"Удаление колонки '{col_name}'")
del self.columns[col_name]
del self.column_names[col_index]
self.display_data()
self._save_state(f"После удаление колонки")
def rename_column_dialog(self, old_name):
"""Диалог для переименования столбца"""
dialog = tk.Toplevel(self.root)
dialog.title("Переименовать столбец")
dialog.geometry("300x130")
dialog.transient(self.root)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text=f"Текущее имя: {old_name}").pack(pady=5)
new_name_var = tk.StringVar(value=old_name)
name_entry = ttk.Entry(dialog, textvariable=new_name_var)
name_entry.pack(pady=5, padx=20, fill=tk.X)
name_entry.select_range(0, tk.END)
name_entry.focus()
def confirm_rename():
new_name = new_name_var.get().strip()
new_name = new_name.replace(" ", "_")
if new_name and new_name != old_name:
if new_name in self.columns:
messagebox.showerror("Ошибка", "Столбец с таким именем уже существует")
return
self.columns[new_name] = self.columns.pop(old_name)
self.column_names = [new_name if name == old_name else name for name in self.column_names]
self.display_data()
dialog.destroy()
else:
messagebox.showwarning("Предупреждение", "Введите корректное новое имя")
ttk.Button(dialog, text="ОК", command=confirm_rename).pack(side=tk.LEFT, padx=20, pady=10)
ttk.Button(dialog, text="Отмена", command=dialog.destroy).pack(side=tk.RIGHT, padx=20, pady=10)
def show_context_menu(self, event):
"""Показать контекстное меню"""
self.last_click_x = event.x
self.last_click_y = event.y
region = self.tree.identify("region", event.x, event.y)
if region == "heading":
self.context_menu.post(event.x_root, event.y_root)
elif region == "cell":
self.context_menu.entryconfig(0, command=lambda: self.edit_cell(event))
self.context_menu.post(event.x_root, event.y_root)
def save_changes(self):
"""Сохранить изменения в файл"""
if not self.columns:
messagebox.showinfo("Информация", "Нет данных для сохранения")
return
filename = filedialog.asksaveasfilename(
defaultextension=".txt",
filetypes=[("Text files", "*.txt"), ("All files", "*.*")],
title="Сохранить данные"
)
if not filename:
return
try:
num_rows = len(next(iter(self.columns.values())))
with open(filename, 'w') as f:
f.write('\t'.join(self.column_names) + '\n')
for i in range(num_rows):
row = [str(self.columns[col][i]) for col in self.column_names]
f.write('\t'.join(row) + '\n')
messagebox.showinfo("Успех", "Данные успешно сохранены!")
except Exception as e:
messagebox.showerror("Ошибка", f"Не удалось сохранить файл:\n{e}")
def create_new_column(self):
"""Создаёт новую колонку на основе формулы с подсветкой синтаксиса"""
if not self.columns:
messagebox.showinfo("Информация", "Сначала загрузите данные")
return
dialog = tk.Toplevel(self.root)
dialog.title("Создать новую колонку")
dialog.geometry("500x200")
dialog.resizable(False, False)
dialog.transient(self.root)
dialog.grab_set()
self.center_dialog_over_parent(dialog)
ttk.Label(dialog, text="Имя новой колонки:").pack(pady=(10, 0))
name_var = tk.StringVar()
name_entry = ttk.Entry(dialog, textvariable=name_var)
name_entry.pack(pady=5, padx=20, fill=tk.X)
ttk.Label(dialog, text="Формула:").pack(pady=(10, 0))
formula_frame = ttk.Frame(dialog)
formula_frame.pack(pady=5, padx=20, fill=tk.X)
formula_text = tk.Text(
formula_frame,
height=1,
width=1,
font=("Consolas", 10),
wrap=tk.NONE,
yscrollcommand=None
)
formula_text.pack(side=tk.LEFT, fill=tk.X, expand=True)
h_scrollbar = ttk.Scrollbar(formula_frame, orient=tk.HORIZONTAL, command=formula_text.xview)
h_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
formula_text.configure(xscrollcommand=h_scrollbar.set)
formula_text.tag_configure("function", foreground="purple")
formula_text.tag_configure("variable", foreground="blue")
formula_text.tag_configure("number", foreground="green")
formula_text.tag_configure("operator", foreground="black")
formula_text.tag_configure("paren", foreground="gray")
formula_text.tag_configure("comma", foreground="gray")
def show_help():
help_window = tk.Toplevel(dialog)
help_window.title("Справка по формулам")
help_window.geometry("600x500")
help_window.transient(dialog)
help_window.grab_set()
text_frame = ttk.Frame(help_window)
text_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
text_widget = tk.Text(text_frame, wrap=tk.WORD, font=("Consolas", 10))
scrollbar = ttk.Scrollbar(text_frame, orient=tk.VERTICAL, command=text_widget.yview)
text_widget.configure(yscrollcommand=scrollbar.set)
text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
help_text = """СПРАВКА ПО ФОРМУЛАМ
Доступные переменные:
• Все названия ваших колонок (например: U, I, t, А, Б)
• Все ваши константы (например: C, R, g)
Математические функции (можно использовать без "np."):
ОСНОВНЫЕ ФУНКЦИИ:
sqrt(x) — квадратный корень
abs(x) — модуль
exp(x) — экспонента (e^x)
log(x) — натуральный логарифм
log10(x) — десятичный логарифм
log2(x) — логарифм по основанию 2
СТЕПЕННЫЕ ФУНКЦИИ:
power(x, y) — x в степени y
square(x) — x²
cube(x) — x³
ТРИГОНОМЕТРИЧЕСКИЕ ФУНКЦИИ:
sin(x), cos(x), tan(x)
arcsin(x), arccos(x), arctan(x)
arctan2(y, x)
ГИПЕРБОЛИЧЕСКИЕ ФУНКЦИИ:
sinh(x), cosh(x), tanh(x)
arcsinh(x), arccosh(x), arctanh(x)
СТАТИСТИЧЕСКИЕ ФУНКЦИИ:
mean(x) — среднее значение
std(x) — стандартное отклонение
max(x), min(x) — максимум и минимум
ОПЕРАТОРЫ:
+ - * / ** % //
== != < > <= >=
& | ^ ~ (побитовые)
ПРИМЕРЫ:
U * I → мощность
sqrt(U**2 + I**2) → модуль комплексного числа
log(I) / t → темп роста
exp(-t / tau) → экспоненциальный спад
sin(2 * pi * f * t) → гармонический сигнал
(U - mean(U)) / std(U) → стандартизация
ВАЖНО:
• Все вычисления выполняются поэлементно
• Результат должен иметь ту же длину, что и исходные данные
• Используйте точку как разделитель десятичных дробей
"""
text_widget.insert(tk.END, help_text)
text_widget.config(state=tk.DISABLED)
available_functions = {
'sqrt', 'abs', 'exp', 'log', 'log10', 'log2',
'power', 'square', 'cube',
'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan', 'arctan2',
'sinh', 'cosh', 'tanh', 'arcsinh', 'arccosh', 'arctanh',
'mean', 'std', 'max', 'min'
}
available_variables = set(self.column_names) | set(self.constants.keys())
available_constants = {'pi', 'e'}
def highlight_syntax(event=None):
"""Подсвечивает синтаксис в реальном времени"""
content = formula_text.get("1.0", tk.END)
formula_text.tag_remove("function", "1.0", tk.END)
formula_text.tag_remove("variable", "1.0", tk.END)
formula_text.tag_remove("number", "1.0", tk.END)
formula_text.tag_remove("operator", "1.0", tk.END)
formula_text.tag_remove("paren", "1.0", tk.END)
formula_text.tag_remove("comma", "1.0", tk.END)
import re
for match in re.finditer(r'[(),]', content):
start = f"1.0+{match.start()}c"
end = f"1.0+{match.end()}c"
char = match.group()
if char in '()':
formula_text.tag_add("paren", start, end)
else:
formula_text.tag_add("comma", start, end)
operators = r'[\+\-\*/%<>=!&|^]+'
for match in re.finditer(operators, content):
if match.start() > 0:
prev_char = content[match.start() - 1]
if prev_char.isdigit() or prev_char == '.':
continue
start = f"1.0+{match.start()}c"
end = f"1.0+{match.end()}c"
formula_text.tag_add("operator", start, end)
numbers = r'-?\d+\.?\d*([eE][+-]?\d+)?'
for match in re.finditer(numbers, content):
start = f"1.0+{match.start()}c"
end = f"1.0+{match.end()}c"
formula_text.tag_add("number", start, end)
words = r'\b[a-zA-Z_]\w*\b'
for match in re.finditer(words, content):
word = match.group()
start = f"1.0+{match.start()}c"
end = f"1.0+{match.end()}c"
if word in available_functions:
formula_text.tag_add("function", start, end)
elif word in available_variables or word in available_constants:
formula_text.tag_add("variable", start, end)
formula_text.bind("<KeyRelease>", highlight_syntax)
formula_text.bind("<FocusIn>", highlight_syntax)
def get_formula_text():
"""Получает текст формулы"""
return formula_text.get("1.0", tk.END).strip()
button_frame = ttk.Frame(dialog)
button_frame.pack(pady=10)
ttk.Button(button_frame, text="Создать", command=lambda: self._confirm_create_column(
col_name=name_var.get().strip(),
formula=get_formula_text(),
dialog=dialog
)).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Отмена", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
ttk.Button(button_frame, text="Помощь", command=show_help).pack(side=tk.LEFT, padx=5)
name_entry.focus_set()
formula_text.bind("<FocusIn>", lambda e: highlight_syntax())
def _confirm_create_column(self, col_name, formula, dialog):
original_col_name = col_name
col_name = col_name.replace(' ', '_')
if not col_name or not formula:
messagebox.showwarning("Предупреждение", "Заполните все поля")
return
if not col_name.isidentifier():
messagebox.showerror(
"Ошибка",
"Имя колонки должно быть корректным идентификатором:\n"
"• Не может содержать пробелы\n"
"• Не может начинаться с цифры\n"
"• Допускаются буквы, цифры и подчёркивания"
)
return
if col_name in self.columns:
messagebox.showerror("Ошибка", f"Колонка '{col_name}' уже существует")
return
safe_dict = {}
for name, data in self.columns.items():
safe_dict[name] = data
for name, value in self.constants.items():
safe_dict[name] = value
math_functions = {
'sqrt': np.sqrt, 'abs': np.abs, 'exp': np.exp, 'log': np.log,
'log10': np.log10, 'log2': np.log2, 'power': np.power,
'square': np.square, 'cube': lambda x: np.power(x, 3),
'sin': np.sin, 'cos': np.cos, 'tan': np.tan,
'arcsin': np.arcsin, 'arccos': np.arccos, 'arctan': np.arctan,
'sinh': np.sinh, 'cosh': np.cosh, 'tanh': np.tanh,
'arcsinh': np.arcsinh, 'arccosh': np.arccosh, 'arctanh': np.arctanh,
'mean': np.mean, 'std': np.std, 'max': np.max, 'min': np.min,
'pi': np.pi, 'e': np.e,
}
safe_dict.update(math_functions)
safe_dict['np'] = np
try:
node = ast.parse(formula, mode='eval')
result = eval(compile(node, '<string>', 'eval'), {"__builtins__": {}}, safe_dict)
if isinstance(result, np.ndarray):
expected_length = len(next(iter(self.columns.values()))) if self.columns else 0
if result.shape != (expected_length,):
messagebox.showerror("Ошибка", f"Результат должен иметь длину {expected_length}")
return
self.columns[col_name] = result.astype(float)
self._save_state(f"Создание колонки '{col_name}'")
else:
if not self.columns:
messagebox.showerror("Ошибка", "Нет данных для создания колонки")
return
first_col = next(iter(self.columns.values()))
new_col = np.full_like(first_col, result, dtype=float)
self.columns[col_name] = new_col
self.column_names.append(col_name)
self.display_data()
dialog.destroy()
except Exception as e:
messagebox.showerror("Ошибка вычисления", f"Не удалось вычислить формулу:\n{e}")
def _save_state(self, action_name=""):
"""Сохраняет текущее состояние как новую точку в истории"""
if not self.columns and not self.constants:
return
state = {
'columns': {name: data.copy() for name, data in self.columns.items()},
'column_names': self.column_names.copy(),
'constants': self.constants.copy(),
'action': action_name
}
if self.history_index < len(self.history) - 1:
self.history = self.history[:self.history_index + 1]
self.history.append(state)
if len(self.history) > self.max_history:
self.history.pop(0)
else:
self.history_index += 1
def undo(self, event=None):
"""Отменяет последнее действие"""
if self.history_index <= 0:
return
self.history_index -= 1
self._apply_state(self.history[self.history_index])
print(f"Undo: {self.history[self.history_index]['action']}")
return True
def redo(self, event=None):
"""Возвращает отменённое действие"""
if self.history_index >= len(self.history) - 1:
return False
self.history_index += 1
self._apply_state(self.history[self.history_index])
print(f"Redo: {self.history[self.history_index]['action']}")
return True
def _apply_state(self, state):
"""Применяет сохранённое состояние"""
self.columns = {name: data.copy() for name, data in state['columns'].items()}
self.column_names = state['column_names'].copy()
self.constants = state['constants'].copy()
self.display_data()
self.update_constants_display()
def open_plot_window(self):
"""Открывает окно для работы с графиками"""
if not self.columns:
messagebox.showinfo("Информация", "Сначала загрузите данные")
return
from Plot import PlotWindow
PlotWindow(self, self.columns)
def center_dialog_over_parent(self, dialog):
"""Центрирует диалог над основным окном"""
dialog.update_idletasks()
dialog_width = dialog.winfo_width()
dialog_height = dialog.winfo_height()
parent_x = self.root.winfo_x()
parent_y = self.root.winfo_y()
parent_width = self.root.winfo_width()
parent_height = self.root.winfo_height()
x = parent_x + (parent_width - dialog_width) // 2
y = parent_y + (parent_height - dialog_height) // 2
dialog.geometry(f'+{x}+{y}')
def load_columns_dynamically(filename):
try:
data = np.genfromtxt(
filename,
skip_header=1,
missing_values=['бесконечность', 'inf', 'Inf', 'INF', 'NaN', 'nan', 'NAN', 'none', 'None', '-'],
filling_values=np.nan,
dtype=float,
delimiter=None
)
if data.ndim == 1:
data = data.reshape(-1, 1)
cyrillic_letters = ['А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М',
'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ',
'Ы', 'Ь', 'Э', 'Ю', 'Я']
columns = {}
num_columns = data.shape[1]
for i in range(min(num_columns, len(cyrillic_letters))):
columns[cyrillic_letters[i]] = data[:, i]
for i in range(len(cyrillic_letters), num_columns):
columns[f"СТОЛБЕЦ_{i + 1}"] = data[:, i]
nan_count = np.sum(np.isnan(data))
if nan_count > 0:
print(f"Внимание: обнаружено {nan_count} некорректных значений, замененных на NaN")
print(f"Загружено столбцов: {num_columns}")
print("Текущие имена столбцов:", list(columns.keys()))
return columns
except FileNotFoundError:
messagebox.showerror("Ошибка", f"Файл {filename} не найден")
return {}
except Exception as e:
messagebox.showerror("Ошибка загрузки",
f"Не удалось загрузить файл:\n{e}\n\n"
"Попробуйте проверить формат файла или использовать другой разделитель")
return {}
if __name__ == "__main__":
root = tk.Tk()
app = DataTableApp(root)
root.mainloop()