Matrix With X Lines and Y Colums and Random Numbers in python - python-3.9

Im doing a project for Uni in python, and i want to creat a matrix with X number of lines and Y number of colums and all the numbers would be between 0 and 1 (int). I did some code but it's not working properly and i don't know how to fix it.
import numpy as np
import random
x=int(input(print('l?')))
y=int(input(print('c?')))
R=np.random.ranint(2,size(x,y))
It's always showing this type of error : AttributeError: module 'numpy.random' has no attribute 'ranint'

Related

Unexpected results from sum using gekko variable

I am optimizing a simple problem where I am summing intermediate variables for a constraint where the sum needs to be lower than a certain budget.
When I print the sum, either using sum or np.sum, I get the following results:(((((((((((((((((((((((((((((i429+i430)+i431)+i432)+i433)+i434)+i435)+i436)+i437)+i438)+i439)+i440)+i441)+i442)+i443)+i444)+i445)+i446)+i447)+i448)+i449)+i450)+i451)+i452)+i453)+i454)+i455)+i456)+i457)+i458)
Here is the command to create the variables and the sum.
x = m.Array(m.Var, (len(bounds)),integer=True)
sums = [m.Intermediate(objective_inverse2(x,y)) for x,y in zip(x,reg_feats)]
My understanding of the intermediate variable is a variable which is dynamically calculated based on the value of x, which are decision variables.
Here is the summing function for the max budget constraint.
m.Equation(np.sum(sums) < max_budget)
Solving the problem returns an error saying there are no feasible solution, even through trivial solutions exist. Furthermore, removing this constraint returns a solution which naturally does not violate the max budget constraint.
What am I misunderstanding about the intermediate variable and how to sum them.
It is difficult to diagnose the problem without a complete, minimal problem. Here is an attempt to recreate the problem:
from gekko import GEKKO
import numpy as np
m = GEKKO()
nb = 5
x = m.Array(m.Var,nb,value=1,lb=0,ub=1,integer=True)
y = m.Array(m.Var,nb,lb=0)
i = [] # intermediate list
for xi,yi in zip(x,y):
i.append(m.Intermediate(xi*yi))
m.Maximize(m.sum(i))
m.Equation(m.sum(i)<=100)
m.options.SOLVER = 1
m.solve()
print(x)
print(y)
Instead of creating a list of Intermediates, the summation can also happen with the result of the list comprehension. This way, only one Intermediate value is created.
from gekko import GEKKO
import numpy as np
m = GEKKO()
nb = 5
x = m.Array(m.Var,nb,value=1,lb=0,ub=1,integer=True)
y = m.Array(m.Var,nb,lb=0)
sums = m.Intermediate(m.sum([xi*yi for xi,yi in zip(x,y)]))
m.Maximize(sums)
m.Equation(sums<=100)
m.options.SOLVER = 1
m.solve()
print(sums.value)
print(x)
print(y)
In both cases, the optimal solution is:
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 1.560000001336448E-002 sec
Objective : -100.000000000000
Successful solution
---------------------------------------------------
[100.0]
[[1.0] [1.0] [1.0] [1.0] [1.0]]
[[20.0] [20.0] [20.0] [20.0] [20.0]]
Try using the Gekko m.sum() function to improve solution efficiency, especially for large problems.

Conditional expectation with sympy

How can I calculate the conditional expectation of a random variable in sympy? I read this and tried:
from sympy.stats import *
v = Uniform("v",0,1)
E(v)
this returns correctly 1/2, but then:
E(v, v>1/2)
returns NaN. I also tried:
E(v, where(v > 1/2))
it returned 1/2, which is incorrect (it should be 3/4).
What am I doing wrong?
This issue (which I see you already reported) is specific to uniformly distributed random variables. (There's also an older issue involving Uniform.) For other distributions, what you did works correctly:
>>> from sympy.stats import *
>>> x = Exponential("x", 1)
>>> E(x, x < 2)
-3/(-1 + exp(2)) + exp(2)/(-1 + exp(2))
As for the uniform type, a workaround for now is to remember that conditioning a uniformly distributed random variable to some interval creates another uniformly distributed random variable.
So the value of E(v, v > 1/2) can be found by computing
E(Uniform("x", 1/2, 1))
which returns 0.75.
Caution: if working interactively, one may want to eventually import from core SymPy, in addition to its stats module. Since E stands for Euler's number 2.718... in SymPy, one may end up unable to compute expectations with
TypeError: 'Exp1' object is not callable
So one either has to be more specific about what to import, or use namespace for one or both modules. My preferred solution is
from sympy import *
import sympy.stats as st
So that st.E is expectation while E is 2.718...

Pyomo summation of a product of a matrix by a vector

I edit my code including all the parameters and variables involved:
(D is a numpy matrix imported from Python)
import pyomo
from pyomo.environ import *
from array import *
import numpy as np
import scipy as sp
from diff_matrix import D ##N=10????
print(D)
m =ConcreteModel()
...
m.n = Param(initialize = 10, within = Integers)
m.Ns = Set(initialize = range(0,value(m.n)))
m.x1 = Var(m.N, domain = Reals)
m.D = Param(m.N, m.N, initialize=D)
m.f_x1 = Var(m.N)
def f_x1_definition(model,i):
return m.f_x1[i] == sum(m.x1[j]*m.D[i,j] for j in range(value(m.n)))
m.f_x1_const = Constraint(m.Ns, rule = f_x1_definition)
But I get the next error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Any help?
The simplest thing is to just use the Python sum() function instead of the Pyomo summation() function:
def f_x1_definition(model,i):
return model.f_x1[i] == sum(model.x1[j]*model.D[i,j] for j in range(value(model.n)))
Also, note that I reversed the order of the Pyomo Var (m.x1) and the matrix (m.D). Based on your other questions (Importing a matrix from Python to Pyomo), I am assuming that the matrix is a NumPy matrix. When multiplying a NumPy value and a Pyomo component (Var or Param), always put the Pyomo object first. This is due to a conflict between the NumPy operator overloading and the Pyomo operator overloading in current versions of Pyomo (up through at least 5.1).
EDIT 1: Note on reversing the order of operands: in your original question, it was not clear that m.D was being defined as a Pyomo Param. There is no concern with the order of Pyomo objects in expressions. The operator overloading problem mentioned above is only when multiplying NumPy objects with Pyomo components. Further, at this time (up through Pyomo 5.1), Pyomo does not support matrix algebra - that is, operations like matrix-matrix or matrix-vector products. Since every expression is a scalar expression, the ordering of the terms in a commutative operation (+, *) does not change the meaning of the expression.
EDIT 2: Your error has nothing to do with the sum/summation you originally posted. The problem is with how you are initializing your Param. At this time (up through Pyomo 5.1), you cannot directly initialize a Param from a numpy.ndarray. You need to first convert the NumPy object into a Python dictionary with something like:
m.D = Param(m.N, m.N, initialize=dict(((i,j),D[i,j]) for i in m.N for j in m.N))

generation of random binary numbers in python

I want to print or plot list of binary numbers which are randomly generated. I have print and plot random numbers between 1 and 5000 and my code is as under;
generation of random numbers
for a in range(0, 5000):
a=random.sample(range(0, 5000), 5000)
print (a)
plt.plot(a)
plt.show()
This code is running perfectly.
but I want Binary numbers instead of Decimal numbers.
kindly help me in this regard.
To get the binary representation of your random generated number (decimal int) , use bin()
For instance, the following code will print 10 random numbers. in decimal and binary
import random
for i in range(0, 10):
a = random.randint(0, 5000)
print a, bin(a)
output:
1465 0b10110111001
1624 0b11001011000
2963 0b101110010011
510 0b111111110
3653 0b111001000101
3671 0b111001010111
2624 0b101001000000
4412 0b1000100111100
3910 0b111101000110
2582 0b101000010110
Online demo - https://repl.it/Dx3O
NOTE: in your example i saw some usage in matplotlib however you weren't explicitly asking about matplotlib so i answered more generally

DataFrame, count unique values, Java

I have a DataFrame and I want to count the uniqe lines of two columns in this Data Frame. For example:
a x
a x
a y
b y
b y
b y
should be to:
a x 2
a y 1
b y 3
I know the solution for this operation in pandas DataFrame, but now I want to do it direct in Java (the best way is Java 8).
I am not sure what input type you have, but assuming you have a List<DataFrame> list and DataFrame implements equals/hashcode as expected, you could use a combination of two collectors:
Map<DataFrame, Long> count = list.stream().collect(groupingBy(x -> x, counting()));
which requires the following static imports:
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
I have found the next solution by myself. Copy here, if somebody has an interest....
DataFrame df2 = df.groupBy("Column_one", "Column_two").count();
df2.show();

Resources