How add fixed SNR nosie to dataset pytorch - pytorch

#代码
class MyData(Dataset):
def __init__(self,root,root_1,transform,col_list):
super(MyData, self).__init__()
self.df=pd.read_excel(root,usecols=col_list,header=None)
self.label = pd.read_excel(root_1,header=None)
self.transform=transform
self.weidu=len(col_list)
def __getitem__(self, item):
data=self.df.values[item*512:item*512+512]
data=data.T
# data =data.reshape((self.weidu,512),aix=1)
label=int(self.label.values[item])
data=torch.tensor(data) #先是通道数,再是数据
return self.transform(data),label
def __len__(self):
return (self.label.shape[0])
if name == 'main':
data=MyData(r"F:\jd_struct\data\test.xlsx",r"F:\jd_struct\data\test_label.xlsx",transform=transforms.Normalize(0.5,0.5),col_list=[1])
print(len(data))
img,tar=data[0]
print(img[0])

Related

Factory design pattern using __init_subclass__ python3

I didn't find any info about the implementation of the factory design pattern using __init_subclass__ to register the product and the class. What do you think about?
https://peps.python.org/pep-0487/
class Shape:
product = None
shapes_classes = {}
def __init_subclass__(cls, **kwargs):
cls.shapes_classes[cls.product] = cls
#classmethod
def create_shape(cls, product, *args, **kwargs):
return cls.shapes_classes[product](*args, **kwargs)
def __str__(self):
return f'I am {self.__class__.__name__} shape'
def area(self):
raise NotImplemented
class Triangle(Shape):
product = 'triangle'
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return self.height * self.base / 2
class Square(Shape):
product = 'square'
def __init__(self, base, ):
self.base = base
def area(self):
return self.base ** 2
#Usage:
Shape.shapes_classes
{'triangle': __main__.Triangle, 'square': __main__.Square}
triangle = Shape.create_shape(product='triangle',base=3,height=4)
square=Shape.create_shape(product='square',base=3)
print(triangle)
I am Triangle shape
print(square)
I am Square shape
triangle.area()
6.0
square.area()
9

subclass for NameError: name 'side_length' is not defined

class Polygon():
def __init__(self, side_lengths):
self.side_lengths = side_lengths
def perimeter(self):
return sum(self.side_lengths)
def __str__(self):
side_lengths = len(self.side_lengths)
return 'Polygon with {} sides'.format(side_lengths)
class Triangle(Polygon):
def __init__(self, side_lengths):
super().__init__(side_lengths)
def area(self):
s = sum(self.side_lengths)/2
a = self.side_lengths[0]
b = self.side_lengths[1]
c = self.side_lengths[2]
return float((s*(s-a)*(s-b)*(s-c)) ** 0.5)
def __str__(self):
return 'Triangle, Area: {:.2f} units^2, Perimeter: {:.2f} units'.format(self.area(), self.perimeter())
class Rectangle(Polygon):
def __init__(self, side_lengths):
super().__init__(side_lengths)
def area(self):
return float(self.side_lengths[0]*self.side_lengths[1])
def __str__(self):
return 'Rectangle, Area: {:.2f} units^2, Perimeter: {:.2f} units'.format(self.area(), self.perimeter())
class Square(Rectangle):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return float(4*side_length)
def __str__(self):
return 'Square, Area: {:.2f} units^2, Perimeter: {:.2f} units'.format(self.area(), self.perimeter())
For this program, I want to calculate the area of the square when the input of side_length is a float instead of a list, but name error occurs. How to deal with such issue?
class Square(Rectangle):
def __init__(self,side_length):
super().__init__(side_length)
I also tried this method, it does not work as well.

Completion with QLineEdit and QItemDelegate

