Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Tuesday, February 18, 2020

japanese text in myplotlib

import matplotlib

matplotlib.rcParams['font.sans-serif'] =["Noto Sans CJK JP"]
matplotlib.rcParams['font.serif']=["Noto Serif CJK JP"]

Monday, April 1, 2019

Matplotlib under pyenv

gtk3agg backend works


sudo apt install libgirepository1.0-dev
pip install pycairo cairocffi pygobject

....
import matplotlib
matplotlib.use('gtk3agg')
import matplotlib.pyplot as plt

Monday, November 26, 2018

Thursday, June 2, 2016

Example of numpy and c integration by ctype

example.c

#include <sys/types.h>

//sum by rows only the elements less than th
void sumLowerThan(double* res, double *a, ssize_t* dims,double th)
{
  int i,j;double v;
  for (i=0; i<dims[0]; i++) {
    res[i]=0;
    for (j=0;j<dims[1];j++){
      v=a[i*dims[1]+j];
      if (v<th){
        res[i]+=v;
      }     
    }//for j   
  }
}

compile with

gcc -shared -Wl,-soname,example -o example.so -fPIC example.c

example.py

#!/usr/bin/env python
import ctypes
import numpy as np


lib = np.ctypeslib.load_library('example', '.')

lib.sumLowerThan.restype = None
lib.sumLowerThan.argtypes = [np.ctypeslib.ndpointer(float, ndim=1,  # res
                                                    flags='aligned, contiguous, writeable'),
                             np.ctypeslib.ndpointer(float, ndim=2,  # a
                                                    flags='aligned, contiguous'),
                             ctypes.POINTER(np.ctypeslib.c_intp),  # dims
                             ctypes.c_double,  # th
                             ]


def sumLowerThan(a, th):
    a = np.require(a, float, ['CONTIGUOUS', 'ALIGNED'])
    res = np.require(np.empty(np.size(a, 0)),
                     float, ['CONTIGUOUS', 'ALIGNED', 'WRITEABLE'])
    lib.sumLowerThan(res, a, a.ctypes.shape, th)
    return res


a = np.random.rand(5, 10)
print(a)
print(sumLowerThan(a, 0.5))


sources:
http://stackoverflow.com/questions/5081875/ctypes-beginner
http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.python-as-glue.html






minimal pyqtgraph multithreading plotting example

#!/usr/bin/env python
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import Queue
from threading import Thread


class QtPlotter:

    def __init__(self):
        self.ports = []
        self.timer = pg.QtCore.QTimer()
        self.win = pg.GraphicsWindow()
        self.ax = self.win.addPlot()
        self.timer.timeout.connect(self.update)
        self.timer.start(0)
        self.ax.setAspectLocked(True)

    def getPort(self):
        q = Queue.Queue()
        plt = self.ax.plot()

        self.ports.append((q, plt))
        return q

    def update(self):
        for q, plt in self.ports:
            try:
                    data, color = q.get(block=False)
                    plt.clear()
                    plt.setData(
                        np.asarray(data[0, :]).flatten(),
                        np.asarray(data[1, :]).flatten(), pen=None, symbol="o",
                        symbolPen=pg.mkPen({'color': color, 'width': 2}),
                        symbolSize=1
                    )

            except Queue.Empty:
                pass


def qtLoop():
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()


def example():
    import time
    plotter = QtPlotter()
    curve = plotter.getPort()

    def producer():
        while True:
            curve. put((np.random.random(size=(2, 10)), "#00FFFF"))
            time.sleep(1)

    p = Thread(target=producer)
    p.daemon = True
    p.start()

    qtLoop()

if __name__ == "__main__":
    example()

Thursday, May 12, 2016

auto complete for ein

if
(setq ein:use-auto-complete t)

gives the error
symbol's function definition is void: ac-define-source

then install auto-complete in emacs
(it comes automatically if you install ac-anaconda)


M-x elpy- config tells what is not installed
install it with pip

source:
https://realpython.com/blog/python/emacs-the-best-python-editor/

Sunday, April 24, 2016

jupyter notebook

To have vectorial images
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')

source: http://blog.rtwilson.com/how-to-get-nice-vector-graphics-in-your-exported-pdf-ipython-notebooks/


To disable access tokens edit (create with jupyter-notebook --generate-config)
 .jupyter/jupyter_notebook_config.py

to contain

c.NotebookApp.token = ''
c.NotebookApp.password = ''
c.NotebookApp.disable_check_xsrf = True
 
and optionally
c.NotebookApp.open_browser =False

to have white bg for figs


 ipython profile locate
in the specified folder (~/.ipython/profile_default)  create 

~/.ipython/profile_default/ipython_kernel_config.py
reading
c.InlineBackend.rc = {"figure.facecolor": (1, 1, 1, 1),
                      "axes.facecolor": (1, 1, 1, 1)}


to have inline images

%matplotlib inline
import matplotlib
matplotlib.rcParams["figure.facecolor"]=(1,1,1,1)
matplotlib.rcParams["axes.facecolor"]=(1,1,1,1)

Friday, April 22, 2016

ein ipython notebook

ein does not work when the system variables http_proxy and https_proxy are set.

ein:notebooklist-open

gives the error

REQUEST [error] Error (error) while connecting to http://127.0.0.1:8888/api/contents.
REQUEST [error] Callback is not called when stopping process! Explicitly calling from timer.
ein: [error] Content list call http://127.0.0.1:8888/api/contents/ failed with status timeout.

remove the variables and set the proxies manually.

For ELPA:
(setq url-proxy-services '(("no_proxy" . "127.0.0.1")
                           ("http" . "myproxy.com:8080")))

For erc:
(setq socks-noproxy '("localhost"))
(require 'socks)
(setq erc-server-connect-function 'socks-open-network-stream)
(setq socks-server (list "proxyIdentifier" "myproxy.com" 8080 5))

where 5 is the SOCKS version (can be 4)

to have inline images in emacs, libraries for the images are required, otherwise the following error is reported

Error (websocket): in callback `on-message': error: "Not an image: nil"

in windows
copy bin/libpng16-16.dll and bin/zlib1.dll of
https://sourceforge.net/projects/ezwinports/files/libpng-1.6.12-w32-bin.zip/download

to emacs's bin directory

To enable / disable transparent plots:

import matplotlib
matplotlib.rcParams["figure.facecolor"]=(1,1,1,x)
matplotlib.rcParams["axes.facecolor"]=(1,1,1,x)
where x is the alpha (0 for transparent, 1 for fully opaque)


sources:
 https://www.emacswiki.org/emacs/UrlPackage
https://www.emacswiki.org/emacs/ErcProxy
http://stackoverflow.com/questions/2650041/emacs-under-windows-and-png-files

Thursday, April 21, 2016

ipyhon

to autoreload in ipython type

%load_ext autoreload
%autoreload 2


to make it permanent

create a profile
ipython profile create
  
add in
~/.ipython/profile_default/ipython_config.py (win)
~/.config/ipython/profile_default/ipython_config.py (linux, old ipython)
 ~/.ipython/profile_default/ipython_config.py (linux, new ipython)


the following lines

c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.InteractiveShellApp.exec_lines.append('print("autoreload active")')


source:
http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython/10472712#10472712