Please help me in perspective projection [duplicate] - pygame

This question already has answers here:
How to rotate a square around x-axis in a 3D space
(1 answer)
Pygame rotating cubes around axis
(1 answer)
Closed 1 year ago.
I want to project a 3d point onto a 2d plane (screen).
Here is my code as well as the class that converts 3d coordinate to 2d coordinate.
The class to convert 3d coordinate to 2d coordinate:
class dtod(pygame.sprite.Sprite):
def __init__(self, point, scale):
super().__init__()
self.point = numpy.array(point)
width, height = pygame.display.get_surface().get_size()
self.angle = 0
self.point[0] = (self.point[0] * 1) / self.point[2]
self.point[1] = (self.point[1] * 1) / self.point[2]
self.projection = numpy.array(
[[math.cos(self.angle), math.sin(self.angle), 0.], [math.sin(self.angle), math.cos(self.angle), 0.]])
self.point = numpy.dot(self.projection, self.point)
self.point = ((self.point[0] * scale) + width / 2, height / 2 - (self.point[1] * scale))
The main code where I draw the things:
import pygame
import numpy as np
from coord import dtod
import math
pygame.init()
screen = pygame.display.set_mode((0, 0))
run = True
width, height = screen.get_size()
colors = {"white": (255, 255, 255), "red": (255, 0, 0), "green": (150, 253, 55), "blue": (0,
227, 227), "orange": (255, 127, 39), "grey": (64, 64, 64), "yellow": (255, 240, 0)}
tx, ty, tz = 0., 0., 0.
fps = pygame.time.Clock()
def cos(x):
return math.cos(x)
def sin(x):
return math.sin(x)
rx = np.array([[1., 0., 0.], [0., cos(tx), -sin(tx)], [0., sin(tx), cos(tx)]])
ry = np.array([[cos(ty), 0., sin(ty)], [0., 1., 0.], [-sin(ty), 0., cos(ty)]])
rz = np.array([[cos(tz), -sin(ty), 0.], [sin(ty), cos(ty), 0.], [0., 0., 1.]])
scale = 200
p1 = np.array([0.5, 0.5, 1.])
p2 = np.array([-0.5, 0.5, 1.])
p3 = np.array([-0.5, -0.5, 1.])
p4 = np.array([0.5, -0.5, 1.])
p5 = np.array([0.5, 0.5, -2.])
p6 = np.array([-0.5, 0.5, -2.])
p7 = np.array([-0.5, -0.5, -2.])
p8 = np.array([0.5, -0.5, -2.])
def transform(tx, ty, tz):
global rx, ry, rz, p1, p2, p3, p4, p5, p6, p7, p8
rx = np.array([[1., 0., 0.], [0., cos(tx), -sin(tx)], [0., sin(tx), cos(tx)]])
ry = np.array([[cos(ty), 0., sin(ty)], [0., 1., 0.], [-sin(ty), 0., cos(ty)]])
rz = np.array([[cos(tz), -sin(ty), 0.], [sin(ty), cos(ty), 0.], [0., 0., 1.]])
p1 = np.dot(rx, p1)
p1 = np.dot(ry, p1)
p1 = np.dot(rz, p1)
p2 = np.dot(rx, p2)
p2 = np.dot(ry, p2)
p2 = np.dot(rz, p2)
p3 = np.dot(rx, p3)
p3 = np.dot(ry, p3)
p3 = np.dot(rz, p3)
p4 = np.dot(rx, p4)
p4 = np.dot(ry, p4)
p4 = np.dot(rz, p4)
p5 = np.dot(rx, p5)
p5 = np.dot(ry, p5)
p5 = np.dot(rz, p5)
p6 = np.dot(rx, p6)
p6 = np.dot(ry, p6)
p6 = np.dot(rz, p6)
p7 = np.dot(rx, p7)
p7 = np.dot(ry, p7)
p7 = np.dot(rz, p7)
p8 = np.dot(rx, p8)
p8 = np.dot(ry, p8)
p8 = np.dot(rz, p8)
while run:
screen.fill((0, 0, 0))
fps.tick(60)
transform(tx, ty, tz)
pygame.draw.circle(screen, colors["white"], dtod(p1, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p2, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p3, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p4, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p5, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p6, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p7, scale).point, 5)
pygame.draw.circle(screen, colors["white"], dtod(p8, scale).point, 5)
pygame.draw.line(screen, colors["white"], dtod(p1, scale).point, dtod(p2, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p2, scale).point, dtod(p3, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p3, scale).point, dtod(p4, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p4, scale).point, dtod(p1, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p5, scale).point, dtod(p6, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p6, scale).point, dtod(p7, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p7, scale).point, dtod(p8, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p8, scale).point, dtod(p5, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p1, scale).point, dtod(p5, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p6, scale).point, dtod(p2, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p7, scale).point, dtod(p3, scale).point)
pygame.draw.line(screen, colors["white"], dtod(p8, scale).point, dtod(p4, scale).point)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
run = False
pygame.display.update()
pygame.quit()
The logic I used:
I m using orthographic projection technique, and to get a feel of perception, I m dividing the x and y coordinates by depth (z-component) before actually converting 3d->2d.
Thank you in advance