I'm trying to implement the QCompleter example we can find in the widgets/tools/customcompleter sources.
What I want is when I'm typing some text, if there is some matches, the first completion line available is selected so if I hit the return key (and only if I hit it), the completion is done.
But in my code here, the line is never selected. I think my problem is located in the keyPressEvent but I don't know where. It is a minimal example, written in pyqt5 (5.10) and Python 3.5.2.
Any help is very appreciated :)
Best regards
import sys
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant
from PyQt5.QtWidgets import (QApplication, QCompleter, QItemDelegate,
QLineEdit, QMainWindow, QTableView)
class MyLineEdit(QLineEdit):
def __init__(self, parent=None, completer=None):
super().__init__(parent)
if completer:
self.setCompleter(completer)
def setCompleter(self, completer):
if completer:
completer.setWidget(self)
completer.setCompletionMode(QCompleter.PopupCompletion)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setModelSorting(
QCompleter.CaseSensitivelySortedModel)
completer.setMaxVisibleItems(15)
completer.activated.connect(self.insertCompletion)
super().setCompleter(completer)
def insertCompletion(self, completion):
completer = self.completer()
if completer and completer.widget() == self:
completer.widget().setText(completion)
def keyPressEvent(self, event):
completer = self.completer()
if event.key() in (Qt.Key_Return, Qt.Key_Enter,
Qt.Key_Tab, Qt.Key_Backtab):
self.returnPressed.emit()
if completer and completer.popup().isHidden():
return
super().keyPressEvent(event)
input_text = self.text()
if completer:
if not event.text():
completer.popup().hide()
return
if input_text and input_text != completer.completionPrefix():
completer.setCompletionPrefix(input_text)
completer.popup().setCurrentIndex(
completer.completionModel().index(0, 0))
class MyDelegate(QItemDelegate):
def __init__(self, parent):
super().__init__(parent)
def createEditor(self, parent, option, index):
strings = ('tata', 'tete', 'titi', 'toto', 'tutu')
completer = QCompleter(strings)
editor = MyLineEdit(parent)
editor.setCompleter(completer)
editor.editingFinished.connect(self.commitAndCloseEditor)
editor.returnPressed.connect(self.commitAndCloseEditor)
return editor
def commitAndCloseEditor(self):
editor = self.sender()
self.commitData.emit(editor)
self.closeEditor.emit(editor)
def setEditorData(self, editor, index):
if editor:
editor.setText(index.model().data[0])
def setModelData(self, editor, model, index):
if editor:
model.setData(index, editor.text(), Qt.EditRole)
class Model(QAbstractTableModel):
def __init__(self):
super().__init__()
self.data = ['hello']
def rowCount(self, parent=None):
return 1
def columnCount(self, parent=None):
return 1
def data(self, index, role):
if not index.isValid():
return QVariant()
if role in (Qt.DisplayRole, Qt.EditRole):
return self.data[0]
return QVariant()
def setData(self, index, value, role):
if role == Qt.EditRole:
self.data[0] = value
top_left = self.index(0, 0)
bottom_right = self.index(
self.rowCount() + 1, self.columnCount())
self.dataChanged.emit(top_left, bottom_right,
[Qt.DisplayRole])
return True
return False
def flags(self, index):
return Qt.ItemIsEditable | super().flags(index)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.model = Model()
self.table = QTableView()
self.table.setModel(self.model)
delegate = MyDelegate(self.table)
self.table.setItemDelegateForColumn(0, delegate)
def initUI(self):
self.show()
self.setCentralWidget(self.table)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.initUI()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5 import QtCore, QtWidgets
class LineEdit(QtWidgets.QLineEdit):
def __init__(self, *args, **kwargs):
QtWidgets.QLineEdit.__init__(self, *args, **kwargs)
self.multipleCompleter = None
def keyPressEvent(self, event):
QtWidgets.QLineEdit.keyPressEvent(self, event)
if not self.multipleCompleter:
return
c = self.multipleCompleter
if self.text() == "":
return
c.setCompletionPrefix(self.cursorWord(self.text()))
if len(c.completionPrefix()) < 1:
c.popup().hide()
return
c.complete()
def cursorWord(self, sentence):
p = sentence.rfind(" ")
if p == -1:
return sentence
return sentence[p + 1:]
def insertCompletion(self, text):
p = self.text().rfind(" ")
if p == -1:
self.setText(text)
else:
self.setText(self.text()[:p+1]+ text)
def setMultipleCompleter(self, completer):
self.multipleCompleter = completer
self.multipleCompleter.setWidget(self)
completer.activated.connect(self.insertCompletion)
def main():
app = QtWidgets.QApplication(sys.argv)
w = LineEdit()
completer = QtWidgets.QCompleter(['tata', 'tete', 'titi', 'toto', 'tutu'])
completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
w.setMultipleCompleter(completer)
w.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Finally found a solution. I used a QTextEdit, it does not work with QLineEdit, I don't know why. I still have a small problem, I can't close the completion popup when I hit the return key, so I must hit return key, twice. Not a big problem.
import sys
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant, pyqtSignal
from PyQt5.QtGui import QTextCursor, QTextOption
from PyQt5.QtWidgets import (QAbstractItemDelegate, QApplication, QCompleter,
QItemDelegate, QMainWindow, QTableView, QTextEdit)
class MyLineEdit(QTextEdit):
returnPressed = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptRichText(False)
self.setWordWrapMode(QTextOption.NoWrap)
self.setUndoRedoEnabled(False)
self.setTabChangesFocus(True)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.completer = None
self.textChanged.connect(self.textHasChanged)
def setCompleter(self, completer):
if completer:
completer.setWidget(self)
completer.setCompletionMode(QCompleter.PopupCompletion)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setModelSorting(
QCompleter.CaseSensitivelySortedModel)
completer.setMaxVisibleItems(15)
completer.activated.connect(self.insertCompletion)
self.completer = completer
def insertCompletion(self, completion):
print('>>> insertCompletion')
if self.completer and self.completer.widget() == self:
self.completer.widget().setPlainText(completion)
self.completer.widget().moveCursor(QTextCursor.EndOfLine)
self.completer.widget().ensureCursorVisible()
def focusInEvent(self, event):
print('>>> focusInEvent')
if self.completer:
self.completer.setWidget(self)
super().focusInEvent(event)
def keyPressEvent(self, event):
print('>>> keyPressEvent')
if self.completer and self.completer.popup().isVisible():
if event.key() in (Qt.Key_Return, Qt.Key_Enter,
Qt.Key_Tab, Qt.Key_Backtab, Qt.Key_Escape):
event.ignore()
return
else:
if event.key() in(Qt.Key_Return, Qt.Key_Enter):
self.returnPressed.emit()
return
super().keyPressEvent(event)
if not self.toPlainText():
self.completer.popup().hide()
return
self.completer.setCompletionPrefix(self.toPlainText())
self.completer.popup().setCurrentIndex(
self.completer.completionModel().index(0, 0))
self.completer.complete()
def textHasChanged(self):
# remove new lines and strip left blank characters
self.blockSignals(True)
cursor = self.textCursor()
self.setPlainText(' '.join(self.toPlainText().splitlines()).lstrip())
self.setTextCursor(cursor)
self.ensureCursorVisible()
self.blockSignals(False)
class MyDelegate(QItemDelegate):
def __init__(self, parent):
super().__init__(parent)
def createEditor(self, parent, option, index):
strings = ('tata', 'tada', 'tadam', 'tete', 'titi', 'toto', 'tutu')
completer = QCompleter(strings)
editor = MyLineEdit(parent)
editor.setCompleter(completer)
editor.returnPressed.connect(self.commitAndCloseEditor)
return editor
def commitAndCloseEditor(self):
print('>>> commitAndCloseEditor')
editor = self.sender()
self.commitData.emit(editor)
self.closeEditor.emit(editor)
def setEditorData(self, editor, index):
if editor:
editor.setText(index.model().data[0])
editor.selectAll()
def setModelData(self, editor, model, index):
if editor:
model.setData(index, editor.toPlainText(), Qt.EditRole)
class Model(QAbstractTableModel):
def __init__(self):
super().__init__()
self.data = ['hello']
def rowCount(self, parent=None):
return 1
def columnCount(self, parent=None):
return 1
def data(self, index, role):
if not index.isValid():
return QVariant()
if role in (Qt.DisplayRole, Qt.EditRole):
return self.data[0]
return QVariant()
def setData(self, index, value, role):
if role == Qt.EditRole:
self.data[0] = value
top_left = self.index(0, 0)
bottom_right = self.index(
self.rowCount() + 1, self.columnCount())
self.dataChanged.emit(top_left, bottom_right,
[Qt.DisplayRole])
return True
return False
def flags(self, index):
return Qt.ItemIsEditable | super().flags(index)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.model = Model()
self.table = QTableView()
self.table.setModel(self.model)
delegate = MyDelegate(self.table)
self.table.setItemDelegateForColumn(0, delegate)
def initUI(self):
self.show()
self.setCentralWidget(self.table)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.initUI()
sys.exit(app.exec_())

