run sage worksheet as a script? - python

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.

Related

list index out of range example PyomoBook

I'm starting to work with Pyomo and Python, I am following the examples in the book Pyomo Optimization Modeling in Python.
I am trying to solve the Warehouse problem. And I am trying to import the parameters from an Excel file, as indicated in the book:
import pandas
import sys
from pyomo.environ import*
df = pandas.read_excel(sys.argv[1], 'Delivery Costs',header=0, index_col=0)
model = ConcreteModel(name = "WL")
N = list(df.index.map(str))
M = list(df.columns.map(str))
d = {(r, c):df.at[r,c]for r in N for c in M}
P = int(sys.argv[2])
model.x = Var(N, M, bounds=(0,1))
model.y = Var(N, within=Binary)
def obj_rule(model):
return sum(d[n,m]*model.x[n,m] for n in N for m in M)
model.obj = Objective(rule=obj_rule)
def one_per_cust_rule(model, m): # Es necesario poner m porque queremos que lo haga para cada cliente
return sum(model.x[n,m]for n in N) == 1
model.one_per_cust = Constraint(M, rule=one_per_cust_rule)
def warehouse_active_rule(model, n, m):
return model.x[n,m] <= model.y[n]
model.warehouse_active = Constraint(N, M, rule=warehouse_active_rule)
def num_warehouses_rule(model):
return sum(model.y[n] for n in N) <= P
model.num_warehouses = Constraint(rule=num_warehouses_rule)
opt = SolverFactory('glpk')
results = opt.solve(model)
model.pprint()
But when I run the code, I get the following error:
IndexError: list index out of range
What is going wrong?

How I can set a specific cell from excel in python?

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.

WARN: Tried to pass invalid video frame, marking as broken: Your frame has data type int64, but we require uint8

I am doing some Udemy AI courses and came across with one that "teaches" a bidimensional cheetah how to walk. I was doing the exercises on my computer, but it takes too much time. I decided to use Google Cloud to run the code and see the results some hours after. Nevertheless, when I run the code I get the following error " WARN: Tried to pass
invalid video frame, marking as broken: Your frame has data type int64, but we require uint8 (i.e. RGB values from 0-255)".
After the code is executed, I see into the folder and I don't see any videos (just the meta info).
Some more info (if it helps):
I have a 1 CPU (4g), SSD Ubuntu 16.04 LTS
I have not tried anything yet to solve it because I don´t know what to try. Im looking for solutions on the web, but nothing I could try.
This is the code
import os
import numpy as np
import gym
from gym import wrappers
import pybullet_envs
class Hp():
def __init__(self):
self.nb_steps = 1000
self.episode_lenght = 1000
self.learning_rate = 0.02
self.nb_directions = 32
self.nb_best_directions = 32
assert self.nb_best_directions <= self.nb_directions
self.noise = 0.03
self.seed = 1
self.env_name = 'HalfCheetahBulletEnv-v0'
class Normalizer():
def __init__(self, nb_inputs):
self.n = np.zeros(nb_inputs)
self.mean = np.zeros(nb_inputs)
self.mean_diff = np.zeros(nb_inputs)
self.var = np.zeros(nb_inputs)
def observe(self, x):
self.n += 1.
last_mean = self.mean.copy()
self.mean += (x - self.mean) / self.n
#abajo es el online numerator update
self.mean_diff += (x - last_mean) * (x - self.mean)
#abajo online computation de la varianza
self.var = (self.mean_diff / self.n).clip(min = 1e-2)
def normalize(self, inputs):
obs_mean = self.mean
obs_std = np.sqrt(self.var)
return (inputs - obs_mean) / obs_std
class Policy():
def __init__(self, input_size, output_size):
self.theta = np.zeros((output_size, input_size))
def evaluate(self, input, delta = None, direction = None):
if direction is None:
return self.theta.dot(input)
elif direction == 'positive':
return (self.theta + hp.noise * delta).dot(input)
else:
return (self.theta - hp.noise * delta).dot(input)
def sample_deltas(self):
return [np.random.randn(*self.theta.shape) for _ in range(hp.nb_directions)]
def update (self, rollouts, sigma_r):
step = np.zeros(self.theta.shape)
for r_pos, r_neg, d in rollouts:
step += (r_pos - r_neg) * d
self.theta += hp.learning_rate / (hp.nb_best_directions * sigma_r) * step
def explore(env, normalizer, policy, direction = None, delta = None):
state = env.reset()
done = False
num_plays = 0.
#abajo puede ser promedio de las rewards
sum_rewards = 0
while not done and num_plays < hp.episode_lenght:
normalizer.observe(state)
state = normalizer.normalize(state)
action = policy.evaluate(state, delta, direction)
state, reward, done, _ = env.step(action)
reward = max(min(reward, 1), -1)
#abajo sería poner un promedio
sum_rewards += reward
num_plays += 1
return sum_rewards
def train (env, policy, normalizer, hp):
for step in range(hp.nb_steps):
#iniciar las perturbaciones deltas y los rewards positivos/negativos
deltas = policy.sample_deltas()
positive_rewards = [0] * hp.nb_directions
negative_rewards = [0] * hp.nb_directions
#sacar las rewards en la dirección positiva
for k in range(hp.nb_directions):
positive_rewards[k] = explore(env, normalizer, policy, direction = 'positive', delta = deltas[k])
#sacar las rewards en dirección negativo
for k in range(hp.nb_directions):
negative_rewards[k] = explore(env, normalizer, policy, direction = 'negative', delta = deltas[k])
#sacar todas las rewards para sacar la desvest
all_rewards = np.array(positive_rewards + negative_rewards)
sigma_r = all_rewards.std()
#acomodar los rollauts por el max (r_pos, r_neg) y seleccionar la mejor dirección
scores = {k:max(r_pos, r_neg) for k, (r_pos, r_neg) in enumerate(zip(positive_rewards, negative_rewards))}
order = sorted(scores.keys(), key = lambda x:scores[x])[:hp.nb_best_directions]
rollouts = [(positive_rewards[k], negative_rewards[k], deltas[k]) for k in order]
#actualizar policy
policy.update (rollouts, sigma_r)
#poner el final reward del policy luego del update
reward_evaluation = explore (env, normalizer, policy)
print('Paso: ', step, 'Lejania: ', reward_evaluation)
def mkdir(base, name):
path = os.path.join(base, name)
if not os.path.exists(path):
os.makedirs(path)
return path
work_dir = mkdir('exp', 'brs')
monitor_dir = mkdir(work_dir, 'monitor')
hp = Hp()
np.random.seed(hp.seed)
env = gym.make(hp.env_name)
env = wrappers.Monitor(env, monitor_dir, force = True)
nb_inputs = env.observation_space.shape[0]
nb_outputs = env.action_space.shape[0]
policy = Policy(nb_inputs, nb_outputs)
normalizer = Normalizer(nb_inputs)
train(env, policy, normalizer, hp)
In the end, I think it was either a thing of an old version of ffmpeg or another compatibility issue (this is my first try with linux and I could not update ffmpeg properly). I changed my virtual environment from Ubunto 16.04 to Debian. It worked perfectly.

Rostopic pub equivalent in Python

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

How can i show index on the input of user?

I can show for user the number of task, example: input('Start task 1:' )
n = input('Digite o numero de trabalhos: ')
i = 0
job = []
while(i != n):
start_job1 = int(input('Inicio da tarefa: ' ))
final_job1 = int(input('Final da tarefa: '))
lucro_job1 = int(input('Valor da tarefa: '))
job.append(Job(start_job1, final_job1, lucro_job1))
i = i+1
print("Melhor lucro sera: "),
print schedule(job)
You can format your string with the str.format method:
start_job1 = int(input('Inicio da tarefa {}: '.format(i + 1)))
or with the string formatting operator:
start_job1 = int(input('Inicio da tarefa %d: ' % (i + 1)))

Categories