Finally I made that, oh my god I am so happy.
Use the following code, it works fine.
The class to convert 3d-coordinates -> 2d-coordinates:
class dtod(pygame.sprite.Sprite):
def __init__(self, point, scale):
super().__init__()
self.point = numpy.array(point)
width, height = pygame.display.get_surface().get_size()
self.angle = 2 * math.pi / 3
self.length = 5
self.projection = numpy.array(
[[(self.length / math.tan(self.angle)) / (self.point[2] - (self.length / math.tan(self.angle))), 0., 0.],
[0., (self.length / math.tan(self.angle)) / (self.point[2] - (self.length / math.tan(self.angle))), 0.]])
self.point = numpy.dot(self.projection, self.point)
self.point = ((self.point[0] * scale) + width / 2, height / 2 - (self.point[1] * scale))
The main code where I draw the cube:
import pygame
import numpy as np
from coord import dtod
import math
pygame.init()
screen = pygame.display.set_mode((0, 0))
run = True
width, height = screen.get_size()
colors = {"white": (255, 255, 255), "red": (255, 0, 0), "green": (150,253,55),"blue": (0, 227, 227),
"orange": (255, 127, 39),
"grey": (64, 64, 64), "yellow": (255, 240, 0)}
tx, ty, tz = 0., 0., 0.
fps = pygame.time.Clock()
x, y, z = 0, 0, 0
def cos(x):
return math.cos(x)
def sin(x):
return math.sin(x)
rotation_matrices = [np.array([[1., 0., 0.], [0., cos(tx), -sin(tx)], [0.,
sin(tx), cos(tx)]]), np.array([[cos(ty), 0., sin(ty)], [0., 1., 0.], [-sin(ty),
0., cos(ty)]]), np.array([[cos(tz), -sin(ty), 0.], [sin(ty), cos(ty), 0.], [0.,
0., 1.]])]
scale = 200
points = [np.array([0.5, 0.5, 0.5]), np.array([-0.5, 0.5, 0.5]), np.array([-0.5,
-0.5, 0.5]),
np.array([0.5, -0.5, 0.5]), np.array([0.5, 0.5, -0.5]),
np.array([-0.5, 0.5, -0.5]),
np.array([-0.5, -0.5, -0.5]), np.array([0.5, -0.5, -0.5])]
def transform(tx, ty, tz):
global points, rotation_matrices
rotation_matrices = [np.array([[1., 0., 0.], [0., cos(tx), -sin(tx)], [0.,
sin(tx), cos(tx)]]),
np.array([[cos(ty), 0., sin(ty)], [0., 1., 0.], [-
sin(ty), 0., cos(ty)]]),
np.array([[cos(tz), -sin(tz), 0.], [sin(tz), cos(tz),
0.], [0., 0., 1.]])]
for i in range(8):
for j in range(3):
points[i] = np.dot(rotation_matrices[j], points[i])
while run:
screen.fill((0, 0, 0))
fps.tick(60)
transform(tx, ty, tz)
for i in range(8):
pygame.draw.circle(screen, colors["white"], dtod(points[i],
scale).point, 5)
pygame.draw.line(screen, colors["white"], dtod(points[0], scale).point,
dtod(points[1], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[1], scale).point,
dtod(points[2], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[2], scale).point,
dtod(points[3], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[3], scale).point,
dtod(points[0], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[4], scale).point,
dtod(points[5], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[5], scale).point,
dtod(points[6], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[6], scale).point,
dtod(points[7], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[7], scale).point,
dtod(points[4], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[0], scale).point,
dtod(points[4], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[5], scale).point,
dtod(points[1], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[6], scale).point,
dtod(points[2], scale).point)
pygame.draw.line(screen, colors["white"], dtod(points[7], scale).point,
dtod(points[3], scale).point)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
run = 0
if event.key == pygame.K_x:
x = 1
if event.key == pygame.K_y:
y = 1
if event.key == pygame.K_z:
z = 1
if event.key == pygame.K_UP:
if x == 1:
tx += math.pi / 180
if y == 1:
ty += math.pi / 180
if z == 1:
tz += math.pi / 180
if event.key == pygame.K_DOWN:
if x == 1:
tx -= math.pi / 180
if y == 1:
ty -= math.pi / 180
if z == 1:
tz -= math.pi / 180
if event.type == pygame.KEYUP:
if event.key == pygame.K_x:
x = 0
tx = 0
if event.key == pygame.K_y:
y = 0
ty = 0
if event.key == pygame.K_z:
z = 0
tz = 0
pygame.display.update()
pygame.quit()
The problem was that I was applying parallax method but in the wrong way. I didn't consider the position of camera. Notice, now I m subtracting and multiplying some value from self.point[0] i.e. x component and same with y component. That value is the distance from camera, which can easily be proved by similar triangles.

Related

While I convert coco json file into csv, I got only the same filename for the images i want to display all

I need to convert the json file into csv file for some classification purpose, however, I couldn't get the exact output that I want to. It only produces the same image throughout each Id.
import os
filename = '/train/annotation.json'
db_di= '/train/img'
def convert_coco_json_to_csv(filename,db_di):
import pandas as pd
import json
s = json.load(open(filename, 'r'))
out_file = filename[:-5] + '.csv'
with open(out_file, 'w') as out:
out.write('id,file_names, categories,x0,y0,x1,y1,x2,y2,x3,y3,x4,y4,x5,y5,x6,y6,x7,y7,x8,y8,x9,y9,x10,y10,x11,y11,x12,y12,x13,y13,x14,y14,x15,y15,x16,y16\n')
file_names = [f"{db_di}/{image['file_name']}" for image in s['images']]
categories = [cat['name'] for cat in s['categories']]
all_ids = []
for im in s['images']:
all_ids.append(im['id'])
# file_names = im['file_name']
# all_file_names.append(file_names)
all_ids_ann = []
for ann in s['annotations']:
HEIGHT = s['images'][ann['image_id']]['height']
WIDTH = s['images'][ann['image_id']]['width']
x0 = ann['bbox'][0] /WIDTH
x1 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x2 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x3 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x4 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x5 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x6 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x7 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x8 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x9 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x10 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x11 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x12 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x13 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x14 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x15 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
x16 = (ann['bbox'][0] + ann['bbox'][2]) /WIDTH
y0 = ann['bbox'][1]/HEIGHT
y1 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y2 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y3 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y4 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y5 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y6 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y7 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y8 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y9 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y10 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y11 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y12 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y13 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y14 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y15 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
y16 = (ann['bbox'][1] + ann['bbox'][3]) /HEIGHT
# label = ann['category_id']
out.write(f"{file_names[ann['image_id']]},{categories[ann['category_id']]},{x0}, {y0}, {x1}, {y1}, {x2}, {y2}, {x3}, {y3}, {x4}, {y4}, {x5}, {y5}, {x6}, {y6}, {x7}, {y7}, {x8}, {y8}, {x9}, {y9}, {x10}, {y10}, {x11}, {y11}, {x12}, {y12}, {x13}, {y13}, {x14}, {y14}, {x15}, {y15}, {x16}, {y16}\n")
all_ids = set(all_ids)
all_file_names = set(all_file_names)
all_ids_ann = set(all_ids_ann)
no_annotations = list(all_ids - all_ids_ann)
# Output images without any annotations
for image_id in no_annotations:
out.write('{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n'.format(image_id, file_names, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1))
out.close()
# Sort file by image id
s1 = pd.read_csv(out_file)
s1.sort_values('id', inplace=True)
It displays the last image from the json file, but it should display all the images from A-Z for each training data images.
Or if you have any precise way, I am a beginner so it's time saving for me.
Thank you

How to write a cuda c argmax kernel like python does and let it decode one-hot matrix?

Like the title suggested.
Here is the code.
Where show_data() and get_data() are functions to display and inport data.
I'm not sure how to list through a one-hot matrix that is column major(which can fit into cublas functions), and decode it like python's argmax funtion.
I know I must have messed up the index inside the argmax kernel, not sure how I can fix it.
the data is like this:
[[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
the out put should be like:
[1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10]
#define IDX2C(i,j,ld) (((j)*(ld))+(i))
__global__ void argmax_kernel(float *data, float *dataout, int ld, int sd) {
int stride = gridDim.x * blockDim.x;
int tid = blockDim.x * blockIdx.x + threadIdx.x;
float temp = 0.0f;
int i = 0;
int j = 0;
for (i = 0; i < ld; i++) {
for (j = (tid + i*sd*stride); j < sd; j+= stride) {
if (j = (tid + i*sd*stride)) {
temp = data[j];
dataout[i*sd*stride] = 1.0f;
}
else if (temp <= data[j]) {
temp = data[j];
dataout[i*sd*stride] += 1.0f;
}
}
}
}
void argmax(float *data, float *dataout, int ld, int sd) {
int i = 0;
int j = 0;
float temp = 0.0f;
for (i = 0; i < ld; i++) {
for (j = 0; j < sd; j++) {
if (j == 0) {
temp = data[IDX2C(i, j, ld)];
dataout[i] = 1.0f;
}
else if (temp <= data[IDX2C(i, j, ld)]) {
temp = data[IDX2C(i, j, ld)];
dataout[i] = dataout[i] + 1.0f;
}
}
}
}
int main() {
float *y_in, *y_out;
float *d_yin, *d_yout;
int rols_y = 20;
int cols_y = 10;
int size_y = rols_y*cols_y;
char y_file_name[100] = "argmax.csv";
y_in = (float*)malloc(size_y * sizeof(float));
y_out = (float*)malloc(rols_y * sizeof(float));
cudaMalloc((void**)&d_yin, size_y * sizeof(*y_in));
cudaMalloc((void**)&d_yout, rols_y * sizeof(*y_out));
get_ydata(y_in, y_file_name);
show_data(y_in, rols_y, cols_y);
cudaMemcpy(d_yin, y_in, size_y * sizeof(float), cudaMemcpyHostToDevice);
argmax(y_in, y_out, rols_y, cols_y);
show_data(y_out, rols_y, 1);
dim3 dimBlock(256);
int threadBlocks = (size_y + (dimBlock.x - 1)) / dimBlock.x;
if (threadBlocks > 65520) threadBlocks = 65520;
dim3 dimGrid(threadBlocks);
argmax_kernel<<<dimGrid, dimBlock>>>(d_yin, d_yout, rols_y, cols_y);
cudaFree(d_yin);
cudaFree(d_yout);
free(y_in);
free(y_out);
system("pause");
return EXIT_SUCCESS;
}
You have outright errors in your kernel code such as this:
if (j = (tid + i*sd*stride))
but I wouldn't be able to explain what is going on more generally with your kernel code. None of it makes sense to me. I think the simplest thing to do is just to duplicate your host code in your kernel, converting only the outer loop in ld to be a grid-stride loop, which seems to be your desire. Here is an example:
$ cat t23.cu
#include <iostream>
#include <cublas_v2.h>
#define IDX2C(i,j,ld) (((j)*(ld))+(i))
__global__ void argmax_kernel(float *data, float *dataout, int ld, int sd) {
int stride = gridDim.x * blockDim.x;
int tid = blockDim.x * blockIdx.x + threadIdx.x;
float temp = 0.0f;
int i = 0;
int j = 0;
for (i = tid; i < ld; i+= stride) {
for (j = 0; j < sd; j++) {
if (j == 0) {
temp = data[IDX2C(i,j, ld)];
dataout[i] = 1.0f;
}
else if (temp <= data[IDX2C(i, j, ld)]) {
temp = data[IDX2C(i, j, ld)];
dataout[i] += 1.0f;
}
}
}
}
void argmax(float *data, float *dataout, int ld, int sd) {
int i = 0;
int j = 0;
float temp = 0.0f;
for (i = 0; i < ld; i++) {
for (j = 0; j < sd; j++) {
if (j == 0) {
temp = data[IDX2C(i, j, ld)];
dataout[i] = 1.0f;
}
else if (temp <= data[IDX2C(i, j, ld)]) {
temp = data[IDX2C(i, j, ld)];
dataout[i] = dataout[i] + 1.0f;
}
}
}
}
int main() {
float *y_in, *y_out;
float *d_yin, *d_yout;
int rows_y = 20;
int cols_y = 10;
int size_y = rows_y*cols_y;
float d_in[cols_y][rows_y] = {
{1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.},
{0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.},
{0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.},
{0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.},
{0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.},
{0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.},
{0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.},
{0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.},
{0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.},
{0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.}};
y_in = (float*)malloc(size_y * sizeof(float));
y_out = (float*)malloc(rows_y * sizeof(float));
//transpose
for (int r = 0; r < cols_y; r++)
for (int c = 0; c < rows_y; c++)
y_in[IDX2C(c,r,rows_y)] = d_in[r][c];
cudaMalloc((void**)&d_yin, size_y * sizeof(*y_in));
cudaMalloc((void**)&d_yout, rows_y * sizeof(*y_out));
cudaMemcpy(d_yin, y_in, size_y * sizeof(float), cudaMemcpyHostToDevice);
argmax(y_in, y_out, rows_y, cols_y);
for (int i = 0; i < rows_y; i++)
std::cout << y_out[i] << " ";
std::cout << std::endl;
dim3 dimBlock(256);
int threadBlocks = (size_y + (dimBlock.x - 1)) / dimBlock.x;
if (threadBlocks > 65520) threadBlocks = 65520;
dim3 dimGrid(threadBlocks);
argmax_kernel<<<dimGrid, dimBlock>>>(d_yin, d_yout, rows_y, cols_y);
cudaMemcpy(y_out, d_yout, rows_y*sizeof(*y_out), cudaMemcpyDeviceToHost);
for (int i = 0; i < rows_y; i++)
std::cout << y_out[i] << " ";
std::cout << std::endl;
cudaFree(d_yin);
cudaFree(d_yout);
free(y_in);
free(y_out);
}
$ nvcc -o t23 t23.cu
$ cuda-memcheck ./t23
========= CUDA-MEMCHECK
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
========= ERROR SUMMARY: 0 errors
$
There are other things I don't understand here, like why you are using a float output data type to represent an index, but that doesn't seem to be the crux of your question. I'm not suggesting this code is defect-free or optimal in any way, however it may be best to keep things simple at this point.
If you want to, you can probably simplify your host and device argmax functions like this:
$ cat t23.cu
#include <iostream>
#include <cublas_v2.h>
#define IDX2C(i,j,ld) (((j)*(ld))+(i))
__host__ __device__ void argmax(float *data, float *dataout, int ld, int sd, int start, int inc) {
for (int i = start; i < ld; i+=inc) {
float valout = 1.0f;
float temp = data[IDX2C(i, 0, ld)];
for (int j = 1; j < sd; j++) {
float val = data[IDX2C(i, j, ld)];
if (temp <= val) {
temp = val;
valout += 1.0f;
}
}
dataout[i] = valout;
}
}
__global__ void argmax_kernel(float *data, float *dataout, int ld, int sd) {
int stride = gridDim.x * blockDim.x;
int tid = blockDim.x * blockIdx.x + threadIdx.x;
argmax(data, dataout, ld, sd, tid, stride);
}
int main() {
float *y_in, *y_out;
float *d_yin, *d_yout;
int rows_y = 20;
int cols_y = 10;
int size_y = rows_y*cols_y;
float d_in[cols_y][rows_y] = {
{1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.},
{0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.},
{0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.},
{0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.},
{0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.},
{0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.},
{0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.},
{0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.},
{0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.},
{0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.}};
y_in = (float*)malloc(size_y * sizeof(float));
y_out = (float*)malloc(rows_y * sizeof(float));
//transpose
for (int r = 0; r < cols_y; r++)
for (int c = 0; c < rows_y; c++)
y_in[IDX2C(c,r,rows_y)] = d_in[r][c];
cudaMalloc((void**)&d_yin, size_y * sizeof(*y_in));
cudaMalloc((void**)&d_yout, rows_y * sizeof(*y_out));
cudaMemcpy(d_yin, y_in, size_y * sizeof(float), cudaMemcpyHostToDevice);
argmax(y_in, y_out, rows_y, cols_y, 0, 1);
for (int i = 0; i < rows_y; i++)
std::cout << y_out[i] << " ";
std::cout << std::endl;
dim3 dimBlock(256);
int threadBlocks = (size_y + (dimBlock.x - 1)) / dimBlock.x;
if (threadBlocks > 65520) threadBlocks = 65520;
dim3 dimGrid(threadBlocks);
argmax_kernel<<<dimGrid, dimBlock>>>(d_yin, d_yout, rows_y, cols_y);
cudaMemcpy(y_out, d_yout, rows_y*sizeof(*y_out), cudaMemcpyDeviceToHost);
for (int i = 0; i < rows_y; i++)
std::cout << y_out[i] << " ";
std::cout << std::endl;
cudaFree(d_yin);
cudaFree(d_yout);
free(y_in);
free(y_out);
}
$ nvcc -o t23 t23.cu
$ cuda-memcheck ./t23
========= CUDA-MEMCHECK
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
========= ERROR SUMMARY: 0 errors
For other readers, I will point out that I don't consider this code to be a typical argmax implementation; it will not duplicate results for usual argmax functions on arbitrary data. But it should be usable with this kind of one-hot encoding data (only).

how do i get keydown to input only once?

hey so im pretty new to python and im trying to make this game. its a 2d top down action game. i added an inventory, yet i have to hold e for it to keep open, how do i make it so keydown inputs only once and the inventory keeps open?
i apologize if the code looks messy.
the code i need help for:
win.fill(green)
win.blit(bg, (0, 0))
win.blit(tree, (xtree, ytree))
win.blit(tree1, (xtree1, ytree1))
win.blit(tree2, (xtree2, ytree2))
win.blit(rocka, (xrock, yrock))
win.blit(rockb, (xrock1, yrock1))
win.blit(rockc, (xrock2, yrock2))
win.blit(i, (200, 530))
win.blit(top, (100, 2))
def openinventory():
global w
win.blit(border, (10, 10))
win.blit(border, (770, 10))
win.blit(border1, (10, 270))
win.blit(border1, (770, 280))
win.blit(border2, (10, 590))
win.blit(border2, (10, 10))
win.blit(border2, (10, 250))
win.blit(border2, (15, 270))
win.blit(islot, (20, 20))
win.blit(islot, (20, 100))
win.blit(islot, (20, 175))
win.blit(islot, (90, 20))
win.blit(islot, (90, 100))
win.blit(islot, (90, 175))
win.blit(islot, (160, 20))
win.blit(islot, (160, 100))
win.blit(islot, (160, 175))
win.blit(i1, (240, 20))
win.blit(border, (230, 10))
win.blit(i2, (14, 270))
if woodmat == 1:
win.blit(woodmat3, w)
if w > (10, 10) and w > (200, 0):
w = (20, 455)
if woodmat == 2:
win.blit(woodmat6, w)
if w > (10, 10) and w > (200, 0):
w = (20, 455)
if woodmat == 3 or woodmat > 3:
win.blit(woodmat9, w)
if w > (10, 10) and w > (200, 0):
w = (20, 455)
if rockmat == 1:
win.blit(rockmat2, (100, 455))
if rockmat == 2 or rockmat > 2:
win.blit(rockmat4, (100, 455))
if rockmat == 3 or rockmat > 3:
win.blit(rockmat6, (100, 455))
# here it is:
if keys[pygame.K_e]:
openinventory()
heres the full code:
import pygame
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 150, 15)
blue = (0, 0, 255)
def game_loop():
global w
w = 20, 455
w_width = 800
w_height = 600
xtree = 390
ytree = 80
xtree1 = 90
ytree1 = 280
xtree2 = 590
ytree2 = 140
xrock = 215
yrock = 185
xrock1 = 690
yrock1 = 340
xrock2 = 400
yrock2 = 300
woodmat = 0
rockmat = 0
x = 400
y = 400
pygame.display.set_caption("Dragon Quest 2")
win = pygame.display.set_mode((w_width, w_height))
icon = pygame.image.load("icon.gif")
pygame.display.set_icon(icon)
clock = pygame.time.Clock()
man = pygame.image.load("man.gif")
manright = pygame.image.load("manleft.gif")
manleft = pygame.image.load("manright.gif")
manup = pygame.image.load("manback.gif")
tree = pygame.image.load("tree2.gif")
tree1 = pygame.image.load("tree1.gif")
tree2 = pygame.image.load("tree2.gif")
rocka = pygame.image.load("rock.gif")
rockb = pygame.image.load("rock.gif")
rockc = pygame.image.load("rock.gif")
border = pygame.image.load("iborder.gif")
border1 = pygame.image.load("iborder1.gif")
border2 = pygame.image.load("iborder2.gif")
bg = pygame.image.load("bg.png")
islot = pygame.image.load("islot.gif")
i1 = pygame.image.load("inventory.gif")
i2 = pygame.image.load("idown.png")
i = pygame.image.load("bar.png")
top = pygame.image.load("top.png")
woodmat3 = pygame.image.load("woodmat3.png")
woodmat6 = pygame.image.load("woodmat6.png")
woodmat9 = pygame.image.load("woodmat9.png")
rockmat2 = pygame.image.load("rockmat2.png")
rockmat4 = pygame.image.load("rockmat4.png")
rockmat6 = pygame.image.load("rockmat6.png")
gameexit = False
while not gameexit:
win.fill(green)
win.blit(bg, (0, 0))
win.blit(tree, (xtree, ytree))
win.blit(tree1, (xtree1, ytree1))
win.blit(tree2, (xtree2, ytree2))
win.blit(rocka, (xrock, yrock))
win.blit(rockb, (xrock1, yrock1))
win.blit(rockc, (xrock2, yrock2))
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameexit = True
win.blit(man, (x, y))
keys = pygame.key.get_pressed()
movespeed = 5
if keys[pygame.K_LEFT] and x > 5:
x -= movespeed
win.blit(manleft, (x + 10, y + 2))
if keys[pygame.K_RIGHT]:
x += movespeed
win.blit(manright, (x, y))
if keys[pygame.K_UP]:
y -= movespeed
win.blit(manup, (x + 5, y + 5))
if keys[pygame.K_DOWN]:
y += movespeed
win.blit(man, (x, y - 5))
if x == 400 and y == 140 and keys[pygame.K_SPACE]:
xtree = 1000
if xtree == 1000:
woodmat += 1
if x == 100 and y == 350 and keys[pygame.K_SPACE]:
xtree1 = 1000
if xtree1 == 1000:
woodmat += 1
if x == 600 and y == 200 and keys[pygame.K_SPACE]:
xtree2 = 1000
if xtree2 == 1000:
woodmat += 1
if x == 225 and y == 200 and keys[pygame.K_SPACE]:
xrock = 1000
if xrock == 1000:
rockmat += 1
if x == 700 and y == 365 and keys[pygame.K_SPACE]:
xrock1 = 1000
if xrock1 == 1000:
rockmat += 1
if x == 410 and y == 325 and keys[pygame.K_SPACE]:
xrock2 = 1000
if xrock2 == 1000:
rockmat += 1
win.blit(i, (200, 530))
win.blit(top, (100, 2))
def openinventory():
global w
win.blit(border, (10, 10))
win.blit(border, (770, 10))
win.blit(border1, (10, 270))
win.blit(border1, (770, 280))
win.blit(border2, (10, 590))
win.blit(border2, (10, 10))
win.blit(border2, (10, 250))
win.blit(border2, (15, 270))
win.blit(islot, (20, 20))
win.blit(islot, (20, 100))
win.blit(islot, (20, 175))
win.blit(islot, (90, 20))
win.blit(islot, (90, 100))
win.blit(islot, (90, 175))
win.blit(islot, (160, 20))
win.blit(islot, (160, 100))
win.blit(islot, (160, 175))
win.blit(i1, (240, 20))
win.blit(border, (230, 10))
win.blit(i2, (14, 270))
if woodmat == 1:
win.blit(woodmat3, w)
if w > (10, 10) and w > (200, 0):
w = (20, 455)
if woodmat == 2:
win.blit(woodmat6, w)
if w > (10, 10) and w > (200, 0):
w = (20, 455)
if woodmat == 3 or woodmat > 3:
win.blit(woodmat9, w)
if w > (10, 10) and w > (200, 0):
w = (20, 455)
if rockmat == 1:
win.blit(rockmat2, (100, 455))
if rockmat == 2 or rockmat > 2:
win.blit(rockmat4, (100, 455))
if rockmat == 3 or rockmat > 3:
win.blit(rockmat6, (100, 455))
if keys[pygame.K_e]:
openinventory()
pygame.display.update()
pygame.time.delay(30)
clock.tick(60)
game_loop()
pygame.quit()
quit()
i also apologize if the answer was very simple yet i was a big idiot
im pretty new
Add a global state variable door_open = False before the main loop, set the state when e is pressed:
door_open = False
gameexit = False
while not gameexit:
# [...]
if keys[pygame.K_e]:
door_open = True
if door_open:
openinventory()
# [...]
The door_open is ste True and keeps its state. If you want to "close" the door you've to set door_open = False, e.g. close the door when c is pressed:
if keys[pygame.K_c]:
door_open = False
Note, you can do this by an event (e.g. pygame.KEYDOWN) in the event loop, too:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameexit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
door_open = True

Haskell Instances required for definition

I have the following Haskell code, a function that checks how many digits are the same in a number and based on how many of them were the same takes a value. I keep getting the error:
Instances of (Ord (Int -> Int -> Int), Num (Int -> Int -> Int)) required for definition of digits
digits :: Int->Int->Int
digits x y
|(equal < 2) = 0
|(equal == 2) = 1
|(equal == 3) = 5
|(equal == 4) = 20
|(equal == 5) = 300
|(equal == 6) = 8000
|(equal == 7) = 10000
|otherwise = 100000
where
equal :: Int -> Int -> Int
equal 0 0 = 0
equal a b
|(a `mod` 10 == b `mod` 10) = 1 + equal (a `div` 10) (b `div` 10)
|otherwise = 1 + equal (a `div` 10) (b `div` 10)
What am I doing wrong? Also what does the error mean exactly?
EDIT: Did it like this and it works like a charm!
digits :: Int->Int->Int
digits x y
|(c < 2) = 0
|(c == 2) = 1
|(c == 3) = 5
|(c == 4) = 20
|(c == 5) = 300
|(c == 6) = 8000
|(c == 7) = 10000
|otherwise = 100000
where c = equal x y
where
equal :: Int -> Int -> Int
equal 0 0 = 0
equal a b
|(a `mod` 10 == b `mod` 10) = 1 + equal (a `div` 10) (b `div` 10)
|otherwise = 0 + equal (a `div` 10) (b `div` 10)

How to shorten this MySQL Query (colums use often the same sql parts...)

I am not an MySQL Professinal, but my query works fine
SELECT r.id,
/* Total repurchase price per Ton
* (Quantitiy/t * repurchase price/dry) + Extra Costs
*/
(
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0) +
IF ((r.finanzierung_satz > 0) AND (r.finanzierung_monate > 0) AND SUM(rc.menge / 1000),
((r.finanzierung_satz / 100) / 12) * r.finanzierung_monate * (
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0)
)
, 0) ) as repurchase_price,
/* Profit
* (Quantitiy/t * Price) - repurchase_price
*/
(SUM(rc.menge) / 1000 * r.vk) - (
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0) +
IF ((r.finanzierung_satz > 0) AND (r.finanzierung_monate > 0) AND SUM(rc.menge / 1000),
((r.finanzierung_satz / 100) / 12) * r.finanzierung_monate * (
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0)
)
, 0)
) as profit,
/* Profit Percentage
* Profit / (repurchase_price / 100)
*/
((SUM(rc.menge) / 1000 * r.vk) - (
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0) +
IF ((r.finanzierung_satz > 0) AND (r.finanzierung_monate > 0) AND SUM(rc.menge / 1000),
((r.finanzierung_satz / 100) / 12) * r.finanzierung_monate * (
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0)
)
, 0)
))
/
((
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0) +
IF ((r.finanzierung_satz > 0) AND (r.finanzierung_monate > 0) AND SUM(rc.menge / 1000),
((r.finanzierung_satz / 100) / 12) * r.finanzierung_monate * (
SUM((rc.menge / 1000) * (rw.preis / (IF (rw.is_zement = 1, 1.25 , 1)) / (1 - (IFNULL(rw.h2o, 0) / 100)))) +
SUM((rc.menge / 1000) * pr.preis) +
IF ((r.extra_1_type > 0), IF ((r.extra_1_type = 1), extra_1 , extra_1 * SUM(rc.menge / 1000)) , 0) +
IF ((r.extra_2_type > 0), IF ((r.extra_2_type = 1), extra_2 , extra_2 * SUM(rc.menge / 1000)) , 0)
)
, 0)
) / 100)
as profit_percentage,
FROM recipe as r
LEFT JOIN recipecomponent as rc ON r.id = rc.recipe_id
LEFT JOIN rawmaterial as rw ON rc.rawmaterial_id = rw.id
LEFT JOIN press as pr ON r.press_id = pr.id
GROUP BY r.id
ORDER BY lieferdatum desc
As you can see, to calculate price, profit, profit percentage, I use often
the same parts... Is it possible to shorten my SQL Query? To make it more
'elegant' :)
Thank you & Best Regars Simon
As a generic answer, if you repeat caculations in your query, you can use derived tables to avoid repetition:
select d.a, d.b, d.a*d.b
from (
select x+y+z as a, d+e+f as b
from yourtable
) as d;