Setting value of Entry using tkinter, MVC and Observables

I am trying to build a simple GUI using tkinter to read in CSV's and then run some text mining functions. I am having difficulty understand tkinter's callback function. The following code was created using this ToyMVC code.
I am able to get the GUI to pop up but am having trouble getting the rightmost Entry widget (variable name = finalPathEntry) to update with the user-inputted text from the left Widget once the user presses the button.
I would greatly appreciate any advice on how to move forward and what I am doing wrong.
Best,
import tkinter as tk
class Observable:
def __init__(self, initialValue=None):
self.data = initialValue
self.callbacks = {}
def addCallback(self, func):
self.callbacks[func] = 1
def delCallback(self, func):
del self.callback[func]
def _docallbacks(self):
for func in self.callbacks:
func(self.data)
def set(self, data):
self.data = data
self._docallbacks()
def get(self):
return self.data
def unset(self):
self.data = None
class Model:
def __init__(self):
self.csvPath = Observable("")
def addPath(self, value):
self.csvPath.set(self.csvPath.get())
class View(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self, master)
self.protocol('WM_DELETE_WINDOW', self.master.destroy)
tk.Label(self, text='Please input path to CSV').pack(side='left')
self.pathEntry = tk.Entry(self, width=50)
self.pathEntry.pack(side='left')
self.addButton = tk.Button(self, text='Read CSV', width=8)
self.addButton.pack(side='left')
self.path = tk.StringVar()
self.finalPathEntry = tk.Entry(self, width = 30, textvariable = self.path)
self.finalPathEntry.pack(side='left')
def setPath(self, value):
self.path.set(str(value))
class Controller:
def __init__(self, root):
self.model = Model()
self.model.csvPath.addCallback(self.pathChanged)
self.view1 = View(root)
self.view1.minsize(width = 500, height = 500)
self.view1.addButton.config(command=self.addPath)
self.pathChanged(self.model.csvPath.get())
def addPath(self):
self.model.addPath(self.view1.pathEntry.get())
def pathChanged(self, val):
self.view1.setPath(val)
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
app = Controller(root)
root.mainloop()
EDIT: Using the answer below, I have fixed my code. Here is the updated and working snippet:
import tkinter as tk
class Observable:
def __init__(self, initialValue = None):
self.data = initialValue
self.callbacks = {}
def addCallback(self, func):
self.callbacks[func] = 1
def delCallback(self, func):
del self.callback[func]
def _docallbacks(self):
for func in self.callbacks:
func(self.data)
def set(self, data):
self.data = data
self._docallbacks()
def get(self):
return self.data
def unset(self):
self.data = None
class Model:
def __init__(self):
self.csvPath = Observable("")
def addPath(self, value):
self.csvPath.set(self.csvPath.get())
class View(tk.Toplevel):
def __init__(self, master):
tk.Toplevel.__init__(self, master)
self.protocol('WM_DELETE_WINDOW', self.master.destroy)
tk.Label(self, text='Please input path to CSV').pack(side='left')
self.pathEntry = tk.Entry(self, width=50)
self.pathEntry.pack(side='left')
self.addButton = tk.Button(self, text='Read CSV', width=8)
self.addButton.pack(side='left')
self.path = tk.StringVar()
self.finalPathEntry = tk.Entry(self, width = 30, textvariable = self.path)
self.finalPathEntry.pack(side='left')
def setPath(self, value):
self.path.set(str(value))
class Controller:
def __init__(self, root):
self.model = Model()
self.model.csvPath.addCallback(self.pathChanged)
self.view1 = View(root)
self.view1.minsize(width = 500, height = 500)
self.view1.addButton.config(command = self.addPath)
self.pathChanged(self.model.csvPath.get())
def addPath(self):
self.model.addPath(self.view1.pathEntry.get())
def pathChanged(self, val):
self.view1.setPath(val)
if __name__ == '__main__':
root = tk.Tk()
root.withdraw()
app = Controller(root)
root.mainloop()
One thing about this code seems obvious: The functions beginning at
def addcallback(self, func):
until
def unset(self):
are not part of the Observable class. So the "self" argument is not what you expect it to be. You should indent these functions.

PyQT: adding to QAbstractItemModel using a button

I'm trying to implement a TreeView using QAbstractItemModel. I want to set up an empty model and then add an item to the model using a button.
This appears to be a lot more complex than I'd realised! I've modified a custom instance of the QAbstractItemModel example found in the Lib\site-packages\PyQt4\examples\itemviews\simpletreemodel\simpletreemodel.pyw.
Rather than setting up the model all at once, I want o build it incrementally.
When I click the button, I get the message showing that the process method is executing, but the model isn't updated.
Any pointers as to why it's not working would be greatly appreciated!
from PyQt4 import QtGui, QtCore
import sys
class myWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(500, 400)
#Tree Widget
self.treeView = QtGui.QTreeView(self)
#Model
self.model = TreeModel()
self.treeView.setModel(self.model)
# Button
self.button = QtGui.QPushButton(self)
self.button.setText('Add Item')
self.button.clicked.connect(self.process)
# Add to Layout
self.gridLayout = QtGui.QGridLayout(self)
self.gridLayout.addWidget(self.button,0,0)
self.gridLayout.addWidget(self.treeView,1,0)
def process(self):
print "here"
newItem = TreeItem(["bob","bob","bob"],self.model.rootItem)
self.model.rootItem.appendChild(newItem)
class TreeItem(object):
def __init__(self, data, parent=None):
self.parentItem = parent
self.itemData = data
self.childItems = []
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def columnCount(self):
return len(self.itemData)
def data(self, column):
try:
return self.itemData[column]
except IndexError:
return None
def parent(self):
return self.parentItem
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
class TreeModel(QtCore.QAbstractItemModel):
def __init__(self, parent=None):
super(TreeModel, self).__init__(parent)
self.rootItem = TreeItem(("Model", "Status","Location"))
def columnCount(self, parent):
if parent.isValid():
return parent.internalPointer().columnCount()
else:
return self.rootItem.columnCount()
def data(self, index, role):
if not index.isValid():
return None
if role != QtCore.Qt.DisplayRole:
return None
item = index.internalPointer()
return item.data(index.column())
def flags(self, index):
if not index.isValid():
return QtCore.Qt.NoItemFlags
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.rootItem.data(section)
return None
def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid():
return QtCore.QModelIndex()
childItem = index.internalPointer()
parentItem = childItem.parent()
if parentItem == self.rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent):
if parent.column() > 0:
return 0
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()
if __name__ == "__main__":
app = QtGui.QApplication.instance() # checks if QApplication already exists
if not app: # create QApplication if it doesnt exist
app = QtGui.QApplication(sys.argv)
# Window
window = myWindow()
window.show()
sys.exit(app.exec_())
Using a QStandardItemModel has worked a treat!
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Window(QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(500, 400)
#Tree Widget
self.treeView = QTreeView()
#Model
self.model = QStandardItemModel()
self.treeView.setModel(self.model)
# Button
self.button = QPushButton()
self.button.setText('Add Item')
self.button.clicked.connect(self.addChildClick)
# Add to Layout
self.gridLayout = QGridLayout(self)
self.gridLayout.addWidget(self.button,0,0)
self.gridLayout.addWidget(self.treeView,1,0)
def addChildClick(self):
selection = self.treeView.selectedIndexes()
text = "bob"
item = QStandardItem(text)
# if nothing selected parent is model
if selection == []:
parent = self.model
else: # Otherwise parent is what is selected
s = selection[0] # Handling multiple selectons
parent = self.model.itemFromIndex(s)
parent.appendRow(item)
#cleanup
self.treeView.expandAll()
self.treeView.clearSelection()
if __name__ == "__main__":
app = QApplication.instance() # checks if QApplication already exists
if not app: # create QApplication if it doesnt exist
app = QApplication(sys.argv)
# Window
window = Window()
window.show()
app.exec_()

Resources