Widget in HeatMap with Holoviews - widget

I want add a widget in my HeatMap with Holoviews.
For istance, I have:
z, a, b = np.histogram2d(df['a'], df['b'])
hv.Image((a, b, z), ['a', 'b'], 'Count')
and I want a widget that let me change a third variable (like "Symbol" in the follow example: http://holoviews.org/user_guide/Dashboards.html )
This is my HeatMap:
z, a, b = np.histogram2d(data['X'],data['Y'])
hv.Image((a, b, z), ['X', 'Y'], 'Count')
And I would do something like the follow but with the prewious plot (the HeatMap):
ds = hv.Dataset(data, kdims=['X', 'Y'], vdims=['Z'])
ds.to(hv.Curve, kdims=['X'], vdims=['Y'], groupby=['Z'])

z, a, b = np.histogram2d(data['X'],data['Y'])
hv.Image((a, b, z), ['X', 'Y'], 'Count')
and I would add the widget for the variable 'Z'

Related

SML Binary Search Tree Insert Function

I am new to SML and am trying to implement a BST. I have figured out how to parse through the tree, but am struggling with creating an insert function. I want the function to be: insert(bst, key, value) of type BST * int * int -> BST where it inserts a key-value pair into a given tree and returns the resulting tree. I am struggling in the creation of this though, because I get a bit confused on making sure the function is of the right type.
Here is my code so far, I have included an example tree as well
(* left subtree, right subtree, key, value *)
datatype BST = Empty | Node of BST * BST * int * int;
fun parsePost [] = Empty
| parsePost lst =
let
fun pP(stack, (0, k, v)::str) = pP(Node(Empty, Empty, k, v)::stack, str)
| pP(L::stack, (1, k, v)::str) = pP(Node(L, Empty, k, v)::stack, str)
| pP(R::stack, (2, k, v)::str) = pP(Node(Empty, R, k, v)::stack, str)
| pP(R::L::stack, (3, k, v)::str) = pP(Node(L, R, k, v)::stack, str)
| pP(T::stack, []) = T;
in
pP([], lst)
end;
val exTree1 = [(0, 1, 1), (0, 3, 3), (3, 2, 2)];
I was thinking of starting off the insert function as so:
fun insert(Empty, x, y) = Empty
But I am not quite sure where to go from there.
If you insert a key and value pair into an empty tree, do you really expect to get an empty tree back? I very much doubt this is what you'd expect.
Rather you'd probably expect a tree with that pair, but with empty branches.
fun insert(Empty, x, y) = Node(Empty, Empty, x, y)
What if the tree is not empty, though?
Let's consider a simple example:
val ex1 = Node(Empty, Empty, 1, 4)
This looks like:
(1,4)
/ \
/ \
/ \
Empty Empty
Well, if we evaluate insert(ex1, 2, 5) then presumably the result should look like:
(1,4)
/ \
/ \
/ \
Empty (2,5)
/ \
/ \
/ \
Empty Empty
To get this we have to realize that the right branch is the same result we'd get if we evaluated insert(Empty, 2, 5).
(2,5)
/ \
/ \
/ \
Empty Empty
So as the tree data type is recursive, so is your solution. We need to check if the key you want to insert is the same as the key already stored in a node. If it is, we don't have to change anything.
If it's less than the key already present, we insert into the left branch, and if it's greater than, we insert into the right branch.
fun insert(Empty, x, y) = Node(Empty, Empty, x, y)
| insert((n as Node(l, r, k, v)), x, y) =
case Int.compare(x, k) of
EQUAL => n
| LESS => Node(insert(l, x, y), r, k, v)
| GREATER => Node(l, insert(r, x, y), k, v)
This strategy scales to any depth of tree structure, because eventually a branch will always either contain the key you're looking for, or have an empty branch.

Multiple functions inside of a function in R

I'd like to create a function called g which in turn contains three other functions f1 and f2. Each of the two functions f1, f2 returns a data frame. I would like that the function g returns the two dataframe obtained from f1 and f2. Here is the code that I run:
g <- function(n,a,b,c,d,e) {
f1 <- function(n,a,b,c,d,e) {
X <- a*matrix(sample(0:1,n,replace = T),nrow=n,ncol=1)
Y <- (b*c-d)*matrix(sample(1:10,n,replace = T),nrow=n,ncol=1)
Z <- (a*e)*matrix(sample(0:12,n,replace = T),nrow=n,ncol=1)
data1 <- as.data.frame(cbind(X,Y,Z))
colnames(data1) <- c("X","Y","Z")
return(data1)
}
f1(n,a,b,c,d,e)
varpredict <- lm(Y ~ 0 + X + Z, data=f1(n,a,b,c,d,e))$fitted.values
h <- function(){
olsreg <- lm(Y ~ 0 + X + Z, data=f1(n,a,b,c,d,e))
P <- olsreg$residuals^2
return(P)
}
h()
G <- rep(0,n)
f2 <- function(n,a,b){
for (i in 1:n) {
G[i] <- varpredict[i]-a
}
X <- matrix(sample(0:1,n,replace = T),nrow=n,ncol=1)+h()
Y <- b*matrix(sample(1:10,n,replace = T),nrow=n,ncol=1)
Z <- (a*b)*matrix(sample(0:12,n,replace = T),nrow=n,ncol=1)-G
data2 <- as.data.frame(cbind(X,Y,Z))
colnames(data2) <- c("X","Y","Z")
return(data2)
}
f2(n,a,b)
return(list(data1,data2))
}
To run the function g I did this:
n=100
a=0.3
b=0.5
c=0.3
d=-1.32
e=c*d
my_function <- g(n,a,b,c,d,e)
But I received the following error message:
Error in g(n, a, b, c, d, e) : object 'data1' not found
Why am I getting this error?
First off, when you call your functions f1 and f2 you need to store their return value somewhere.
Secondly, it’s unclear why you want f1 inside g: it doesn’t seem to share any state with g, so it can be defined independently alongside g instead of inside it. That said, if it’s only ever used inside g then this is to some extent a matter of style.
Here’s how I’d write your code:
g <- function (n, a, b, c, d, e) {
f1 <- function (n, a, b, c, d, e) {
X <- a * matrix(sample(0 : 1, n, replace = TRUE), nrow = n)
Y <- (b * c - d) * matrix(sample(1 : 10, n, replace = TRUE),nrow = n)
Z <- (a * e) * matrix(sample(0 : 12, n, replace = TRUE), nrow = n)
data.frame(X, Y, Z))
}
f2 <- function(n, a, b) {
G <- varpredict - a
X <- matrix(sample(0 : 1, n, replace = TRUE), nrow = n) + square_res
Y <- b * matrix(sample(1 : 10, n, replace = TRUE), nrow = n)
Z <- (a * b) * matrix(sample(0 : 12, n, replace = TRUE), nrow = n) - G
data.frame(X, Y, Z)
}
model <- lm(Y ~ 0 + X + Z, data = f1(n, a, b, c, d, e))
varpredict <- model$fitted.values
square_res <- model$residuals ^ 2
list(f1(n, a, b, c, d, e), f2(n, a, b))
}
I’ve cleaned up the code a bit and I hope you’ll agree that it is more readable this way — it is also more efficient, since it avoids recomputing the initial model over and over again. Apart from that I’ve followed a few simple rules: use consistent spacing, don’t use gratuitous abbreviations (T instead of TRUE), use the appropriate functions to avoid redundant code (e.g. the creation of the data frames), no unnecessary use of returns.
But fundamentally I still have no good idea what it does since the variable names don’t provide any useful information. The most impactful improvement for readability is therefore the choice of better variable names.

