converting the 1D np array to 2D np array - python

The nPhotonDesity is 1 D <class 'numpy.ndarray'> , How can I convert it to 2D <class 'numpy.ndarray'> ?
#######################################################
def getPhotonDensity( pulseWidth, PhotonsTotalNumber, pulseShapeName, xPosition=0):
z = []
if pulseShapeName == ePulseShape.RECT:
Io = PhotonsTotalNumber/len(x);
z = getTransmitedPulse(ePulseShape.RECT.name, T, Io, 0, pulseWidth)(t)
elif pulseShapeName == ePulseShape.GAUSSIAN:
Io = PhotonsTotalNumber;
z = getTransmitedPulse(ePulseShape.GAUSSIAN.name, T, Io, 0, pulseWidth)(t)
return z;
def getTransmitedPulse(name, T, Io, mu=0, pulseWidth = 0, rolloff=None ):
def rc(t, beta):
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return np.sinc(t)*np.cos(np.pi*beta*t)/(1-(2*beta*t)**2)
def rrc(t, beta):
return (np.sin(np.pi*t*(1-beta))+4*beta*t*np.cos(np.pi*t*(1+beta)))/(np.pi*t*(1-(4*beta*t)**2))
# rolloff is ignored for triang and rect
if name == ePulseShape.RECT.name:
return lambda t: Io*(abs(t/T) < pulseWidth).astype(int)
elif name == 'triang':
return lambda t: (1-abs(t/T)) * (abs(t/T) < pulseWidth ).astype(float)
elif name == 'rc':
return lambda t: rc(t/T, rolloff)
elif name == 'rrc':
return lambda t: rrc(t/T, rolloff)
elif name == ePulseShape.GAUSSIAN.name:
return lambda t: Io/(pulseWidth * np.sqrt(2 * np.pi)) * np.exp( - (t/T - mu)**2 / (2 * pulseWidth**2) )
nPhotonDesity = getPhotonDensity(pulseWidth, PhotonsTotalNumber, pulseShapeName)

Related

how to speed up scene._render_pygame_def_update() in python

