I am working with a simulated bebop2
These are the commands I am using to run the simulation.
sphinx /opt/parrot-sphinx/usr/share/sphinx/drones/bebop2.drone
roslaunch bebop_driver bebop_node.launch ip:=10.202.0.1
In this case bebop_driver is the subscriber and bebop_commander the publisher( see code below)
I've been using:
rostopic pub -r 10 cmd_vel geometry_msgs/Twist '{linear: {x: 0.0, y: 0.0, z: 0.0}, angular: {x: 0.0,y: 0.0,z: 0.0}}'
in order to publish to cmd_vel topic successfully .I need to publish the same message to the same topic using a Python script, but so far I haven't been able.
This is the Python script I am trying to use :
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
import sys
rospy.init_node("bebop_commander")
movement_publisher= rospy.Publisher('cmd_vel', Twist , queue_size=10)
movement_cmd = Twist()
speed = float(sys.argv[1])
time = float(sys.argv[2])
print ("Adelante")
if speed != "" and speed > 0 :
print ("Velocidad =" , speed , "m/s")
else:
print ("Falta parametro de velocidad o el valor es incorrecto")
if time != "" and time > 0 :
print ("Tiempo = ",time, "s")
else:
print ("Falta parametro de tiempo o el valor es incorrecto")
if time != "" and time > 0 :
movement_cmd.linear.x = 0
movement_cmd.linear.y = 0
movement_cmd.linear.z = 0
movement_cmd.angular.x = 0
movement_cmd.angular.y = 0
movement_cmd.angular.z = 0
movement_publisher.publish(movement_msg)
print ("Publishing")
rospy.spin()
Few mistakes/suggestions in your code:
You are not checking if the user is actually entering all the arguments at the start, namely filename, speed and time. Here try using below code:
if len(sys.argv)>2:
speed = float(sys.argv[1])
time = float(sys.argv[2])
else:
print("one or more arguments missing!!")
There is no need of speed != "" and time != "" once you checked len(sys.argv)>2 condition.
you are passing an unknown variable movement_msg inside movement_publisher.publish(). Kindly check below line:
movement_publisher.publish(movement_msg)
It should be movement_cmd.
Modified code(Tested):
Filename: test_publisher.py
import rospy
from geometry_msgs.msg import Twist
import sys
rospy.init_node("bebop_commander")
movement_publisher= rospy.Publisher('cmd_vel', Twist , queue_size=10)
movement_cmd = Twist()
if len(sys.argv)>2:
speed = float(sys.argv[1])
time = float(sys.argv[2])
print("Adelante")
if speed > 0.0:
print("Velocidad =" , speed , "m/s")
else:
print("Falta parametro de velocidad o el valor es incorrecto")
if time > 0.0:
print ("Tiempo = ",time, "s")
movement_cmd.linear.x = 0
movement_cmd.linear.y = 0
movement_cmd.linear.z = 0
movement_cmd.angular.x = 0
movement_cmd.angular.y = 0
movement_cmd.angular.z = 0
movement_publisher.publish(movement_cmd)
print ("Publishing")
rospy.spin()
else:
print ("Falta parametro de tiempo o el valor es incorrecto")
else:
print('one or more argument is missing!!')
Note: Don't forget to copy the file test_publisher.py to scripts directory and make it executable via chmod +x test_publisher.py
Output:
(Terminal 1): Run roscore command. You must have a roscore running in order for ROS nodes to communicate.
(Terminal 2): Run python publisher file with arguments.
(Terminal 3): checking rostopic information
Related
I'm doing a function with python where I have to create a matrix in Excel, but for that I need to know how I can manipulate some keyboard request to specific excel cells positions in it to create this matrix with some values in this cells.
The code that I have right now it is here:
import sys
import openpyxl as opxl
def crear_menu():
menu=int(input("Elija una opción \n 1.Crear parámetros \n
2.Aplicar Dijkstra \n 3.Aplicar Kruskal \n 4.Salir"))
if menu == 1:
min_nodos()
elif menu == 2:
dijkstra()
elif menu == 3:
kruskal()
elif menu == 4:
sys.exit()
else:
print("\n ERROR: Elija una opción válida.")
crear_menu()
def crear_matriz_adyacente2(cant_nodos):
lista_nodos = []
lista_matriz = []
lista_filas = []
lista_columnas = []
libro = opxl.Workbook()
pagina = libro.active
pagina.title = "matriz_de_adyacencia"
i = 0
while(i < cant_nodos):
num = str(i+1)
nodo = str(input("Ingresar nombre del nodo " + num + ":"))
if nodo not in lista_nodos:
lista_nodos.append(nodo)
pagina.cell(row = i+2, column = 1, value = nodo)
pagina.cell(row = 1, column = i+2, value = nodo)
i += 1
elif(nodo < 0):
print("ERROR: Nodo no valido")
else:
print("Error: Nodo existente. \n Ingrese otro nombre: ")
libro.save("matriz_de_adyacencia.xlsx")
def min_nodos():
cant_nodos = int(input("Elija la cantidad de nodos a utilizar
(mínimo 6):"))
while(cant_nodos < 6):
print("ERROR: Elija mínimo 6 nodos y que sea entero positivo.")
cant_nodos = int(input("Elija la cantidad de nodos a utilizar (mínimo 6):"))
else:
crear_matriz_adyacente(cant_nodos)
Here in the red box I'm trying to do the matrix, but I don't know the best way to import a specific excel cell. I mean, I don't know if with this I'm referring to A2.
Thank you for your help.
I am trying to use stockfish to evaluate a chess position using FEN notation all in Python. I am mainly using two libraries (pgnToFen I found on github here: https://github.com/SindreSvendby/pgnToFen and Stockfish the MIT licensed one here: https://github.com/zhelyabuzhsky/stockfish). After many bugs I have reached problem after problem. Stockfish not only can't analyse this FEN position (3b2k1/1p3pp1/8/3pP1P1/pP3P2/P2pB3/6K1/8 b f3 -) but it infinitely loops! "No worries!" and thought changing the source code would be accomplishable. Changed to _put(), but basically I am unable to put dummy values in because stdin.flush() won't execute once I give it those values! Meaning I don't even think I can skip to the next row in my dataframe. :( The code I changed is below.
def _put(self, command: str, tmp_time) -> None:
if not self.stockfish.stdin:
raise BrokenPipeError()
self.stockfish.stdin.write(f"{command}\n")
try:
self.stockfish.stdin.flush()
except:
if command != "quit":
self.stockfish.stdin.write('isready\n')
try:
time.sleep(tmp_time)
self.stockfish.stdin.flush()
except:
#print ('Imma head out', file=sys.stderr)
raise ValueError('Imma head out...')
#sys.stderr.close()
def get_evaluation(self) -> dict:
"""Evaluates current position
Returns:
A dictionary of the current advantage with "type" as "cp" (centipawns) or "mate" (checkmate in)
"""
evaluation = dict()
fen_position = self.get_fen_position()
if "w" in fen_position: # w can only be in FEN if it is whites move
compare = 1
else: # stockfish shows advantage relative to current player, convention is to do white positive
compare = -1
self._put(f"position {fen_position}", 5)
self._go()
x=0
while True:
x=x+1
text = self._read_line()
#print(text)
splitted_text = text.split(" ")
if splitted_text[0] == "info":
for n in range(len(splitted_text)):
if splitted_text[n] == "score":
evaluation = {
"type": splitted_text[n + 1],
"value": int(splitted_text[n + 2]) * compare,
}
elif splitted_text[0] == "bestmove":
return evaluation
elif x == 500:
evaluation = {
"type": 'cp',
"value": 10000,
}
return evaluation
and last but not least change to the init_ contructor below:
self._stockfish_major_version: float = float(self._read_line().split(" ")[1])
And the code where I am importing this code to is below, this is where errors pop up.
import pandas as pd
import re
import nltk
import numpy as np
from stockfish import Stockfish
import os
import sys
sys.path.insert(0, r'C:\Users\path\to\pgntofen')
import pgntofen
#nltk.download('punkt')
#Changed models.py for major version line 39 in stockfish from int to float
stockfish = Stockfish(r"C:\Users\path\to\Stockfish.exe")
file = r'C:\Users\path\to\selenium-pandas output.csv'
chunksize = 10 ** 6
for chunk in pd.read_csv(file, chunksize=chunksize):
for index, row in chunk.iterrows():
FullMovesStr = str(row['FullMoves'])
FullMovesStr = FullMovesStr.replace('+', '')
if "e.p" in FullMovesStr:
row.to_csv(r'C:\Users\MyName\Logger.csv', header=None, index=False, mode='a')
print('Enpassant')
continue
tokens = nltk.word_tokenize(FullMovesStr)
movelist = []
for tokenit in range(len(tokens)):
if "." in str(tokens[tokenit]):
try:
tokenstripped = re.sub(r"[0-9]+\.", "", tokens[tokenit])
token = [tokenstripped, tokens[tokenit+1]]
movelist.append(token)
except:
continue
else:
continue
DFMoves = pd.DataFrame(movelist, columns=[['WhiteMove', 'BlackMove']])
DFMoves['index'] = row['index']
DFMoves['Date'] = row['Date']
DFMoves['White'] = row['White']
DFMoves['Black'] = row['Black']
DFMoves['W ELO'] = row['W ELO']
DFMoves['B ELO'] = row['B ELO']
DFMoves['Av ELO'] = row['Av ELO']
DFMoves['Event'] = row['Event']
DFMoves['Site'] = row['Site']
DFMoves['ECO'] = row['ECO']
DFMoves['Opening'] = row['Opening']
pd.set_option('display.max_rows', DFMoves.shape[0]+1)
print(DFMoves[['WhiteMove', 'BlackMove']])
seqmoves = []
#seqmovesBlack = []
evalmove = []
pgnConverter = pgntofen.PgnToFen()
#stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
#rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
for index, row in DFMoves.iterrows():
try:
stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
except:
evalmove.append("?")
continue
#stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
pgnConverter.resetBoard()
WhiteMove = str(row['WhiteMove'])
BlackMove = str(row['BlackMove'])
if index == 0:
PGNMoves1 = [WhiteMove]
seqmoves.append(WhiteMove)
#seqmoves.append(BlackMove)
else:
seqmoves.append(WhiteMove)
#seqmoves.append(BlackMove)
PGNMoves1 = seqmoves.copy()
#print(seqmoves)
try:
pgnConverter.pgnToFen(PGNMoves1)
fen = pgnConverter.getFullFen()
except:
break
try:
stockfish.set_fen_position(fen)
print(stockfish.get_board_visual())
evalpos = stockfish.get_evaluation()
evalmove.append(evalpos)
except:
pass
try:
stockfish.set_fen_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")
except:
evalmove.append("?")
continue
pgnConverter.resetBoard()
if index == 0:
PGNMoves2 = [WhiteMove, BlackMove]
seqmoves.append(BlackMove)
else:
seqmoves.append(BlackMove)
PGNMoves2 = seqmoves.copy()
try:
pgnConverter.pgnToFen(PGNMoves2)
fen = pgnConverter.getFullFen()
except:
break
try:
stockfish.set_fen_position(fen)
print(stockfish.get_board_visual())
evalpos = stockfish.get_evaluation()
print(evalpos)
evalmove.append(evalpos)
except:
pass
#DFMoves['EvalWhite'] = evalwhite
#DFMoves['EvalBlack'] = evalblack
print(evalmove)
So the detailed question is getting stockfish.get_evalution() to just skip, or better yet fix the problem, for this ( 3b2k1/1p3pp1/8/3pP1P1/pP3P2/P2pB3/6K1/8 b f3 - ) FEN position. I have been working on this problem for quite a while so any insight into this would be very much appreciated.
My specs are Windows 10, Python 3.9, Processor:Intel(R) Core(TM) i9-10980XE CPU # 3.00GHz 3.00 GHz and RAM is 64.0 GB.
Thanks :)
Ok. It seems your fen is invalid (3b2k1/1p3pp1/8/3pP1P1/pP3P2/P2pB3/6K1/8 b f3 -). So check that. And python-chess (https://python-chess.readthedocs.io/en/latest/index.html) library allows you to use FEN AND chess engines. So, pretty cool no ? Here is an example of theses two fantastics tools :
import chess
import chess.engine
import chess.pgn
pgn = open("your_pgn_file.pgn")
game = chess.pgn.read_game(pgn)
engine = chess.engine.SimpleEngine.popen_uci("your_stockfish_path.exe")
# Iterate through all moves, play them on a board and analyse them.
board = game.board()
for move in game.mainline_moves():
board.push(move)
print(engine.analyse(board, chess.engine.Limit(time=0.1))["score"])
I am trying to simulate my FMU created from TRNSYS using pyFMI. When I try to simulate it, it prompts the following message:
"forrtl severe(193):Run-time Check Failure. The variable \'TRNSYSFUNCTIONS_mp_GETOUTPUT VALUE$GETOUTPUT VALUE\' is being used without being initiated"
My code looks like this:
from pyfmi import load_fmu
import os
from collections import defaultdict
import time
model = 'ZUB_FMU2.fmu'
model_dir ='C:\\Trnsys17\MyProjects\\TEST_ZUB_13_FMU_check'
trnsys = load_fmu(fmu=model, path=model_dir)
os.chdir(model_dir)
import numpy as np
t_start = 3624*3600
t_end = 6552*3600
h_step = 1*3600
t_array = np.arange(t_start, t_end, h_step)
cool = 26
heat = 19
tim = 0
LR = []
# Initialize FMU
start_time = time.time()
trnsys.initialize(t_start, t_end)
while tim <= len(t_array)-1:
try:
trnsys.set('setCool', cool)
trnsys.set('setHeat', heat)
res = trnsys.do_step(current_t= t_array[tim],step_size=h_step, new_step=True)
if res != 0:
print "Failed to do step", t_array[tim]
LR.append(float(trnsys.get('DG_BU_Shading')))
tim += 1
except ValueError:
raw_input("Error...")
print "Time for simulating an FMU is:"
del trnsys
print 'LR is given as: ', LR
Can anybody predict the reason for an error. It seems like there is an initialization error.
Working with Python 3.5 and Pandas 0.19.2
I describe my problem: I have in a data frame different "IDActivo" sorted by date and time ascending. Well, I have a field called Result whose values are NaN or 1. I need to calculate for each row how long ago was the last N time where the result field was 1 for that particular "IdActivo".
This is my dataframe:
import pandas as pd
import numpy as np
from datetime import datetime
df = pd.DataFrame({'IdActivo': [1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2],
'Fecha': ['1990-01-02','1990-01-03','1990-01-04','1990-01-05','1990-01-08',\
'1990-01-09','1990-01-10','1990-01-11','1990-01-12' ,'1990-01-15',\
'1990-01-16', '1990-01-17', '1990-01-18','1990-01-19','1990-01-22',\
'1990-01-23 ', '1990-01-24', '1990-01-25','1990-01-26','1990-01-29'],
'Hora': ['10:10:00','10:11:00','10:12:00','10:13:00','10:10:00',\
'10:10:00','10:17:00','10:14:00','11:14:00','12:14:00',\
'10:10:00', '10:20:00', '14:22:00','15:22:00','16:22:00',\
'10:10:00', '00:00:00', '00:00:00','00:00:00','00:00:00']})
def Inicio():
numHoraDia = '10:10:00'
numDia = 2 # para nosotros el 2 será el martes ya que le añadimos +1 al lunes que es 0 por defecto
nomDiasSemanaHora = " Resultado"; inpfield = "Fecha" ; oupfield = "Dia_Semana"
df_final = Fecha_Dia_Hora(df,inpfield,oupfield,numHoraDia,numDia,nomDiasSemanaHora)
print (df_final)
def Fecha_Dia_Hora(df, inpfield, oupfield,numHoraDia,numDia,nomDiasSemanaHora):
ord_df = df.sort_values(by=['IdActivo', 'Fecha'])
ord_df[inpfield] = pd.to_datetime(ord_df[inpfield])
ord_df[oupfield] = ord_df[inpfield].dt.dayofweek + 1
ord_df[nomDiasSemanaHora] = np.NaN
ord_df.ix[np.logical_and(ord_df[oupfield] == numDia, ord_df.Hora == numHoraDia), [nomDiasSemanaHora]] = '1'
return ord_df.sort_index()
def Fin():
print("FIN")
if __name__ == "__main__":
Inicio()
Fin()
I show you an example derivated of the dataframe you can see on the code:
imagen
What functions must I investigate to get it?
Thanks
Angel
Hi I have written a code in sageworksheet format, it runs nice and smooth on sagecloud, but I have one problem : I want to make it more interactive so the user can enter the parameters by himself, so I'm willing to convert this into a sage script or a pyhton script, I have installed sage on my ubuntu machine, again the code runs on the notebook but not on the console it gives me some syntax error on " P.x " (the same goes if I try to run it as a python script) All I want is to make it run as a Python script or Sage script so I can use input function to ask users to enter the parameters ! Here is the code :
P.<x> = PolynomialRing(ZZ);
def bezout(f,g):
P.<x> = PolynomialRing(QQ)
f = f+x-x
g = g+x-x
e=xgcd(f,g)
gcd=e[0]
u=e[1]
v=e[2]
return (u,v,gcd)
def polymod(f,q):
P.<x> = PolynomialRing(QQ)
f = f
c = f.coefficients(sparse=False)
N = len(c)
for i in range(N):
c[i] = Rational(c[i]).mod_ui(q);
p = sum(c[i]*(x^(i)) for i in range(N));
return p
def center(f,q):
u = q/2
v = -u
c = f.coefficients(sparse=False)
N = len(c)
for i in range(N):
if c[i]<v:
c[i] = c[i] + q;
elif c[i]>u:
c[i] = c[i] - q;
else:
c[i] = c[i];
p = sum(c[i]*(x^(i)) for i in range(N));
return p
class Ntru:
N = None
p = None
q = None
d = None
f = None
g = None
h = None
fp = None
fq = None
Phi = None
def __init__(self,N,p,q,d):
self.N = N
self.p = p
self.q = q
self.d = d
v = self.N
self.Phi = x^v -1
def test(self):
if not is_prime(self.N):
print "N n est pas premier, pensez a changer ce parametre"
return False
if gcd(self.N,self.p) != 1:
print "N et p ne sont pas premiers entre eux, pensez a changer ces parametres"
return False
if gcd(self.N,self.q) != 1:
print "N et q ne sont pas premiers entre eux, pensez a changer ces parameres"
return False
if self.q <= (6*self.d+1)*self.p :
print "q doit etre superieur a (6d+1)*p "
return False
return True
def genPublicKey(self,f_new,g_new):
self.f = f_new
self.g = g_new
(b_f,b_phi,bz) = bezout(self.f,self.Phi)
self.fp = polymod(b_f,self.p)
self.fq = polymod(b_f,self.q)
self.h = polymod((self.fq*self.g).quo_rem(self.Phi)[1],self.q)
if not self.test():
print "le cryptage ne peut s effectuer avec ces parametres !"
quit()
def encrypt(self,message,rand):
if self.h!=None:
temp=(self.p*rand*self.h + message).quo_rem(self.Phi)[1]
e=polymod(temp,self.q)
return e
else:
print "Impossible de faire le cryptage : la cle n a pas encore ete generee"
print "Veuillez en generer une avec la fonction genPublicKey"
def decrypt(self,encryptedMsg):
a = (self.f*encryptedMsg).quo_rem(self.Phi)[1]
a = polymod(a,self.q)
a = center(a,self.q)
tmp = (self.fp*a).quo_rem(self.Phi)[1]
m=polymod(tmp,self.p)
return m
NTRU=Ntru(167,3,128,3)
f = 1+x-x^2-x^3-x^4+x^5+x^6
g = -1+x^2+x^3+x^4-x^5-x^6
NTRU.f = f
NTRU.g = g
NTRU.genPublicKey(f,g)
print "La cle publique est : ",NTRU.h
msg = 1+x+x^4+x^5+x^6
rand = -1 -x + x^2 + x^3 - x^4 + x^6
enc = NTRU.encrypt(msg,rand)
print "Le Message crypte est : ",enc
dec = NTRU.decrypt(enc)
print "Le Message dechiffre est : ",dec
print "Le Message en clair etait : ",msg
Thank you !
For a python script, you can start by taking your code at the bottom and defining a function as a main entry point like:
def main():
NTRU=Ntru(167,3,128,3)
f = 1+x-x^2-x^3-x^4+x^5+x^6
g = -1+x^2+x^3+x^4-x^5-x^6
NTRU.f = f
NTRU.g = g
NTRU.genPublicKey(f,g)
print "La cle publique est : ",NTRU.h
msg = 1+x+x^4+x^5+x^6
rand = -1 -x + x^2 + x^3 - x^4 + x^6
enc = NTRU.encrypt(msg,rand)
print "Le Message crypte est : ",enc
dec = NTRU.decrypt(enc)
print "Le Message dechiffre est : ",dec
print "Le Message en clair etait : ",msg
Then after this code block, you need to tell python what code you want it to run as if it was a script like so:
if __name__ == "__main__":
main()
If you would like to run it as an executable from the ubuntu command line, I would suggest adding a shebang at the top like:
#!/bin/python //this should be the path to your python executable
If you are interested in adding command line arguments to the script for user input, I suggest looking into the argParse library included with python:
https://docs.python.org/3.3/library/argparse.html for python 3
https://docs.python.org/2/library/argparse.html for python 2.7
Unfortunately I am unfamiliar with Sage; I hope this gets you started in the right direction.