gnuplot-py script failure - python

I am trying to plot a simple graph using gnuplot and installed the gnuplot-py binding. I am using the script below and I am getting the below error -
gnuplot> set terminal aqua
line 0: unknown or ambiguous terminal type; type just 'set terminal' for a list
I am running on a mac.
Here is the code I am using --
import numpy as np
import Gnuplot
def gnudemo2():
#Create some data
x = np.linspace(0,10,100)
y1 = x**2
y2 = 10*np.sin(np.pi*x)
#Instantiate Gnuplot object
g = Gnuplot.Gnuplot(persist=1)
g('set terminal png size 800,600 enhanced font "Helvetica,8" ')
g('set style data lines')
g('set output \'output1.png\'')
#Create the Gnuplot data
d1 = Gnuplot.PlotItems.Data(x, y1, with_='lp', title='d1')
d2 = Gnuplot.PlotItems.Data(x,y2, with_='l', title='d2')
g.plot(d1,d2)
# when executed, just run gnudemo2():
if __name__ == '__main__':
gnudemo2()
I am setting the terminal to png but still its trying to use the aqua term.
I installed the aquaterm as well. But it still would not work. What could be going on here?
If I use the same lines inside gnuplot on the command line, everything works fine. So I know the commands are correct. But something is missing when I run them through python.

Related

Python & Inkscape: SVG-to-EMF conversion breaks down?

I am trying to automatically convert an SVG graphic to EMF with Python, using Inkscape on the command line. My code is
from subprocess import call
import matplotlib.pyplot as plt
from numpy import linspace, sin
x = linspace(0,10,10)
y = sin(x)
plt.plot(x,y)
plt.savefig("source.svg")
for k in range(0,5):
call(["C:\Program Files\Inkscape\inkscape.exe", "--file", "source.svg", "--export-emf", "result" + str(k) + ".emf" ])
# this usually breaks down at k = 1 or 2
The "call" command works fine when called once. If I call it multiple times, e.g. on consecutive lines as shown above, Inkscape breaks down and I have to restart my python kernel and kill Inkscape via the Windows Task-Manager.
Any ideas why that might be?
Thanks!

Different behaviour of matplotlib in interpretor and in script

Running following code inside python interpretor displays a figure with random values
>>>fig = plt.figure();ax1 = fig.add_subplot(111);plt.ion();ax1 = ax1.imshow(np.random.rand(256,256))
while running the following script as a file does not display any output/figure.
import numpy as np
import matplotlib.pyplot as plt
import time
fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.ion()
ax1 =ax1.imshow(np.random.rand(256,256))
what is the reason for difference in behaviour?
I suspect what is going on is that
matplotlib.rcParams['interactive'] == True
and this is set in your .matplotlibrc file.
which means that plt.show is non-blocking (so that you get a figure that you can interact with and an command prompt you can type more code at). However, in the case of a script the (implicit) plt.show does not block so the script exits, taking the figure with it.
I suggest the setting the interactive rcparam to False and then either explitily setting it to true in the repl or (the preferred method) use IPython and the %matplotlib magic.

How to start a program on Python?

I'm doing a project on projectile motion where I have to create a program that given some values, it will give several values. I haven't finished it yet, but I wish to test it, but I have very little knowledge on how to run my programs. I created a file on Notepad++ with some of my code, but every time I try to run it, it says:
Traceback (most recent call last):
File <"stdin">, line 1, in
ImportError: no module named py
The thing is, I don't see anywhere how to run my programs on Python using Notepad++ so I am confused as to what I have to do. I am using the command prompt to run my program.
I will post what I have so far of my project because maybe it's a problem of what I have written. This is what I have so far:
"""Mini-Project about projectile motion."""
USER = ""
USER_ID = ""
import numpy as np
#Define variables for ease of use:
g = 9.81 #gravitational constant
u = (float(raw_input("enter launch_speed: ")))#speed of launch
r = (float(raw_input("enter launch_angle_deg: "))*(np.pi)/180) #angle of launch in radians
n = (float(raw_input("enter num_samples: "))) #number of time divisions
#"t" variable of time
#"x" variable of horizontal distance
#"y" variable of vertical distance
def x(t):
"""function that gives the horizontal position "x" as a function
of time.
"""
return u*(np.cos(r))*t #formula for horizontal displacement
def y(t):
"""function that gives the vertical position "y" as a function of
time.
"""
return u*(np.sin(r))*t - (g/2)*t**2 #formula for vertical displacement
def y(x):
"""function that gives the vertical position "y" as a function of the
horizontal position "x".
"""
return x*(np.tan(r))-(g/2)*(x/(u*np.cos(r)))**2
a = np.arange(1, n+1, dtype=float)
def trajectory(launch_speed, launch_angle_deg , num_samples ):
"""This function gives the values of horizontal x-values, vertical
y-values, and time values, respectively, given the values for initial
launch speed, and the angle at which it is launched, for some given
divisions of time that the object is in the air.
"""
while t <= (u*(np.sin(r))/g): #maximum time given by this formula
t = x/(u*(np.cos(r)))
I am assuming you are on Windows, for the reference good ol' command prompt. Be sure you have Python installed, then navigate to the folder you have your Python script stored. Shift right-click on the folder and select "Open command window here". A CMD window should appear. Now just type
python name_of_your_python_file.py
And you should see the output. As for the ImportError you posted, be sure to have all dependencies installed. (Numpy)
If you are determined to use Notepad++ as your development environment, read here for more information on running those Python scripts direct from notepad++
Store the program in a file named "projectile.py"
Install Python 3 and NumPy.
Then open console, navigate to the folder containing the file
Invoke
python3 projectile.py

