Kivy and matplotlib? - python-2.7

I just wanted to know if matplotlib is compatible with kivy 1.9.0, and how I do I go about implementing it if it's possible? If it's isn't supported, does kivy have something very similar to it?
I want to able use this particular code from one my programs in my kivy app:
def printPieChart(table, column):
if column == 6:
columnList = table.iloc[:, -1:].values.T.ravel()
else:
columnList = table.iloc[:, (column - 7): (column - 6)].values.T.ravel()
countedList = Counter(columnList)
#set up the size of the pie chart
fig = plt.figure(figsize=[10, 10])
ax = fig.add_subplot(111)
cmap = plt.cm.prism
#input variables for pie function
slices = [float(v) for v in countedList.values()]
colors = cmap(np.linspace(0., 1., len(slices)))
labels = [float(k) for k in countedList]
columnHeaders = list(table.columns.values)
#the pie chart
pie_wedge_collection = ax.pie(slices, colors = colors, labels = labels, labeldistance = 1.05, autopct = '%1.1f%%')
#get rid of the black outlines between the wedges and around the pie
for pie_wedge in pie_wedge_collection[0]:
pie_wedge.set_edgecolor('white')
ax.set_title(columnHeaders[column + 1])
If I wanted to make a compilation recipe for matplotlib would it be along these lines?
#!/bin/bash
VERSION_matplotlib=${VERSION_matplotlib:-1.4.3}
DEPS_matplotlib=(numpy python dateutil pyparsing six linpng pytz freetype agg PyCXX qhull ttconv)
URL_matplotlib=http://pypi.python.org/packages/source/m/matplotlib/matplotlib-$VERSION_matplotlib.tar.gz
MD5_matplotlib=f43c20480a1673185afefc7d4848a1d2
BUILD_matplotlib=$BUILD_PATH/matplotlib/$(get_directory $URL_matplotlib)
RECIPE_matplotlib=$RECIPES_PATH/matplotlib
# function called for preparing source code if needed
# (you can apply patch etc here.)
function prebuild_matplotlib() {
true
}
function shouldbuild_lxml() {
if [ -d "$SITEPACKAGES_PATH/matplotlib" ]; then
DO_BUILD=0
fi
}
# function called to build the source code
function build_matplotlib() {
cd $BUILD_matplotlib
push_arm
export CC="$CC -I$BUILD_numpy/"
export LDFLAGS="-L$BUILD_numpy/numpy/.libs -L$BUILD_numpy/numpy/.libs -L$BUILD_numpy/.libs -L$BUILD_numpy/numpy -L$BUILD_numpy/numpy -L$BUILD_numpy/ $LDFLAGS"
export LDSHARED="$LIBLINK"
chmod +x $BUILD_numpy/numpy-config
export PATH=$PATH:$BUILD_numpy
#plus more for the other dependencies
try $HOSTPYTHON setup.py build_ext -I$BUILD_matplotlib
try find . -iname '*.pyx' -exec $CYTHON {} \;
try $HOSTPYTHON setup.py build_ext -v
try find build/lib.* -name "*.o" -exec $STRIP {} \;
export PYTHONPATH=$BUILD_hostpython/Lib/site-packages
try $BUILD_hostpython/hostpython setup.py install -O2 --root=$BUILD_PATH/python-install --install-lib=lib/python2.7/site-packages
unset LDSHARED
pop_arm
}
# function called after all the compile have been done
function postbuild_matplotlib() {
true
}

You can call matplotlib from a kivy script fine, exactly as you normally would, but kivy has no built in way to display plots - you'd have to get matplotlib to render them (e.g. as png, or you could try kivy's experimental svg support but it might be buggy) then display them in an Image widget or similar.
If you want to do this on android or ios, you'd need a compilation recipe for matplotlib, as I don't think we have one yet. I think that shouldn't be too hard and we'd be happy to discuss if if you're interested.
We do have a GSoC student working on giving us proper matplotlib support, so there may be good news on it in the next few months.

Related

Is there a way to directly make use of SMOTE to a xxx.csv in python-weka-wrapper3