im trying to make a 3d renderer but i can only get at most 20fps on idle.
i tried using #functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle.
is there any way i could make this any faster
im using a long math formula i found a few month ago but it seems to be to slow for the map in projected_des
from math import *
import pygame
import numpy
from functools import lru_cache
#lru_cache(maxsize=None)
def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance):
x,y,z=x-posx,y-posy,z-posz
if abs(x)>render_distance or abs(z)>render_distance:return None
px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx
py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy
return [round(px),round(py)]
class coordinate:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
class verticies_structure:
def __init__(self):
self._verts=[]
def add_vert(self,x,y,z):
self._verts.append(coordinate(x,y,z))
def get_coords(self,indexes):
return self._verts[indexes[0]:indexes[1]]
class camera:
def __init__(self,w,h,render_distance,fov=45):
self.fov=360-fov
self.w=w
self.h=h
self.x=0
self.rx=0
self.cx=0
self.y=0
self.ry=0
self.cy=0
self.z=0
self.rz=0
self.cz=0
self.render_distance=render_distance
def false(f,value):
if value==f:
value=f+0.01
return value
def inf360(value):
if value>359:value=0
if value<0:value=359
return value
class mesh(object):
def __init__(self,file_obj,cam):
self.cam=cam
self.verts=verticies_structure()
self.source=file_obj
self.read_object_file()
self.verts=verticies_structure()
size=100
for x in range(size):
for z in range(size):
self.verts.add_vert(x-size//2,0,z-size//2)
self.w2s_vect=numpy.vectorize(self.w2s)
self.array_verts=numpy.array(self.verts._verts)
def w2s(self,coord):
cam=self.cam
return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)
def projected_des(self,cam):
#return self.w2s_vect(self.array_verts).tolist()
return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1]))
def read_object_file(self):
self.verts=verticies_structure()
import re
reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE)
with open(self.source) as f:
data = [txt.group() for txt in reComp.finditer(f.read())]
v_arr, vn_arr, vt_arr, f_arr = [], [], [], []
for line in data:
tokens = line.split(' ')
if tokens[0] == 'v':
v_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vn':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'vt':
vn_arr.append([float(c) for c in tokens[1:]])
elif tokens[0] == 'f':
f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]])
vertices, normals = [], []
for face in f_arr:
for tp in face:
self.verts.add_vert(*v_arr[tp[0]-1])
self.array_verts=numpy.array(self.verts._verts)
class draw:
class frame:
class pygame_uitl:
def grid(rowx,rowy,px,color=(255,255,255)):
display=pygame.display.get_surface()
for r in range(rowx):
r+=1
pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px)
for r in range(rowy):
r+=1
pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)
class system:
class pygame_util:
def get_orientation():
inf=pygame.display.Info()
w,h=inf.current_w,inf.current_h
if w>h:
return 1
else:
return 0
class Drivers:
class Pygame:
DEFAULT="PG-default"
SDL2="PG-sdl2"
class master:
class scene:
def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int):
self._model={
"class 1":[],
"class 2":[],
"class 3":[],
"class 4":[]}
self._fps=fps
self._window_wh=wh
self._driver=display_driver
self._camera=camera(*wh,render_distance)
self._mode="mesh"
self._super_ls=0
if display_driver==Drivers.Pygame.DEFAULT:
self._render_pygame_def_setup()
def add_model(self,file):
model=mesh(file,self._camera)
vertexes=len(model.verts._verts)
if vertexes>100:
self._model["class 4"].append(model)
elif vertexes>50:
self._model["class 3"].append(model)
elif vertexes>25:
self._model["class 2"].append(model)
else:
self._model["class 1"].append(model)
def regulate_camera(self):
self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz)
self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz)
def correct_camera(self,orient=1):
self._orient=orient
if orient:
self._camera.cx=self._window_wh[1]//2
self._camera.cy=self._window_wh[0]
self._camera.ry=0.4
else:
self._camera.cx=self._window_wh[0]//2
self._camera.cy=self._window_wh[1]
self._camera.ry=0.2
def auto_render_distance(self):
if self._driver==Drivers.Pygame.DEFAULT:
if self._pygame_clock.get_fps()+5>self._fps:
self._camera.render_distance+=1
else:
self._camera.render_distance-=1
def landscape_super(self):
self._super_ls=1
self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01])
self._lss_hdri_file_jpg_surf.fill((200,220,255))
def _render_pygame_def_setup(self):
self._pygame_clock=pygame.time.Clock()
self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE)
def _render_pygame_def_update(self):
self._pygame_screen.fill((0,70,0))
self.regulate_camera()
for idx,vclass in self._model.items():
for model in vclass:
for point in model.projected_des(self._camera):
if point!=None:
try:self._pygame_screen.set_at(point,(255,255,255))
except:pass
if self._super_ls:
self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0))
def _render_pygame_def_finish(self):
pygame.display.flip()
self._pygame_clock.tick(self._fps)
scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60)
scene.add_model("cube.obj")
scene.correct_camera(0)
scene.landscape_super()
#make the sky mapped to edge of render
pygame.font.init()
while 1:
rx,ry=pygame.mouse.get_rel()
scene._camera.rx+=rx/200
scene._render_pygame_def_update()
#scene.auto_render_distance()
scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0))
scene._render_pygame_def_finish()

Is there a way to create a sign function in python?