Python Spyder Display Symbolic Math

In Spyder 2 (Anaconda distribution) and in the IPython QT Console I'm able to print results of symbolic calculations (from an answer I got for a previous post) but I can't get equations in strings to print with the a IPython's Rich Display System:
from sympy import *
from IPython.display import display, Math
init_printing(use_unicode=False, wrap_line=False, no_global=True)
x, y, z = symbols('x y z')
#----- prints correctly
ii = integrate(x**2 + x + 1, x)
display(ii)
#----- does not print
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
The above prints the results of the integrate correctly but the Math() does not print (no error -- just skips it). Note it all works in SciPy web notebook.
Thank you!
The Math class doesn't generate the rendered image from your Latex, that's why it doesn't work directly.
To get what you want you need to use this code
from IPython.display import Image, display
from IPython.lib.latextools import latex_to_png
eq = r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'
data = latex_to_png(eq, wrap=True)
display(Image(data=data))
Then you will see the right image
Hello guys im still having the problem, whe i use
from IPython.display import display, Math, Latex
display((Math(r'P(Purchase|Male)= \frac{Numero\ total\ de\ compras\ hechas\ por\ hombres\}{Total\ de\ hombres\ en\ el\ grupo\} = \frac{Purchase\cap Male}{Male}')))
on jupyter it works fine, but when i do the exact same code on spyder it doesnt work
im using python 3.6 , spyder 3.3.3
also i tried the marked asnwer but latex_to_png makes a NoneType Object on spyder

Pymol not outputting image

I am trying to draw a protein structure from a pdb file using pymol.
However, when I try to run the script below, a pymol window opens but it is just pitch black. Also, bizarrely, the pdb file is outputted to the shell.
Here is my code:
bioservices_pdb_obj = PDB()
pdb_file = bioservices_pdb_obj.getFile(results[str(Brick.part_attrib(self,'uniprot_id'))][detail-1],'pdb')
pdb_name = str(Brick.part_attrib(self,'uniprot_id'))
pymol.finish_launching()
pymol.cmd.load(pdb_file, pdb_name)
pymol.cmd.disable("all")
pymol.cmd.enable(pdb_name)
pymol.cmd.png("my_pdb.png")
pymol.cmd.quit()
Does anyone know what is going on here?
The .png file 'my_pdb' is dumped into the working directory, but that's just black as well.
Does this also happen with any other PDB file? If yes, you can try a workaround using the cmd.mpng() function. You can use this function also in other contexts if the cmd.png() function doesn't work, e.g. when using PyMOL in command-line mode.
import pymol
from pymol import cmd
import os
pymol.finish_launching()
cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image.
def pnghack(filepath, width=1024, height=768):
"""Workaround if cmd.png() doesn't work"""
cmd.viewport(width, height) # Set resolution
cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only
cmd.mplay() # cmd.mpng needs the animation to 'run'
cmd.load(pdb_file, pdb_name)
cmd.disable("all")
cmd.enable(pdb_name)
pnghack("my_pdb.png")
cmd.quit()
Note that the resulting png file is named "my_pdb0001.png" as the cmd.mpng() function always adds the framenumber.

Categories