For example,I have a data-set,which has 18 instances(class value:True:False=12:6),and it has 11 attributes.Can just make use SMOTE in python like in weka?
How can I make it by code?
enter image description here
Have you looked at the API examples and the example repository? These resources explain most if not all of the available functionality.
Here is an example of loading a CSV file and applying the SMOTE filter:
import weka.core.jvm as jvm
from weka.core.classes import from_commandline
from weka.core.packages import install_missing_package, installed_package
from weka.core.converters import load_any_file
jvm.start(packages=True)
# install SMOTE if necessary
installed = installed_package("SMOTE")
if not installed:
success, restart = install_missing_package("SMOTE")
if restart:
print("Please rerun script")
jvm.stop()
import sys
sys.exit(0)
# load data
data = load_any_file("/some/where/iris.csv", class_index="last")
# if the default parameters for loading the CSV file don't work,
# you need to configure the CSVLoader yourself and set the
# appropriate options (or even use a 3rd-party package):
# from weka.core.converters import Loader
# loader = Loader(classname="weka.core.converters.CSVLoader", options=[])
# data = loader.load_file("/some/where/iris.csv", class_index="last")
print(data.num_instances)
# apply SMOTE
# replace the command-line with the one that you can copy/paste from
# the Weka Explorer via right-click menu
smote = from_commandline("weka.filters.supervised.instance.SMOTE -C 0 -K 5 -P 100.0 -S 1", classname="weka.filters.Filter")
smote.inputformat(data)
filtered = smote.filter(data)
print(filtered.num_instances)
jvm.stop()

Pyqt4 to Pyqt5 and python code error

i switch from Pyqt4 to Pyqt5 and from python2.7 to 3.4 and i found a bug in Pyqt5 so i upgrade it to the last version which is not suppoted by python3.4 . than i used python3.5 and it work fine except one module called pymaxwell.
always the app crash and closed and to confirm i go back to python2.7 and i use pyqt5 for python2.7 and the same error ; the app closed immediately and show me an error in a part in the code which is work well with pyqt4.
in the gif a comparaison between Pyqt4/Pyqt5 with python2.7
comparison
the part of the code which have problem:
self.btnMXSmxm()
self.mxs_filt.setChecked(True)
self.show_folder.setChecked(False)
inPath = self.input_mxs_scene_2.text();
self.input_mxs_scene.setText(inPath);
self.mxm_list.clear()
if len(inPath) == 0:
self.chosen_material.clear()
# loop over all mxs
else:
mxsList = self.input_mxs_scene.text()
print mxsList
if not len(mxsList) == 0:
scene = Cmaxwell(mwcallback);
ok = scene.readMXS(mxsList);
sceneMaterials = scene.getMaterialNames();
materialcount = int(scene.getMaterialsCount()[0])
if os.path.isfile(self.input_mxs_scene.text()):
for name in sceneMaterials:
scenematerial = scene.getMaterial(name)
problem solved;
i use python 3.5.4 and pyqt 5.9
now even i use read(file) or read(str(file)) don't give any error.
and i find that with pyqt5 it need new arrangement of some lines in the code.
i modify the code and it work :
mxsList = self.input_mxs_scene.text()
scene = Cmaxwell(mwcallback)
materialcount = int(scene.getMaterialsCount()[0])
if not len(inPath) == 0:
if os.path.isfile(self.input_mxs_scene.text()):
ok = scene.readMXS(mxsList)
sceneMaterials = scene.getMaterialNames()
if not len(mxsList) == 0:
for name in sceneMaterials:
scenematerial = scene.getMaterial(name)
# #print scenematerial
self.mxm_list.addItem(name)
i also add : from PyQt5.QtCore import *
that solve other problem with reading media files
after many tries with different versions of python and pyqt5 ; the best versions works well together , python 2.7.9 and pyqt5 from github :
PyQt 5.7.1 for Python 2.7

python + wx & uno to fill libreoffice using ubuntu 14.04