import re
import math
from random
import randint
import hashlib
P = (-0.15, 2.645)
Q = (0.7, 2.71)
max_mod = 1.158 * 10 ** 77
def SHA256_INT(text):
return int(f'0x{hashlib.sha256(text.encode("ascii")).hexdigest()}', 0)
def ecc_double_slope(P):
slope = (3 * P[0] ** 2) / (2 * P[1])
return slope
def ecc_add(P, Q, slope):
xr = slope ** 2 - P[0] - Q[0]
yr = slope * (P[0] - xr) - P[1]
return (xr, yr)
def ecc_double(P):
slope = ecc_double_slope(P)
sum0 = ecc_add(P, P, slope)
return sum0
def ecc_double_for(P, limit):
lis = []
for i in range(limit):
b = ecc_double(P)
P = b
lis.append((2 ** i, b))
return lis
def greedy2(number):
x = 0
dub_lis = []
add_lis = []
while 2 ** x < number:
dub_lis.append(2 ** x)
x += 1
x -= 1
n = 2 ** x
while n != number:
y = x
while n + (2 ** y) > number:
y -= 1
n += (2 ** y)
x += 1
add_lis.append(2 ** y)
return len(dub_lis), add_lis
def ecc_main_add(P, Q):
x1 = P[0]
y1 = P[1]
x2 = Q[0]
y2 = Q[1]
slope = (y2 - y1) / (x2 - y1)
xr = slope ** 2 - x1 - x2
yr = slope * (x1 - xr) - y1
return xr, yr
def gen_points(gen, points):
if gen == 1:
return points
elif gen > 1:
if type(points) == int:
point_curve = (points, math.sqrt(points ** 3 + 7))
elif type(points) == tuple:
point_curve = points
point_steps = greedy2(gen)
point_dub = point_steps[0]
point_add = point_steps[1]
dub_list = ecc_double_for(point_curve, point_dub)
for i in point_add:
b = ecc_main_add(dub_list[int(math.log(i, 2))][1], dub_list[-1][1])
return b, gen
elif gen == 0:
return 0
def sign(messsage, private_key, public_key, G):
global max_mod
msg_hash = SHA256_INT(messsage)
randnum = randint(2, max_mod)
r = gen_points(randnum, G)[0]
r_x = r[0]
msg_hash = SHA256_INT(messsage)
s = (r_x * private_key + msg_hash) / randnum
p1 = gen_points(msg_hash/s, G)
p2 = gen_points(r_x/s, public_key)
p3 = ecc_main_add(p1, p2)
return p3
pub, priv = gen_points(9756, P)
print(sign('hello', priv, pub, P))
Hello, I'm trying to implement a way to sign messages using this tutorial:
https://learnmeabitcoin.com/beginners/digital_signatures_signing_verifying
I've tried to follow the tutorial before, but it's either my key generation is wrong, I didn't follow the tutorial correctly, or both.
My current code generates an error, I've already debugged it and it generates the error: TypeError: 'NoneType' object is not subscriptable.
Does anyone know how to solve this?

ImportError: cannot import name 'ODE_Solver' odesolver implementation and call error