Function with vector as argument in Octave

How can I make a function with a vector as input and a matrix as an output?
I have to write a function that will convert cubic meters to liters and English gallons. The input should be a vector containing volume values ​​in m ^ 3 to be converted. The result should be a matrix in which the first column contains the result in m ^ 3, the second liter, the third English gallon.
I tried this:
function [liter, gallon] = function1 (x=[a, b, c, d]);
liter= a-10+d-c;
gallon= b+15+c;
endfunction
You're almost there.
The x=[a,b,c,d] part is superfluous, your argument should be just x.
function [liter, gallon] = function1 (x);
a = x(1); b = x(2); c = x(3); d = x(4);
liter = a - 10 + d - c;
gallon = b + 15 + c;
endfunction
If you want your code to be safe and guard against improper inputs, you can perform such checks manually inside the function, e.g.
assert( nargin < 1 || nargin > 4, "Wrong number of inputs supplied");
The syntax x=[a,b,c,d] does not apply to octave; this is reserved for setting up default arguments, in which case a, b, c, and d should be given specific values that you'd want as the defaults. if you had said something like x = [1,2,3,4], then this would be fine, and it would mean that if you called the function without an argument, it would set x up to this default value.

Haskell - apply tuple of functions to tuple of values?

I have a tuple of values representing some state, and want to translate it by an addition (shift). My values are a longer version of ( Int, [Int], Int), and I want something conceptually (but not literally) like this:
shift n = ??? (+n) (id, map, id) -- simple(?)
which would be equivalent to:
shift n (a, b, c) = (a+n, map (+n) b, c+n)
I am happy to just go with this explicit function usage, but wondered it there was a more idiomatic point-free version using Applicative or Arrows or ..., or if they would just end-up obfuscating things. I thought that the point-free version shows the basic structure of the operation more clearly.
You can just write
shift n (a,b,c) = (a+n, map (+n) b, c+n)
Or define new combinators similar to Arrow's (***) and (&&&),
prod3 (f,g,h) (a,b,c) = (f a, g b, h c) -- cf. (***)
call3 (f,g,h) x = (f x, g x, h x) -- cf. (&&&)
ap3 f (a,b,c) = (f a, f b, f c)
uncurry3 f (a,b,c) = f a b c
and then call
prod3 ( (+n), map (+n), (+n) ) (a,b,c)
or even (with appropriately set operator precedences)
ap3 ($ (+n)) (id, map, id) `prod3` (a,b,c)
Or, if you'd write your triples as nested pairs, you could use
Prelude Control.Arrow> ( (+5) *** map (+5) *** (+5) ) (1,([2,3],4))
(6,([7,8],9))
So for nested pairs,
shift' :: (Num b) => b -> (b, ([b], b)) -> (b, ([b], b))
shift' n = ( (+n) *** map (+n) *** (+n) )
(see also Multiple folds in one pass using generic tuple function)
With the DeriveFunctor language extension you can write
data MyState a = MyState a [a] a
deriving (Functor)
The derived instance looks like
instance Functor MyState where
fmap f (MyState a bs c) = MyState (f a) (map f bs) (f c)
Now you can define
shift :: MyState Int -> MyState Int
shift n = fmap (+n)
(You say your tuple is even longer than (Int, [Int], Int), so you may want to define your state type using record syntax.)
Applying a list of functions to a list of values is simply
zipWith ($)
Since tuples of different sizes are each their own type, you will have to write a function explicitly for 3-tuples. A general function to apply a 3-tuple of functions to a 3-tuple of values is
apply (f, g, h) (a, b, c) = (f a, g b, h c)
You have to explicitly write each function application because tuples don't have the recursive property of lists.