I collected user data using a wx python gui and than I used uno to fill this data into an openoffice document under ubuntu 10.xx
user + my-script ( +empty document ) --> prefilled document
After upgrading to ubuntu 14.04 uno doesn't work with python 2.7 anymore and now we have libreoffice instead of openoffice in ubuntu. when I try to run my python2.7 code, it says:
ImportError: No module named uno
How could I bring it back to work?
what I tried:
installed https://pypi.python.org/pypi/unotools v0.3.3
sudo apt-get install libreoffice-script-provider-python
converted the code to python3 and got uno importable, but wx is not importable in python3 :-/
ImportError: No module named 'wx'
googled and read python3 only works with wx phoenix
so tried to install: http://wxpython.org/Phoenix/snapshot-builds/
but wasn't able to get it to run with python3
is there a way to get the uno bridge to work with py2.7 under ubuntu 14.04?
Or how to get wx to run with py3?
what else could I try?
Create a python macro in LibreOffice that will do the work of inserting the data into LibreOffice and then in your python 2.7 code envoke the macro.
As the macro is running from with LibreOffice it will use python3.
Here is an example of how to envoke a LibreOffice macro from the command line:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
##
# a python script to run a libreoffice python macro externally
# NOTE: for this to run start libreoffice in the following manner
# soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore
# OR
# nohup soffice "--accept=socket,host=127.0.0.1,port=2002,tcpNoDelay=1;urp;" --writer --norestore &
#
import uno
from com.sun.star.connection import NoConnectException
from com.sun.star.uno import RuntimeException
from com.sun.star.uno import Exception
from com.sun.star.lang import IllegalArgumentException
def uno_directmacro(*args):
localContext = uno.getComponentContext()
localsmgr = localContext.ServiceManager
resolver = localsmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
try:
ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
except NoConnectException as e:
print ("LibreOffice is not running or not listening on the port given - ("+e.Message+")")
return
msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
sp = msp.createScriptProvider("")
scriptx = sp.getScript('vnd.sun.star.script:directmacro.py$directmacro?language=Python&location=user')
try:
scriptx.invoke((), (), ())
except IllegalArgumentException as e:
print ("The command given is invalid ( "+ e.Message+ ")")
return
except RuntimeException as e:
print("An unknown error occurred: " + e.Message)
return
except Exception as e:
print ("Script error ( "+ e.Message+ ")")
print(e)
return
return(None)
uno_directmacro()
And this is the corresponding macro code within LibreOffice called "directmacro.py" and stored in the User area for libreOffice macros (which would normally be $HOME/.config/libreoffice/4/user/Scripts/python :
#!/usr/bin/python
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY
from com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE
from com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX
def directmacro(*args):
import socket, time
class FontSlant():
from com.sun.star.awt.FontSlant import (NONE, ITALIC,)
#get the doc from the scripting context which is made available to all scripts
desktop = XSCRIPTCONTEXT.getDesktop()
model = desktop.getCurrentComponent()
text = model.Text
tRange = text.End
cursor = desktop.getCurrentComponent().getCurrentController().getViewCursor()
doc = XSCRIPTCONTEXT.getDocument()
parentwindow = doc.CurrentController.Frame.ContainerWindow
# your cannot insert simple text and text into a table with the same method
# so we have to know if we are in a table or not.
# oTable and oCurCell will be null if we are not in a table
oTable = cursor.TextTable
oCurCell = cursor.Cell
insert_text = "This is text inserted into a LibreOffice Document\ndirectly from a macro called externally"
Text_Italic = FontSlant.ITALIC
Text_None = FontSlant.NONE
cursor.CharPosture=Text_Italic
if oCurCell == None: # Are we inserting into a table or not?
text.insertString(cursor, insert_text, 0)
else:
cell = oTable.getCellByName(oCurCell.CellName)
cell.insertString(cursor, insert_text, False)
cursor.CharPosture=Text_None
return None
You will of course need to adapt the code to either accept data as arguments, read it from a file or whatever.
Ideally I would say use python 3, because python 2 is becoming outdated. The switch requires quite a bit of new coding changes, but better sooner than later. So I tried:
sudo pip3 install -U --pre \
-f http://wxpython.org/Phoenix/snapshot-builds/ \
wxPython_Phoenix
However this gave me errors, and I didn't want to spend the next couple of days working through them. Probably the pre-release versions are not ready for prime time yet.
So instead, what I recommend is to switch to AOO for now. See https://stackoverflow.com/a/27980255/5100564 for instructions. AOO does not have all the latest features that LO has, but it is a good solid Office product.
Apparently it is also possible to rebuild LibreOffice with python 2 using this script: https://gist.github.com/hbrunn/6f4a007a6ff7f75c0f8b

Convert pdf to jpg using python 2.7- an error

I try to find a simple python code that convert hundred of pdf files to jpg files to the same folder where the pdf files located. I use this code from Python Wand converts from PDF to JPG background is incorrect
from wand.image import Image
from wand.color import Color
import os, os.path, sys
def pdf2jpg(source_file, target_file, dest_width, dest_height):
RESOLUTION = 300
ret = True
try:
with Image(filename=source_file, resolution=(RESOLUTION,RESOLUTION)) as img:
img.background_color = Color('white')
img_width = img.width
ratio = dest_width / img_width
img.resize(dest_width, int(ratio * img.height))
img.format = 'jpeg'
img.save(filename = target_file)
except Exception as e:
ret = False
return ret
if __name__ == "__main__":
source_file = r"C:\Users\yaron.KAYAMOT\Desktop\aaa.pdf"
target_file = r"C:\Users\yaron.KAYAMOT\Desktop\aaa.jpg"
ret = pdf2jpg(source_file, target_file, 1895, 1080)
but i get an error:
ImportError: MagickWand shared library not found.
You probably had not installed ImageMagick library.
Try to install:
http://docs.wand-py.org/en/latest/guide/install.html#install-imagemagick-on-windows
>>>
but i do have module MagickWand in the hard disk as shown in the cmd :
UPDATE:
when i try to pip install in the cmd "wand" module i get:
so,i do have this module. When i try to pip install imagemagick \ ImageMagick i get:
You're importing from wand module.
You probably haven't installed bindings for Python.
pip install Wand
See the details here: http://docs.wand-py.org/en/0.4.2/
Also try to do the following:
pip search pythonmagick
or something like that. Try to install all required packages.
This may help you.

How do you shift all pages of a PDF document right by one inch?

I want to shift all the pages of an existing pdf document right one inch so they can be three hole punched without hitting the content. The pdf documents will be already generated so changing the way they are generated is not possible.
It appears iText can do this from a previous question.
What is an equivalent library (or way do this) for C++ or Python?
If it is platform dependent I need one that would work on Linux.
Update: Figured I would post a little script I wrote to do this in case anyone else finds this page and needs it.
Working code thanks to Scott Anderson's suggestion:
rightshift.py
#!/usr/bin/python2
import sys
import os
from pyPdf import PdfFileReader, PdfFileWriter
#not sure what default user space units are.
# just guessed until current document i was looking at worked
uToShift = 50;
if (len(sys.argv) < 3):
print "Usage rightshift [in_file] [out_file]"
sys.exit()
if not os.path.exists(sys.argv[1]):
print "%s does not exist." % sys.argv[1]
sys.exit()
pdfInput = PdfFileReader(file( sys.argv[1], "rb"))
pdfOutput = PdfFileWriter()
pages=pdfInput.getNumPages()
for i in range(0,pages):
p = pdfInput.getPage(i)
for box in (p.mediaBox, p.cropBox, p.bleedBox, p.trimBox, p.artBox):
box.lowerLeft = (box.getLowerLeft_x() - uToShift, box.getLowerLeft_y())
box.upperRight = (box.getUpperRight_x() - uToShift, box.getUpperRight_y())
pdfOutput.addPage( p )
outputStream = file(sys.argv[2], "wb")
pdfOutput.write(outputStream)
outputStream.close()
You can try the pypdf library. In 2022 PyPDF2 was merged back into pypdf.
two ways to perform this task in Linux
using ghostscript trough gsview
look in your /root or /home for the hidden file .gsview.ini
go to section:
[pdfwrite Options]
Options=
Xoffset=0
Yoffset=0
change the values for X axis, settling a convenient value (values are in postscript points, 1 inch = 72 postscript points)
so:
[pdfwrite Options]
Options=
Xoffset=72
Yoffset=0
close .gsview.ini
open your pdf file with gsview
file / convert / pdfwrite
select first odd pages and print to a new file (you can name this as odd.pdf)
now repeat same steps for even pages
open your pdf file with gsview
[pdfwrite Options]
Options=
Xoffset=-72
Yoffset=0
file / convert / pdfwrite
select first even pages and print to a new file (you can name this as even.pdf)
now you need to mix these two pdf with odd and even pages
you can use:
Pdf Transformer
http://sourceforge.net/projects/pdf-transformer/
java -jar ./pdf-transformer-0.4.0.jar <INPUT_FILE_NAME1> <INPUT_FILE_NAME2> <OUTPUT_FILE_NAME> merge -j
2: : use podofobox + pdftk
first step: with pdftk separate whole pdf document in two pdf files with only odd and even pages
pdftk file.pdf cat 1-endodd output odd.pdf && pdftk file.pdf cat 1-endeven output even.pdf
now with podofobox, included into podofo utils
http://podofo.sourceforge.net/about.html
podofobox file.pdf odd.pdf crop -3600 0 widht height for odd pages and
podofobox file.pdf even.pdf crop 3600 0 widht height for even pages
width and height are in postscript point x 100 and can be found with pdfinfo
e.g. if your pdf file has pagesize 482x680, then you enter
./podofobox file.pdf odd.pdf crop -3600 0 48200 68000
./podofobox file.pdf even.pdf crop 3600 0 48200 68000
then you can mix together odd and even in a unique file with already cited
Pdf Transformer
http://sourceforge.net/projects/pdf-transformer/
With pdfjam, the command to translate all pages 1 inch to the right is
pdfjam --offset '1in 0in' doc.pdf
The transformed document is saved to doc-pdfjam.pdf. For further options, type pdfjam --help. Currently pdfjam requires a Unix-like command prompt (Linux, Mac, or Cygwin). In Ubuntu, it can be installed with
sudo apt install pdfjam
Not a full answer, but you can use LaTeX with pdfpages:
http://www.ctan.org/tex-archive/macros/latex/contrib/pdfpages/
Multiple commandline linux tools also use this approach, for instance pdfjam uses this:
http://www2.warwick.ac.uk/fac/sci/statistics/staff/academic-research/firth/software/pdfjam
Maybe pdfjam can already provide what you need already.
Here is a modified version for python3.x.
First install pypdf2 via pip install pypdf2
import sys
import os
from PyPDF2 import PdfFileReader, PdfFileWriter
uToShift = 40; # amount to shift contents by. +ve shifts right
if (len(sys.argv) < 3):
print ("Usage rightshift [in_file] [out_file]")
sys.exit()
if not os.path.exists(sys.argv[1]):
print ("%s does not exist." % sys.argv[1])
sys.exit()
path=os.path.dirname(os.path.realpath(__file__))
with open(("%s\\%s" % (path, sys.argv[1])), "rb") as pdfin:
with open(("%s\\%s" % (path, sys.argv[2])), "wb") as pdfout:
pdfInput = PdfFileReader(pdfin)
pdfOutput = PdfFileWriter()
pages=pdfInput.getNumPages()
for i in range(0,pages):
p = pdfInput.getPage(i)
for box in (p.mediaBox, p.cropBox, p.bleedBox, p.trimBox, p.artBox):
box.lowerLeft = (box.getLowerLeft_x() - uToShift, box.getLowerLeft_y())
box.upperRight = (box.getUpperRight_x() - uToShift, box.getUpperRight_y())
pdfOutput.addPage( p )
pdfOutput.write(pdfout)