I try to implement ODE Solver contain deifferent numerical schemes for solve ODE 5-th order:
For example consider the Forward Euler scheme code implementation:
# ES.py
from abc import ABC
from ODS import ODE_Solver
class FE(ODE_Solver, ABC):
"""
Attribute:
x: array of x coords
u: solution array y(x)
k: number of steps
f: right hand side ODE equation: du/dx = f(u, x)
"""
#classmethod
def solver_st(self):
u, f, k, x = self.u, self.f, self.k, self.x
dx = x[k+1] - x[k]
u_new = u[k] + dx*f(u[k], x[k])
return u_new
This method code by class and contain one method and based on superclass ODE_Solver:
#ODS.py
import numpy as np
class ODE_Solver(object):
"""
Supercalss sover ODE-s
Attribute:
x: array of x coords
u: solution array y(x)
k: number of steps
f: right hand side ODE equation: du/dx = f(u, x)
"""
def __init__(self, f):
if not callable(f):
# check correct function f(u, x)
raise TypeError('f is %s, not function' % type(f))
self.f = lambda u, x: np.asarray(f(u, x), float)
def solver_st(self):
"""Implement numerical scheme"""
raise NotImplementedError
def set_initial_condition(self, u0):
if isinstance(u0, (float, int)): # ODE 1-th order
self.neq = 1
u0 = float(u0)
else: # ODE high order or system of ODE-s
u0 = np.asarray(u0) # (initial conds)
self.neq = u0.size
self.u0 = u0
# check correct lenght of vector f
try:
f0 = self.f(self.u0, 0)
except IndexError:
raise IndexError(
'index out of bounds f(u,x). right index %s' % (str(range(self.neq))))
if f0.size != self.neq:
raise ValueError('f(u,x) return %d elems, u has %d elems' % (f0.size, self.neq))
def solve(self, coord_points, terminate=None):
"""
Solve equations. Default False
"""
if terminate is None:
terminate = lambda u, x, step_no: False
if isinstance(coord_points, (float, int)):
raise TypeError('solve: array lists not iterable')
self.x = np.asarray(coord_points)
if self.x.size <= 1:
raise ValueError('ODESolver.solve requre coords x array')
n = self.x.size
if self.neq == 1: # ODE
self.u = np.zeros(n)
else:
self.u = np.zeros((n, self.neq))
# Assume self.x[0] corresponds to self.u0
self.u[0] = self.u0
# looping for x coords
for k in range(n - 1):
self.k = k
self.u[k + 1] = self.solver_st()
if terminate(self.u, self.x, self.k + 1):
break
return self.u[:k + 2], self.x[:k + 2]
And now I try to testing my code:
# test.py
import matplotlib.pyplot as plt
import numpy as np
from ODS import ODE_Solver
def f(u, x):
return (u[1],
u[2],
u[3],
u[4],
- 15 * u[4] - 90 * u[3] -
270 * u[2] - 405 * u[1] - 243 * u[0])
y0 = [0, 3, -9, -8, 0]
solver = FE(f)
solver.set_initial_condition(y0)
x_points = np.linspace(0, 5, 150)
u, x = solver.solve(x_points)
plt.plot(x, u)
So I consider the reccomendation in commentary I succes to call solver methods, but I get type error:
File "C:\Fin_Proj_ODE\test1.py", line 19, in <module>
u, x = solver.solve(x_points)
File "C:\Fin_Proj_ODE\ODS.py", line 71, in solve
self.u[k + 1] = self.solver_st()
File "C:\Fin_Proj_ODE\ES.py", line 18, in solver_st
u, f, k, x = self.u, self.f, self.k, self.x
AttributeError: type object 'FE' has no attribute 'u'
This post not help me to decide this troubleshooting
And I have 2 questions:
1) How to fix this error of call methods of required class? Any idea?
How to rewrite class for calling methods in test file from EF class?
ImportError: cannot import name 'ODE_Solver' - this bug related with wrong call methods of class EF:
solver = ODE_Solver.solver_st(f)
solver.set_initial_condition(y0)
x_points = np.linspace(0, 5, 150)
u, x = solver.solve(x_points)
For fixing 2-nd problem should remove #classmethod in numerical scheme class implementation:
class FE(ODE_Solver, ABC):
def solver_st(self):
u, f, k, x = self.u, self.f, self.k, self.x
dx = x[k+1] - x[k]
u_new = u[k] + dx*f(u[k], x[k])
return u_new

OverflowError: math range error in Python

I'm new to Python and I'm having trouble with this:
import cmath as cm
import numpy as np
from scipy import special
from scipy.misc import derivative
def T(X, Y):
s0 = np.sign(X)
s1 = np.sign(X - 15)
s3 = np.sign(X + 15)
k0 = cm.sqrt( X**2 -(10*Y)**2 )/10
k1 = cm.sqrt( ((X - 15)**2) - (10*Y)**2 )/10
k3 = cm.sqrt( ((X + 15)**2) - (10*Y)**2 )/10
def z(k):
return complex(k, -Y)/cm.sqrt(k**2 + Y**2)
def w(k, s, x):
return np.array([[cm.exp(complex(0, 1)*k*x), cm.exp(-complex(0, 1)*k*x)], [s*z(k)*cm.exp(complex(0, 1)*k*x), -s*cm.exp(-complex(0, 1)*z(k)*x)/z(k)]])
I15 = np.linalg.inv(w(k1, s1, 5))
I05 = np.linalg.inv(w(k0, s0, 5))
I310 = np.linalg.inv(w(k3, s3, 10))
Omega = w(k1, s1, 0).dot(I15).dot(w(k0, s0, 5)).dot(I05).dot(w(k3, s3, 5)).dot(I310)
Omegan = special.eval_chebyu(19, np.trace(Omega)/2)*Omega - special.eval_chebyu(18, np.trace(Omega)/2)*np.identity(2)
I00 = np.linalg.inv(w(k0, s0, 0))
tt = I00.dot(Omegan).dot(w(k0, s0, 200))
t = 1/tt[0][0]
return cm.log(t)
def V(X):
Y0 = X*np.sin(np.deg2rad(2))/10
result = derivative(func=T, x0=Y0, args=(X,))*X/(20*np.pi)
return -result.imag
V = np.vectorize(V)
X = np.linspace(0.01, 10, 1000)
VX = V(X)
I'm getting an OverflowError: math range error, when trying to run this code.
Is there a way to avoid this error? Any help is appreciated. Thanks!
How to debug:
Change your function w like this:
def w(k, s, x):
try:
return np.array([[cm.exp(complex(0, 1)*k*x), cm.exp(-complex(0, 1)*k*x)], [s*z(k)*cm.exp(complex(0, 1)*k*x), -s*cm.exp(-complex(0, 1)*z(k)*x)/z(k)]])
except OverflowError:
import pdb
pdb.set_trace()
Run your program:
#> python myprog.py
--Return--
> /Users/xxx/tmp/myprog.py(19)w()->None
-> pdb.set_trace()
(Pdb)
Debug by testing all your expressions:
(Pdb) locals()
{'k': 3.5499997838094535j, 's': 1.0, 'x': 200, 'z': <function T.<locals>.z at 0x124770c10>, '__return__': None}
(Pdb) cm.exp(complex(0, 1)*k*x)
(4.47647977601281e-309+0j)
(Pdb) cm.exp(-complex(0, 1)*k*x) # The problem is here x=200, x=199 works
*** OverflowError: math range error

Python: Logistic regression - inputing my data into my algorithm

I'm trying to implement a logistic regression algorithm in python, but i'm not used to using python.
I followed a tutorial to create my algorithm:
import matplotlib.pyplot as plt
import seaborn as sns
#matplotlib inline
sns.set(style='ticks', palette='Set2')
import pandas as pd
import math
from numpy import *
def logistic_func(theta, X):
return float(1) / (1 + math.e**(-X.dot(theta))) #for x in x_values]
def log_gradient(theta, X, Y):
first_calc = logistic_func(theta, X) - np.squeeze(Y) #by attribute gives Beta(i)
final_calc = first_calc.T.dot(X)
return final_calc
def cost_func(theta, X, Y):
log_func_v = logistic_func(theta,X)
Y = np.squeeze(Y)
step1 = Y * np.log(log_func_v)
step2 = (1.5-Y) * np.log(1.5 - log_func_v)
step3 = (1-Y) * np.log(1 - log_func_v)
final = -step1 - step2 - step3
return np.mean(final)
def grad_desc(theta_values, X, Y, lr=.001, converge_change=.001):
#normalize
X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
#setup cost iter
cost_iter = []
cost = cost_func(theta_values, X, Y)
cost_iter.append([0, cost])
change_cost = 1
i = 1
while(change_cost > converge_change):
old_cost = cost
theta_values = theta_values - (lr * log_gradient(theta_values, X, Y))
cost = cost_func(theta_values, X, X)
cost_iter.append([i, cost])
change_cost = old_cost - cost
i+=1
return theta_values, np.array(cost_iter)
def pred_values(theta, X, hard=True):
#normalize
X = (X - np.mean(X, axis=0)) / np.std(X, axis=0)
pred_prob = logistic_func(theta, X)
p red_value = np.where(pred_prob >= .5, 1, 0)
if hard:
return pred_value
return pred_prob
the algorithm is supposed to predict 3 classifiers.
I can read in the data:
data = pd.read_csv('filepath')
data.loc[data["type"] == "type1", "type"] = 0
data.loc[data["type"] == "type2", "type"] = 1
data.loc[data["type"] == "type2", "type"] = 2
att1= [];
att2=[];
att3= [];
att4= [];
type=[];
for d in data["attribute1"]:
att1.append(d)
for d in data["attribute2"]:
att2.append(d)
for d in data["attribute3"]:
att3.append(d)
for d in data["attribute4"]:
att4.append(d)
for d in data["type"]:
type.append(d)
combinedClassArray = np.array([att1,att2,att3,att4])
X = combinedClassArray.T
y = type
#totalCount = type.count()
type1= data.loc[data["type"] == 0, "type"].count()
type2= data.loc[data["type"] == 1, "type"].count()
type3= data.loc[data["type"] == 1, "type"].count()
totalCount = type1+type2+type3
p = type1+type2
What i'm sure about is how i can insert my data to the algorithm.
Am I very far off?
You need a main function:
def main():
# your code here would be the calls to the algorithm with the parameters (your data)
if __name__ == "__main__":
main()

Categories

Resources