Mapping one list to another (in Haskell, + abstract solution) - 'map reduce'?

Say we have a list of coordinates like:
(1,2)
(0,3)
(4,1)
(0,3)
(-2,3)
(6,5)
And we wanted to result in the following list, which is defined as the summation of each consecutive coordinates. (Sorry bad definition) like so:
(1,5)
(4,4)
(4,4)
(-2,6)
(4,8)
So there exists a set A = (a,b,c,...,n) where a,b,c,...,n are coordinates in R^2.
There exists a function f such that f(A) = B = (a+b,b+c,c+d,...,n-1+n).
~
How would you write something like that in a functional language like Haskell? A program that applies f to a given A to give B.
You can use zip to zip the list with its tail, you get pairs of pairs like [((1,2), (0,3)), ((0,3),(4,1)), ...]. Then you can use map to replace each pair of pairs with its sum. Or you can use zipWith which is basically zip + map in one function, except the function given to zipWith has type a -> b -> c, not (a,b) -> c:
summedCoords = zipWith (\ (a,b) (c,d) -> (a+c, b+d)) coords (tail coords)
You can write a generic function like this
g:: (a -> a -> b) -> [a] -> [b]
g f (x1:x2:xs) = (f x1 x2):(g (x2:xs))
g _ (x1:[]) = []
and pass it your add function
f = g f' where
f' (a,b) (a',b') = (a+a', b+b')