move out the read_data, made a customtextedit, to override Ctrl+D

This commit is contained in:
Ryan Tang 2024-11-06 16:50:48 -05:00
parent 5b4fdba054
commit f5a055cf07
6 changed files with 124 additions and 88 deletions

4
.gitignore vendored
View File

@ -7,4 +7,6 @@ Cleopatra/Isotope
Cleopatra/PlotTGraphTObjArray Cleopatra/PlotTGraphTObjArray
__pycache__ __pycache__
IAEA_NuclearData.csv IAEA_NuclearData.csv
*.txt

View File

@ -0,0 +1,54 @@
#!/usr/bin/python3
from PyQt6.QtWidgets import QTextEdit
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QTextCharFormat, QSyntaxHighlighter
class PythonHighlighter(QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
# Define formatting for comments
self.comment_format = QTextCharFormat()
self.comment_format.setForeground(Qt.GlobalColor.darkGreen)
def highlightBlock(self, text):
# Highlight comments
if text.startswith("#"):
self.setFormat(0, len(text), self.comment_format)
if text.startswith("$"):
self.setFormat(0, len(text), self.comment_format)
if text.startswith("0"):
self.setFormat(0, len(text), self.comment_format)
class CustomTextEdit(QTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
font = QFont("Courier New", 10) # You can adjust the size as needed
self.setFont(font)
self.highlighter = PythonHighlighter(self.document())
def keyPressEvent(self, event):
# Check if Ctrl+D is pressed
if event.key() == Qt.Key.Key_D and event.modifiers() == Qt.KeyboardModifier.ControlModifier:
self.duplicate_line()
event.accept() # Prevent the default behavior of Ctrl+D
else:
super().keyPressEvent(event) # Call the base class to handle other keys
def duplicate_line(self):
cursor = self.textCursor()
# Select the current line under the cursor
cursor.select(cursor.SelectionType.LineUnderCursor)
line_text = cursor.selectedText()
# Move the cursor to the end of the line and insert a newline with duplicated text
cursor.movePosition(cursor.MoveOperation.EndOfLine)
cursor.insertText("\n" + line_text)
# Update the cursor position after inserting the text
self.setTextCursor(cursor)

View File

@ -2,6 +2,39 @@
import numpy as np import numpy as np
def read_DWBA(fileName):
dataX = [] # List for the first column
data = [] # 2D list for other columns
headers = [] # List to store headers
with open(fileName, 'r') as file:
header_found = False # Flag to indicate if the header has been found
for line in file:
# Skip lines that start with '#' and empty lines
if line.startswith('#') or not line.strip():
continue
if not header_found:
headers = line.split() # Use the split parts as headers
header_found = True # Set the flag to True to skip this block in future iterations
# print(f"ELab parts found: {elab_parts}") # Print or process this as needed
continue
# Split the line by whitespace
parts = line.split()
if len(parts) > 0: # Make sure there is at least one column
dataX.append(float(parts[0])) # First column
# Append the rest of the columns to data
if len(data) == 0:
# Initialize the data array with the right number of sublists
data = [[] for _ in range(len(parts) - 1)]
for i in range(len(parts) - 1):
data[i].append(float(parts[i + 1])) # Rest of the columns
# print(self.headers)
return headers, dataX, data
def extract_xsec(read_file, index_for_elastic): def extract_xsec(read_file, index_for_elastic):
# index_for_elastic = 1 ; for Ratio # index_for_elastic = 1 ; for Ratio
# index_for_elastic = 2 ; for Total # index_for_elastic = 2 ; for Total

View File

@ -7,7 +7,8 @@ from PyQt6.QtWidgets import (
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from matplotlib.backends.backend_qtagg import NavigationToolbar2QT as NavigationToolbar from matplotlib.backends.backend_qtagg import NavigationToolbar2QT as NavigationToolbar
from matplotlib import get_backend
from ExtractXsecPy import read_DWBA
# Set backend to a Qt-compatible one # Set backend to a Qt-compatible one
plt.switch_backend('QtAgg') # Or use 'Qt5Agg' if there are still issues plt.switch_backend('QtAgg') # Or use 'Qt5Agg' if there are still issues
@ -47,35 +48,7 @@ class MatPlotLibWindow(QWidget):
layout.addWidget(self.canvas, 2, 0, 5, 3) layout.addWidget(self.canvas, 2, 0, 5, 3)
def read_data(self,file_path): def read_data(self,file_path):
self.x = [] # List for the first column self.headers, self.x, self.data = read_DWBA(file_path)
self.data = [] # 2D list for other columns
self.headers = [] # List to store headers
with open(file_path, 'r') as file:
header_found = False # Flag to indicate if the header has been found
for line in file:
# Skip lines that start with '#' and empty lines
if line.startswith('#') or not line.strip():
continue
if not header_found:
self.headers = line.split() # Use the split parts as headers
header_found = True # Set the flag to True to skip this block in future iterations
# print(f"ELab parts found: {elab_parts}") # Print or process this as needed
continue
# Split the line by whitespace
parts = line.split()
if len(parts) > 0: # Make sure there is at least one column
self.x.append(float(parts[0])) # First column
# Append the rest of the columns to data
if len(self.data) == 0:
# Initialize the data array with the right number of sublists
self.data = [[] for _ in range(len(parts) - 1)]
for i in range(len(parts) - 1):
self.data[i].append(float(parts[i + 1])) # Rest of the columns
# print(self.headers)
def plot_matplotlib_graph(self): def plot_matplotlib_graph(self):
self.ax.clear() self.ax.clear()

View File

@ -10,6 +10,8 @@ from PyQt6.QtCore import QUrl
from PyQt6.QtWebEngineWidgets import QWebEngineView from PyQt6.QtWebEngineWidgets import QWebEngineView
import plotly.graph_objects as go import plotly.graph_objects as go
from ExtractXsecPy import read_DWBA
class PlotWindow(QWidget): class PlotWindow(QWidget):
def __init__(self, XsecFile): def __init__(self, XsecFile):
super().__init__() super().__init__()
@ -44,35 +46,7 @@ class PlotWindow(QWidget):
self.plot_plotly_graph() self.plot_plotly_graph()
def read_data(self,file_path): def read_data(self,file_path):
self.x = [] # List for the first column self.headers, self.x, self.data = read_DWBA(file_path)
self.data = [] # 2D list for other columns
self.headers = [] # List to store headers
with open(file_path, 'r') as file:
header_found = False # Flag to indicate if the header has been found
for line in file:
# Skip lines that start with '#' and empty lines
if line.startswith('#') or not line.strip():
continue
if not header_found:
self.headers = line.split() # Use the split parts as headers
header_found = True # Set the flag to True to skip this block in future iterations
# print(f"ELab parts found: {elab_parts}") # Print or process this as needed
continue
# Split the line by whitespace
parts = line.split()
if len(parts) > 0: # Make sure there is at least one column
self.x.append(float(parts[0])) # First column
# Append the rest of the columns to data
if len(self.data) == 0:
# Initialize the data array with the right number of sublists
self.data = [[] for _ in range(len(parts) - 1)]
for i in range(len(parts) - 1):
self.data[i].append(float(parts[i + 1])) # Rest of the columns
# print(self.headers)
def plot_plotly_graph(self): def plot_plotly_graph(self):

View File

@ -6,33 +6,18 @@ import subprocess
import sys import sys
from PyQt6.QtWidgets import ( from PyQt6.QtWidgets import (
QApplication, QMainWindow, QGridLayout, QPushButton, QApplication, QMainWindow, QGridLayout, QPushButton,
QComboBox, QWidget, QLabel, QLineEdit, QTextEdit, QCheckBox, QComboBox, QWidget, QLabel, QLineEdit, QCheckBox,
QFileDialog, QGroupBox, QVBoxLayout, QSpinBox, QDoubleSpinBox QFileDialog, QGroupBox, QVBoxLayout, QSpinBox, QDoubleSpinBox
) )
from PyQt6.QtCore import Qt from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont, QTextCursor, QTextCharFormat, QSyntaxHighlighter from PyQt6.QtGui import QTextCursor
from CustomTextEdit import CustomTextEdit
from ExtractXsecPy import extract_xsec from ExtractXsecPy import extract_xsec
from ExWindow import ExWindow from ExWindow import ExWindow
from MatPlotLibWindow import MatPlotLibWindow from MatPlotLibWindow import MatPlotLibWindow
class PythonHighlighter(QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
# Define formatting for comments
self.comment_format = QTextCharFormat()
self.comment_format.setForeground(Qt.GlobalColor.darkGreen)
def highlightBlock(self, text):
# Highlight comments
if text.startswith("#"):
self.setFormat(0, len(text), self.comment_format)
if text.startswith("$"):
self.setFormat(0, len(text), self.comment_format)
if text.startswith("0"):
self.setFormat(0, len(text), self.comment_format)
################################################## MainWindow ################################################## MainWindow
class MyWindow(QMainWindow): class MyWindow(QMainWindow):
@ -43,7 +28,9 @@ class MyWindow(QMainWindow):
self.setGeometry(100, 100, 1000, 700) self.setGeometry(100, 100, 1000, 700)
self.setMinimumSize(400, 600) self.setMinimumSize(400, 600)
self.DWBAFileName = "DWBA" self.lastDWBARecord = "lastDWBA.txt"
self.DWBAFileName = ""
self.LoadLastOpenDWBASource()
self.bashResult = "" self.bashResult = ""
self.plot_window = MatPlotLibWindow() self.plot_window = MatPlotLibWindow()
self.Ex_window = ExWindow() self.Ex_window = ExWindow()
@ -81,7 +68,7 @@ class MyWindow(QMainWindow):
self.sbAngMax.setMinimum(0) self.sbAngMax.setMinimum(0)
self.sbAngMax.setMaximum(180) self.sbAngMax.setMaximum(180)
self.sbAngSize = QDoubleSpinBox() self.sbAngSize = QDoubleSpinBox()
self.sbAngSize.setValue(1) self.sbAngSize.setValue(0.2)
self.sbAngSize.setMinimum(0.1) self.sbAngSize.setMinimum(0.1)
self.sbAngSize.setMaximum(10) self.sbAngSize.setMaximum(10)
self.sbAngSize.setSingleStep(0.5) self.sbAngSize.setSingleStep(0.5)
@ -171,12 +158,7 @@ class MyWindow(QMainWindow):
self.bnSaveFile = QPushButton("Save File") self.bnSaveFile = QPushButton("Save File")
self.bnSaveFile.clicked.connect(self.SaveFile) self.bnSaveFile.clicked.connect(self.SaveFile)
self.text_edit = QTextEdit() self.text_edit = CustomTextEdit(self)
self.text_edit.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
font = QFont("Courier New", 10) # You can adjust the size as needed
self.text_edit.setFont(font)
self.highlighter = PythonHighlighter(self.text_edit.document())
self.leStatus = QLineEdit("") self.leStatus = QLineEdit("")
self.leStatus.setReadOnly(True) self.leStatus.setReadOnly(True)
@ -203,7 +185,20 @@ class MyWindow(QMainWindow):
container.setLayout(layout) container.setLayout(layout)
self.setCentralWidget(container) self.setCentralWidget(container)
self.text_edit.setFocus()
####################################### methods ####################################### methods
def LoadLastOpenDWBASource(self):
try :
with open(self.lastDWBARecord, 'r') as file:
self.DWBAFileName = file.readline().strip()
except:
self.DWBAFileName = "DWBA"
def SaveLastOpenDWBASource(self):
with open(self.lastDWBARecord, 'w') as file:
file.write(self.DWBAFileName)
def OnOffXsecOption(self): def OnOffXsecOption(self):
self.cbXsec.setEnabled(self.chkExtracrXsec.isChecked()) self.cbXsec.setEnabled(self.chkExtracrXsec.isChecked())
@ -213,6 +208,7 @@ class MyWindow(QMainWindow):
self.DWBAFileName = file_path self.DWBAFileName = file_path
self.leFileName.setText(self.DWBAFileName) self.leFileName.setText(self.DWBAFileName)
self.LoadFileToTextBox(self.DWBAFileName) self.LoadFileToTextBox(self.DWBAFileName)
self.SaveLastOpenDWBASource()
def LoadFileToTextBox(self, fileName, moveToButton = False): def LoadFileToTextBox(self, fileName, moveToButton = False):
# print(fileName) # print(fileName)
@ -221,7 +217,11 @@ class MyWindow(QMainWindow):
content = file.read() content = file.read()
self.text_edit.setText(content) self.text_edit.setText(content)
if moveToButton : if moveToButton :
self.text_edit.moveCursor(QTextCursor.MoveOperation.End) cursor = self.text_edit.textCursor()
cursor.movePosition(cursor.MoveOperation.End)
cursor.movePosition(cursor.MoveOperation.StartOfBlock)
self.text_edit.setTextCursor(cursor)
self.leStatus.setText(f"Loaded file : {fileName}") self.leStatus.setText(f"Loaded file : {fileName}")
self.leFileName.setText(fileName) self.leFileName.setText(fileName)
except Exception as e: except Exception as e: