PyCuda multiple threads execution error - pycuda

This is my pycuda code.When I execute I get threading errors.I am trying to implement pycuda threads in this.I have searched google but couldn't find an answer.Respurces are also very limited for pycuda I'm the Internet.So guys please help me out.
{{{#!python
import pycuda
import pycuda.driver as cuda
from pycuda.compiler import SourceModule
import threading
import numpy
class GPUThread(threading.Thread):
def __init__(self, number, some_array):
threading.Thread.__init__(self)
self.number = number
self.some_array = some_array
def run(self):
self.dev = cuda.Device(self.number)
self.ctx = self.dev.make_context()
self.array_gpu = cuda.mem_alloc(some_array.nbytes)
cuda.memcpy_htod(self.array_gpu, some_array)
test_kernel(self.array_gpu)
print "successful exit from thread %d" % self.number
self.ctx.pop()
del self.array_gpu
del self.ctx
def test_kernel(input_array_gpu):
mod = SourceModule("""
__global__ void f(float * out, float * in)
{
int idx = threadIdx.x;
out[idx] = in[idx] + 6;
}
""")
func = mod.get_function("f")
output_array = numpy.zeros((1,512))
output_array_gpu = cuda.mem_alloc(output_array.nbytes)
func(output_array_gpu,
input_array_gpu,
block=(512,1,1))
cuda.memcpy_dtoh(output_array, output_array_gpu)
return output_array
cuda.init()
some_array = numpy.ones((1,512), dtype=numpy.float32)
num = cuda.Device.count()
gpu_thread_list = []
for i in range(num):
gpu_thread = GPUThread(i, some_array)
gpu_thread.start()
}}}

You forgot to append the gpu thread.Just add gpu_thread_list.append(gpu_thread) after start() in your code and it will work.There are quite a lot of good tutorial for pycuda online.Check this.

Related

Bokeh callback function with image editing not working with pyscript

I am using pyscript to take an image and process it. I am using a bokeh widget to make changes to the image through callback function. The callback function works but stops when I use Pillow to convert the image to greyscale.
Imports:
import numpy as np
from PIL import Image
import js
from js import document, console, Uint8Array, window, File, Bokeh, JSON, localStorage
from pyodide import create_proxy
import asyncio
import io
import json
from bokeh import __version__
from bokeh.document import Document
from bokeh.embed.util import OutputDocumentFor, standalone_docs_json_and_render_items
from bokeh.models import Slider, Div
from bokeh.layouts import Row
from bokeh.protocol.messages.patch_doc import process_document_events
def callback(attr, old, new):
div.text = f'Symbol is: {new}'
first_item = localStorage.getItem('key')
print(first_item)
my_image = imageToBinary(first_item)
print(my_image)
rs_img = convertBintoRS(my_image,8)
rs_img = encodeRS(rs_img, 5, 6)
rs_img = seperate_img(rs_img,5+6,5)
rs_img = RStoBinary(rs_img,8)
rs_img = binaryToImage(rs_img)
display_image(rs_img,"reed_s")
p.on_change('value', callback)
row = Row(children=[p, div])
def imageToBinary(img):
print('enter imageToBinary')
img = img.convert('L')
print('convert to greyscale')
print(img)
img = np.array(img)
print('convert numpy')
x,y = np.shape(img)
print(x,y)
for i in range(0,x):
for j in range(0,y):
if img[i][j] < 255/2:
img[i][j] = 0
else:
img[i][j] = 1
print('success')
return img
I am also including this which is some code that is relevant to the bokeh widget.
def doc_json(model, target):
with OutputDocumentFor([model]) as doc:
doc.title = ""
docs_json, _ = standalone_docs_json_and_render_items(
[model], suppress_callback_warning=False
)
doc_json = list(docs_json.values())[0]
root_id = doc_json['roots']['root_ids'][0]
return doc, json.dumps(dict(
target_id = target,
root_id = root_id,
doc = doc_json,
version = __version__,
))
def _link_docs(pydoc, jsdoc):
def jssync(event):
if getattr(event, 'setter_id', None) is not None:
return
events = [event]
json_patch = jsdoc.create_json_patch_string(pyodide.ffi.to_js(events))
pydoc.apply_json_patch(json.loads(json_patch))
jsdoc.on_change(pyodide.ffi.create_proxy(jssync), pyodide.ffi.to_js(False))
def pysync(event):
json_patch, buffers = process_document_events([event], use_buffers=True)
buffer_map = {}
for (ref, buffer) in buffers:
buffer_map[ref['id']] = buffer
jsdoc.apply_json_patch(JSON.parse(json_patch), pyodide.ffi.to_js(buffer_map), setter_id='js')
pydoc.on_change(pysync)
async def show(plot, target):
pydoc, model_json = doc_json(plot, target)
views = await Bokeh.embed.embed_item(JSON.parse(model_json))
jsdoc = views[0].model.document
_link_docs(pydoc, jsdoc)
asyncio.ensure_future(show(row, 'myplot'))
The callback function stops within imageToBinary at the print('enter imageToBinary')
I know the function works outside the callback function.
I have printed the item going into localStorage and out of it to check it is the same but type() wouldn't work and gave an error.

How to send signals/variables between a QDialog and Main Window

I am currently working on a project that involves graphing text file data into a pyqt graph and I have been running into problems with a subclass QDialog box. My goal is to have the QDialog box use a combox to choose between different data sets to graph (The code below shows the "steering angle" setting being chosen). The problem lies with how to make it so that when the Create Graph button is pressed (Found in the QDialog Class), it runs the createGraph(self): function in the main class. I dont know how to work classes that well so I dont know how to make this work.
If anyone has any pointers on either how to get this working, how to properly structure a PYQT Program or how to make it more efficient, I'm all ears.
Thank you for your time!
Main Window Code:
class MainWidget(QMainWindow):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
self.activateWindow()
self.raise_()
self.setupGraph()
self.dockcheck = 0
self.graphcheck = 0
self.setWindowTitle("Drag and Drop Test")
self.resize(1200, 800)
self.setAcceptDrops(True)
self.LBLDragAndDrop = QLabel("Drag And Drop Files Here")
self.LBLDragAndDrop.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
if self.graphcheck == 0:
self.setCentralWidget(self.LBLDragAndDrop)
self.path3 = "C:\\Users\\steph\\OneDrive\\Documents\\SAA Wing\\Coding\\Can Bus Data Reading\\Temporary Saves"
self.treeview = QTreeView()
self.treeview.setAnimated(True)
self.fileModel = QFileSystemModel()
self.fileModel.setRootPath(self.path3)
self.indexRoot = self.fileModel.index(self.fileModel.rootPath())
self.treeview.setModel(self.fileModel)
self.treeview.setRootIndex(self.fileModel.index(self.path3))
self.treeview.setColumnWidth(0, 250)
self.treeview.doubleClicked.connect(self.onSelectionChanged)
#self.treeview.doubleClicked.connect(self.openDialog)
####################################################################################################################
# Dialog Box
####################################################################################################################
def onSelectionChanged(self, index):
self.selectionPath = self.sender().model().filePath(index)
self.selectionFilename = (self.selectionPath.split("/")[-1])
IDList = ("ID 00d0","ID 00d1","ID 00d3","ID 00d4","ID 0140","ID 0141","ID 0360","ID 0361")
if self.selectionFilename in IDList:
if self.selectionFilename == "ID 00d0":
editDialog = Dialog00d0()
editDialog.exec_()
####################################################################################################################
# Graphing data
####################################################################################################################
def createGraph(self):
self.graphcheck = 1
if self.graphcheck == 1:
self.setCentralWidget(self.scroll_area)
################################################################################################################
# ID 00D0 Creating Graph
################################################################################################################
if self.selectionFilename == "ID 00d0":
self.df00d0 = pd.read_table(self.selectionPath, header=None , delim_whitespace=True, dtype=object)
self.df00d0.columns = ['Timestamp','ID',"B0","B1","B2","B3","B4","B5","B6","B7"]
self.df00d0.dropna(inplace=True)
self.SA = np.array([], dtype=float)
self.LatAcc = np.array([], dtype=float)
self.LonAcc = np.array([], dtype=float)
self.ComAcc = np.array([], dtype=float)
self.Time00d0 = np.array([], dtype=float)
self.Timestamp00d0 = np.array([], dtype=float)
############################################################################################################
# Getting Time Stamps
############################################################################################################
for item in self.df00d0['Timestamp']:
self.Time00d0 = np.append(self.Time00d0, datetime.fromtimestamp(float(item)).strftime("%H:%M:%S.%f")[:-4])
self.Timestamp00d0 = np.append(self.Timestamp00d0, float(item))
############################################################################################################
# Steering Angle Graph
############################################################################################################
if self.combobox00d0.currentText() == "Steering Angle":
SA_ = (((self.df00d0['B1']) + (self.df00d0['B0'])).apply(int, base=16) * 0.1)
for item in SA_:
if item > 6000:
self.SA = np.append(self.SA, round((item - 6553.6), 1))
else:
self.SA = np.append(self.SA, round(item))
y_value = self.SA
Here is the QDialog Box class code:
class Dialog00d0(QDialog):
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
hlay = QHBoxLayout()
self.setLayout(self.layout)
self.setWindowTitle("Create Graph")
label = QLabel("Data Type")
self.combobox00d0 = QComboBox()
self.combobox00d0.addItem("Steering Angle")
self.combobox00d0.addItem("Latitudinal Acceleration")
self.combobox00d0.addItem("Longitudinal Acceleration")
self.combobox00d0.addItem("Combined Acceleration")
self.BTNCreateGraph = QPushButton("Create Graph")
self.BTNCancel = QPushButton("Cancel")
hlay.addWidget(self.BTNCreateGraph)
hlay.addWidget(self.BTNCancel)
self.layout.addWidget(label)
self.layout.addWidget(self.combobox00d0)
self.layout.addLayout(hlay)
self.BTNCreateGraph.clicked.connect("I need the self.creatGraph here")
self.BTNCancel.clicked.connect("self.close")
I imagine this will help you.
The pyqtSignal() argument tells you what information you want to carry.
In this case, I'm passing a text.
Good luck, I hope I helped.
import sys
from PyQt5.QtWidgets import QMainWindow, QDialog, QApplication
from PyQt5.QtWidgets import QPushButton, QVBoxLayout
from PyQt5 import QtCore, QtGui
class MainWidget(QMainWindow):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
button = QPushButton("Button to open dialog")
button.clicked.connect(self.button_clicked)
self.setCentralWidget(button)
self.show()
def button_clicked(self):
dlg = Dialog00d0()
dlg.signEmit.connect(self.createGraph)
dlg.exec()
def createGraph(self, _str):
print('Now Im here')
print(_str)
class Dialog00d0(QDialog):
signEmit = QtCore.pyqtSignal(str)
def __init__(self):
super().__init__()
self.layout = QVBoxLayout()
self.BTNCreateGraph = QPushButton("link to createGraph()")
self.layout.addWidget(self.BTNCreateGraph)
self.setLayout(self.layout)
self.BTNCreateGraph.clicked.connect(self.BTNCreateGraph_clicked)
def BTNCreateGraph_clicked(self):
self.signEmit.emit('But I passed by')
app = QApplication(sys.argv)
win = MainWidget()
app.exec()

How to change eBPF program attached to the same event?

I'm new to eBPf, I want to chang kernel program attached to the same event in user application. So I write the following code:
#!/usr/bin/python
from bcc import BPF
import time
import sys
prog1 = """
int hello(void *ctx) {
bpf_trace_printk("Hello world\\n");
return 0;
}
"""
prog2 = """
int hello(void *ctx) {
bpf_trace_printk("Hello hhh\\n");
return 0;
}
"""
index = 1
while True:
if index == 1:
b = BPF(text=prog1)
index = 2
else:
b = BPF(text=prog2)
index = 1
# attach the program to an event
clone = b.get_syscall_fnname("clone")
b.attach_kprobe(event=clone, fn_name="hello")
line = b.trace_readline(nonblocking=False)
print(line)
sys.stdout.flush()
time.sleep(3)
# b.trace_print()
But the result is not what I expect. It seems that the kernel program doesn't change at all. Any help?

Can we give Max & Min values statically in normalization using MinMaxScaler Sklearn?

So, I have this doubt and have been looking for answers.
Below is the input post request
{
"emotive_Score": [0.89,0.57,0.089,0,0.004,0,0],
"sentiment_Score": [1.521894,-6.4523187],
"mood_score":[40]
}
And I'm using the following code to scale the values.
from flask import Flask, request
from flask_restful import Resource, Api
from json import dumps
from sklearn import preprocessing
import numpy as np
class MoodScore(Resource):
def post(self):
json_data = request.get_json(force=True)
if not json_data:
return {'message': 'No input data provided'}, 400
x = request.json['emotive_Score']
x1 = request.json['sentiment_Score']
x2 = request.json['mood_score']
#Normalisation for Emotive Score
xEmotive = np.array(x)
PositiveEmotive = str(xEmotive[4]+xEmotive[6])
NegativeEmotive = str(xEmotive[0]+xEmotive[1]+xEmotive[2]+xEmotive[3]+xEmotive[5])
EmotiveScoreArray = (PositiveEmotive,NegativeEmotive)
Nml = np.array(EmotiveScoreArray)
float_array = Nml.astype(np.float)
xM = float_array.reshape(-1,1)
minmaxscaler = preprocessing.MinMaxScaler(feature_range=(0,1))
Emotive = minmaxscaler.fit_transform(xM)
#Normalisation for Sentiment Score
xSentiment = np.array(x1)
PositiveSentiment = str(xSentiment[0])
NegativeSentiment = str(xSentiment[1])
SentimentScoreArray = (PositiveSentiment,NegativeSentiment)
Nml1 = np.array(SentimentScoreArray)
float_array1 = Nml1.astype(np.float)
xM1 = float_array1.reshape(-1,1)
minmaxscaler1 = preprocessing.MinMaxScaler(feature_range=(-1,1))
Sentiment = minmaxscaler1.fit_transform(xM1)
return {'PositiveEmotive':str(Emotive[0]),'NegativeEmotive':str(Emotive[1]),'PositiveSentiment':str(Sentiment[0]),'NegativeSentiment':str(Sentiment[1]),'FinalValue':str(Emotive[0]+Emotive[1]+Sentiment[0]+Sentiment[1])}
# return {'FinalScore': str(Sentiment)}
app = Flask(__name__)
api = Api(app)
api.add_resource(MoodScore, '/moodScore')
if __name__ == '__main__':
app.run(port='5005', host="0.0.0.0")
And I'm getting the following as output.
{
"PositiveEmotive": "[0.]",
"NegativeEmotive": "[1.]",
"PositiveSentiment": "[1.]",
"NegativeSentiment": "[-1.]",
"FinalValue": "[1.]"
}
I just want to know whether I can give static values to Min & Max during normalization calculation so that I can get the desired result as below
{
"PositiveEmotive": "[0.546]",
"NegativeEmotive": "[1.]",
"PositiveSentiment": "[0.598]",
"NegativeSentiment": "[-0.6879.]",
"FinalValue": "[1.4561]"
}

Fiji Jython: Macro.getOptions() returns error "'Macro' is not defined"

I'm trying to pass arguments from a macro to a plugin being run in the macro, but the plugin is returning an error when I try to retrieve the string argument being passed. I believe this means I need to import a class, but everything I've tried to far hasn't worked. Here's the code:
from ij import IJ, ImagePlus, WindowManager, ImageStack
from ij.process import FloatProcessor, ImageProcessor, ByteProcessor
from ij.gui import ProgressBar, PointRoi
from ij.measure import ResultsTable
import ij
import ij.macro.Interpreter
import java.util.ArrayList as ArrayList
#stackOpen = IJ.openImage("/home/srammie/Pictures/Chain_Demo1/chainStack1.tif")
imageOpen = WindowManager.getCurrentImage()
imageOpenTitle = imageOpen.getTitle()
imageOpenTitle = imageOpenTitle.split("-")
amplitude = imageOpenTitle[0]
#imageOpen = IJ.openImage("/home/srammie/Pictures/chain_slap_eval1/summaryImage1.tif")
summaryImage = imageOpen.getProcessor()
print amplitude + " image being analyzed!"
dupImageOpen = imageOpen.createImagePlus()
dupSummaryImage = imageOpen.getProcessor().duplicate()
dupSummaryImageTitle = amplitude + "_resultsImage"
dupImageOpen.setProcessor(dupSummaryImageTitle, dupSummaryImage)
lowerBoundArray = ArrayList()
lowerBoundArrayRight = ArrayList()
lowerBoundArrayLeft = ArrayList()
upperBoundArray = ArrayList()
upperBoundArrayRight = ArrayList()
upperBoundArrayLeft = ArrayList()
deltaArray = ArrayList()
deltaArrayRight = ArrayList()
deltaArrayLeft = ArrayList()
largestDelta = 0
smallestDelta = 100
#print "Break"
pRoi = ArrayList()
arguments = Macro.getOptions()
arg = arguments.split(" ")
for i in range(0, len(arg)-1):
argString = arg[i].split("=")
pRoi.add(argString[1])
This script was working for me the first time it was created, but after restarting Fiji, the script started returning the error
NameError: name 'Macro' is not defined.
Any suggestions? Thanks!
Edit:
Restarting Fiji again seems to have made this problem go away.
You did not import the Macro class. I changed the imports to:
from ij import IJ, ImagePlus, WindowManager, ImageStack, Macro
from ij.process import FloatProcessor, ImageProcessor, ByteProcessor
from ij.gui import ProgressBar, PointRoi
from ij.measure import ResultsTable
from ij.macro import Interpreter
from java.util import ArrayList