Convert values in a list to RGB values - python-3.x

I'm trying the following to convey the value in a list to a list of [R,G,B] values.
data = range(0,6)
minima = min(data)
maxima = max(data)
norm = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.Greys_r)
node_color = []
for d in data:
node_color.append(mapper.to_rgba(d))
The above returns a 4th dimension A. I would like to know if there is a way to obtain only RGB values.

mapper.to_rgba(d) returns a tuple of the form (r, g, b, a). You can directly assign the result to a 4-tuple as r, g, b, a = mapper.to_rgba(d). And then create a triple as (r, g, b) to be stored in a list.
mapper.to_rgba also works when it gets a list or array as parameter, so calling mapper.to_rgba(data) directly gets the list of all rgba-tuples. Via a list comprehension, a new list of rgb-triples can be created:
import matplotlib
from matplotlib import cm
data = range(0, 6)
norm = matplotlib.colors.Normalize(vmin=min(data), vmax=max(data), clip=True)
mapper = cm.ScalarMappable(norm=norm, cmap=cm.Greys_r)
node_color = [(r, g, b) for r, g, b, a in mapper.to_rgba(data)]
PS: The above code gives r, g and b values between 0 and 1. Depending on the application, integer values from 0 to 255 could be needed:
node_color = [(r, g, b) for r, g, b, a in mapper.to_rgba(data, bytes=True)]

Related

MATLAB: Scatter Plot with matrix data

I am trying to perform the scatter plot of X and Y matrices, each of size 54x365, with the following code on MATLAB. The data was extracted from excel.
clc
clear
A = xlsread('Test_data.xlsx', 'Sheet 1', 'F3:NF56');
B = xlsread('Test_data.xlsx', 'Sheet 2', 'F3:NF56');
scatter (A,B)
Although they are of similar size, MATLAB produces the following statement:
Error using scatter (line 44)
X and Y must be vectors of the same length.
Error in Untitled2 (line 11)
scatter(A,B)
Note the following:
A = [ A, B, C, D, E ;
F, G, H, I, J ]
B = [ a, b, c, d, e ;
f, g, h, i, j ]
The variables (A,a), (B,b) and so on are plotted so as to produce a scatter plot.
I need help to perform the scatter plot. Thank you.
Reshaping the arrays as row vectors may allow the scatter() function to plot the data. Here the arrays are reshaped to have dimensions that are 1 by Number_Of_Values in each array.
%Generating random test data%
A = rand(54,365);
B = rand(54,365);
%Reshaping to allow plotting%
Number_Of_Values = numel(A);
A = reshape(A,[1 Number_Of_Values]);
B = reshape(B,[1 Number_Of_Values]);
scatter(A,B);
Ran using MATLAB R2019b

sampling a fixed number of unique pairs from a population

I have a sample of n elements. I want to sub-sample m unique pairs from n.
Is there a simple off-the-self method to do this in python ?
For example, if n = [1,2,3,4,5,6,7] and m = 3, one such sample will be [(1,2),(3,4),(5,6)]
The random module has a sample function which will pick n unique items from a collection. You can then pair them up to create your desired output:
import random
import itertools
data = [1,2,3,4,5,6,7,8,9,10]
m = 3
def pairwise(iterable):
# from the itertools cookbook: https://docs.python.org/3/library/itertools.html#itertools-recipes
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
chosen = random.sample(data, m * 2)
result = pairwise(chosen)
Depending on what you mean precisely with 'random', the answer will differ!
For uniform sampling of unique pairs, assuming all elements of your list are distinct:
import itertools, random
n, m = [1,2,3,4,5,6,7], 3
x = random.sample( list(itertools.permutations(n,2)), m)
print(x) #e.g. [(1,2),(3,4),(5,6)]

How to loop for choosing data in Jupyter Notebook by Python

I have 2 columns in data frames.
Column 1 = Source
Column 2 = Target
My data source
Source Target
A B
W X
B C
C D
C Z
A Z
Z Y
Input = A, The output should be display as below.
Source Target
A B
B C
C D
C Z
A Z
Z Y
I try to code as below but not finished yet.
In [1]:
a = input()
b = []
for Source, Target in zip(data.Source,data.Target):
if Source == a:
b.append(True)
else:
b.append(False)
Input = A
In [2]: is_long = pd.Series(b)
is_long
Out [2]: 0 True
1 False
2 True
3 True
4 ...
In [3]: data[is_long]
Out [3]: Source Target
A B
B C
C D
C Z
A Z
Z Y
As I understood, the idea is:
try in turn each vertice from the source DataFrame,
the current vertice is "OK" when its Source node has been visited
before,
the visited list contains initially only the node given by the user and
should be extended by Target node of each checked vertice.
Start from defining the following class:
class Visitor:
def __init__(self):
self.clear()
def addNode(self, node):
if not self.isVisited(node):
self._nodes.append(node)
def isVisited(self, node):
return node in self._nodes
def clear(self):
self._nodes = []
This class keeps a register of visited nodes. It will be used soon.
Then define a function checking the "continuation criterion" for the current
row:
def isContinued(row, vs):
res = vs.isVisited(row.Source)
if res:
vs.addNode(row.Target)
return res
The first argument is the current row and the second is a Visitor object.
Then run:
vs = Visitor()
vs.addNode(a)
df[df.apply(isContinued, axis=1, vs=vs)]
The first line creates a Visitor object.
The second adds the "starting node" (just given by the user) to the
"visited list".
Then df.apply(isContinued, axis=1, vs=vs) creates a Boolean vector
- the continuation criteria for edges.
As isContinued function is applied to subsequent edges, the "visited list"
is extended with Target node.
The (just updated) visited list is then used to compute the continuation
criteria for subsequent edges.
The result is a list of edges meeting the continuation criterion.

Python partial derivative

I am trying to put numbers in a function that has partial derivatives but I can't find a correct way to do it,I have searched all the internet and I always get an error.Here is the code:
from sympy import symbols,diff
import sympy as sp
import numpy as np
from scipy.misc import derivative
a, b, c, d, e, g, h, x= symbols('a b c d e g h x', real=True)
da=0.1
db=0.2
dc=0.05
dd=0
de=0
dg=0
dh=0
f = 4*a*b+a*sp.sin(c)+a**3+c**8*b
x = sp.sqrt(pow(diff(f, a)*da, 2)+pow(diff(f, b)*db, 2)+pow(diff(f, c)*dc, 2))
def F(a, b, c):
return x
print(derivative(F(2 ,3 ,5)))
I get the following error: derivative() missing 1 required positional argument: 'x0'
I am new to python so maybe it's a stupid question but I would feel grateful if someone helped me.
You can find three partial derivatives of function foo by variables a, b and c at the point (2,3,5):
f = 4*a*b+a*sp.sin(c)+a**3+c**8*b
foo = sp.sqrt(pow(diff(f, a)*da, 2)+pow(diff(f, b)*db, 2)+pow(diff(f, c)*dc, 2))
foo_da = diff(foo, a)
foo_db = diff(foo, b)
foo_dc = diff(foo, c)
print(foo_da," = ", float(foo_da.subs({a:2, b:3, c:5})))
print(foo_db," = ", float(foo_db.subs({a:2, b:3, c:5})))
print(foo_dc," = ", float(foo_dc.subs({a:2, b:3, c:5})))
I have used a python package 'sympy' to perform the partial derivative. The point at which the partial derivative is to be evaluated is val. The argument 'val' can be passed as a list or tuple.
# Sympy implementation to return the derivative of a function in x,y
# Enter ginput as a string expression in x and y and val as 1x2 array
def partial_derivative_x_y(ginput,der_var,val):
import sympy as sp
x,y = sp.symbols('x y')
function = lambda x,y: ginput
derivative_x = sp.lambdify((x,y),sp.diff(function(x,y),x))
derivative_y = sp.lambdify((x,y),sp.diff(function(x,y),y))
if der_var == 'x' :
return derivative_x(val[0],val[1])
if der_var == 'y' :
return derivative_y(val[0],val[1])
input1 = 'x*y**2 + 5*log(x*y +x**7) + 99'
partial_derivative_x_y(input1,'y',(3,1))

Lambifying Nested Parametric Integrals

I have a loss function L(u1,...,un) that takes the form
L(u) = Integral( (I**2 + J**2) * h, (t,c,d) ) //h=h(t), I=I(t,u)
where
I = Integral( f, (x,a,b) ) // f=f(x,t,u)
J = Integral( g, (x,a,b) ) // g=g(x,t,u)
I want to numerically minimize L with scipy, hence I need to lambdify the expression.
However at this point in time lambdify does not natively support translating integrals. With some tricks one can get it to work with single parametric integrals, see Lambdify A Parametric Integral. However I don't see how the proposed solution could possibly be extended to this generalised case.
One idea that in principle should work is the following:
Take the computational graph defining L. Recursively, starting from the leaves, replace each symbolic operation with the corresponding numerical operation, expressed as a lambda function. However this would lead to an immense nesting of lambda function, which I suspect has a very bad influence on performance.
Ideally we would want to arrive at the same result as one would by hand crafting:
L = lambda u: quad(lambda t: (quad(lambda x: f,a,b)[0]**2
+ quad(lambda x: g,a,b)[0]**2)*h, c, d)[0]
MWE: (using code from old thread)
from sympy import *
from scipy.integrate import quad
import numpy as np
def integral_as_quad(function, limits):
x, a, b = limits
param = tuple(function.free_symbols - {x})
f = sp.lambdify((x, *param), function, modules=['numpy'])
return quad(f, a, b, args=param)[0]
x,a,b,t = sp.symbols('x a b t')
f = (x/t-a)**2
g = (x/t-b)**2
h = exp(-t)
I = Integral( f**2,(x,0,1))
J = Integral( g**2,(x,0,1))
K = Integral( (I**2 + J**2)*h,(t,1,+oo))
F = lambdify( (a,b), K, modules=['sympy',{"Integral": integral_as_quad}])
L = lambda a,b: quad(lambda t: (quad(lambda x: (x/t-a)**2,0,1)[0]**2
+ quad(lambda x: (x/t-b)**2,0,1)[0]**2)*np.exp(-t), 1, np.inf)[0]
display(F(1,1))
display(type(F(1,1)))
display(L(1,1))

Resources