Skip to content

Commit

Permalink
includes CVXR page
Browse files Browse the repository at this point in the history
adds some egs of optimization using CVXR package
  • Loading branch information
jpneto committed Oct 31, 2018
1 parent 0a49d2e commit 27918ba
Show file tree
Hide file tree
Showing 20 changed files with 2,682 additions and 1 deletion.
5 changes: 4 additions & 1 deletion index.htm
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,10 @@ <h3>Math</h3>
<li><a href="inf_theory/informationtheory.html">Information Theory</a></li>
<li><a href="maxent/maxent.html">Maximum Entropy</a></li>
<li><a href="noise/noise.html">Noise</a></li>
<li><a href="optimization/optimization.html">Optimization</a></li>
<li><a href="optimization/optimization.html">Optimization</a><ul>
<li><a href="optimization/CVXR.html">CVXR</a></li>
</ul>
</li>
<li><a href="powerlaw/powerlaw.html">Power Laws</a></li>
<li>Probability<ul>
<li><a href="prob/range.html">Min, Max, Range of Uniform rv's</a></li>
Expand Down
34 changes: 34 additions & 0 deletions langs/Haskell2R/HaskellLib.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
-- HaskellLib.hs
{-# LANGUAGE ForeignFunctionInterface #-}
module HaskellLib where

-- ref: http://neilmitchell.blogspot.pt/2011/10/calling-haskell-from-r.html
-- ref: https://wiki.haskell.org/Foreign_Function_Interface
import Foreign
import Foreign.C.Types

foreign export ccall sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()
foreign export ccall factR :: Ptr CULLong -> Ptr CULLong -> IO ()

-------------------------------

sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()
sumRootsR n xs result =
do
n <- peek n
xs <- peekArray n xs
poke result $ sumRoots xs

sumRoots :: [Double] -> Double
sumRoots xs = sum (map sqrt xs)

--------------------------------

factR :: Ptr CULLong -> Ptr CULLong -> IO ()
factR n result =
do
n <- peek n
poke result $ fact n

fact :: (Integral a) => a -> a
fact n = product [1..n]
15 changes: 15 additions & 0 deletions langs/Haskell2R/StartEnd.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// StartEnd.c
#include <Rts.h>

void HsStart() {
int argc = 1;
char* argv[] = {"ghcDll", NULL}; // argv must end with NULL

// Initialize Haskell runtime
char** args = argv;
hs_init(&argc, &args);
}

void HsEnd() {
hs_exit();
}
6 changes: 6 additions & 0 deletions langs/Haskell2R/_Calling Haskell from R.URL
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[InternetShortcut]
URL=http://neilmitchell.blogspot.pt/2011/10/calling-haskell-from-r.html
IDList=
HotKey=0
IconFile=C:\Users\jpn.INFORMATICA\AppData\Local\Mozilla\Firefox\Profiles\9osfg8r9.default-1447323833552-1512492636402\shortcutCache\adzE8Y2nRQRQcABG1l01VA==.ico
IconIndex=0
6 changes: 6 additions & 0 deletions langs/Haskell2R/_R at native speedusing Haskell.URL
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[InternetShortcut]
URL=https://www.tweag.io/posts/2015-09-08-programming-r-at-native-speed-in-haskell.html
IDList=
HotKey=0
IconFile=C:\Users\jpn.INFORMATICA\AppData\Local\Mozilla\Firefox\Profiles\9osfg8r9.default-1447323833552-1512492636402\shortcutCache\JfLPNT5SLjyl9xnA89vRBQ==.ico
IconIndex=0
8 changes: 8 additions & 0 deletions langs/Haskell2R/make.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
ghc -c HaskellLib.hs
ghc -c StartEnd.c
ghc -shared -o HaskellLib.dll HaskellLib.o StartEnd.o
del *.o
del *.h
del *.hi
del *.a
pause
108 changes: 108 additions & 0 deletions langs/haskell.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
---
title: "Running Haskell in R"
author: "João Neto"
date: "27 de Março de 2018"
output: html_document
---

Ref:

+ [Calling Haskell from R](http://neilmitchell.blogspot.pt/2011/10/calling-haskell-from-r.html)

The Foreign Function Interface (FFI) allows Haskell programs to cooperate with programs written with other languages. Haskell programs can call foreign functions and foreign functions can call Haskell code.

The Foreign Function Interface (FFI) is an extension to the Haskell standard. To use it, you need to enable it with the following compiler pragma at the beginning of your source file: `{-# LANGUAGE ForeignFunctionInterface #-}`

The following code creates a C library with two available functions:

```{r, eval=FALSE}
{-# LANGUAGE ForeignFunctionInterface #-}
module HaskellLib where
import Foreign
import Foreign.C.Types
foreign export ccall sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()
foreign export ccall factR :: Ptr CULLong -> Ptr CULLong -> IO ()
-------------------------------
sumRootsR :: Ptr Int -> Ptr Double -> Ptr Double -> IO ()
sumRootsR n xs result =
do
n <- peek n
xs <- peekArray n xs
poke result $ sumRoots xs
sumRoots :: [Double] -> Double
sumRoots xs = sum (map sqrt xs)
--------------------------------
factR :: Ptr CULLong -> Ptr CULLong -> IO ()
factR n result =
do
n <- peek n
poke result $ fact n
fact :: (Integral a) => a -> a
fact n = product [1..n]
```

For each Haskell function we need a wrapper function that takes compatible C types (`Ptr Int` or `Ptr Double`) and the result is a `IO()`. We use `peek` to fetch input values, and `poke` to output the desired result.

To pass a list we need to pass the size of the list and a pointer to its first value. That's the case with `sumRoots`.

We also need some [helper code](https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/win32-dlls.html) that starts up and shuts down Haskell's Runtime System (RTS):

```{r, eval=FALSE}
#include <Rts.h>
void HsStart() {
int argc = 1;
char* argv[] = {"ghcDll", NULL}; // argv must end with NULL
// Initialize Haskell runtime
char** args = argv;
hs_init(&argc, &args);
}
void HsEnd() {
hs_exit();
}
```

The following cmd instructions compile both files and make the DLL:

```{r, eval=FALSE}
ghc -c SumRoots.hs
ghc -c StartEnd.c
ghc -shared -o SumRoots.dll SumRoots.o StartEnd.o
```

Now we should load the DLL [more info](http://users.stat.umn.edu/~geyer/rc/)) and start Haskell's RTS:

```{r}
dyn.load(".\\HaskellLib.dll") # if needed, include full path
.C("HsStart")
```

For easy access to the Haskell's functions, create wrapper classes:
```{r}
sumRoots <- function(ns) {
return(.C("sumRootsR", n=as.integer(length(ns)),
xs=as.double(ns), result=as.double(0))$result)
}
factHaskell <- function(n) {
return(.C("factR", n=as.integer(n), result=as.integer(0))$result)
}
```

Now we can use them as if they were R functions:

```{r}
sumRoots(c(12,444.34))
factHaskell(20) # overflows for some reason
```

233 changes: 233 additions & 0 deletions langs/haskell.html

Large diffs are not rendered by default.

74 changes: 74 additions & 0 deletions langs/reticulate.Rmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
---
title: "Python+R on RStudio"
output:
html_document:
df_print: paged
---

Reticulate needs `knitr` version 1.18+

```{r}
library(reticulate)
use_python("C:\\Users\\jpn.INFORMATICA\\Software\\_Langs\\WinPython-64bit-3.5.2.3Qt5\\python-3.5.2.amd64")
```

More info about configuration [here](https://rstudio.github.io/reticulate/articles/versions.html).

```{r}
py_available(initialize =TRUE)
py_config()
```



```{python}
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 1, 500)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)
fig, ax = plt.subplots()
ax.fill(x, y, zorder=10)
ax.grid(True, zorder=5)
#plt.savefig('test.png')
plt.show()
```

A variable defined on R

```{r}
xpto=100
```

... can be used on a Python script via object `r`:

```{python}
x = 12 * r.xpto
print(x)
```

And conversely, a Python variable can be used o R via object `py`:

```{r}
py$x
```

It's also possible to access python libraries directly on R scripts:

```{r}
# import numpy and specify no automatic Python to R conversion
np <- import("numpy", convert = FALSE)
# py_help(np$array) # opens a text file with help on this function
# do some array manipulations with NumPy
a <- np$array(c(1:4))
sum <- a$cumsum()
# convert to R explicitly at the end
py_to_r(sum)
```

See more info [here](https://rstudio.github.io/reticulate/articles/calling_python.html).
209 changes: 209 additions & 0 deletions langs/reticulate.html

Large diffs are not rendered by default.

Loading

0 comments on commit 27918ba

Please sign in to comment.