module "time" has no attribute 'clock' - python

i am stuck in this error, i know the function "clock" has removed, but the problem is, i cant find the function code in the code
code:
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from skimage.transform import resize
from IPython.display import HTML
import warnings
warnings.filterwarnings("ignore")
source_image =imageio.imread(r"C:\Users\jpdyb\Documents\first-order\workspace\02.png")
reader =imageio.get_reader(r"C:\Users\jpdyb\Documents\first-order\workspace\04.mp4")
#Resize image and video to 256x256
source_image = resize(source_image, (256, 256))[..., :3]
fps = reader.get_meta_data()['fps']
driving_video = [r"C:\Users\jpdyb\Documents\first-order\workspace\04.mp4"]
try:
for im in reader:
driving_video.append(im)
except RuntimeError:
pass
reader.close()
driving_video = [resize(frame, (256, 256))[..., :3] for frame in driving_video]
def display(source, driving, generated=None):
fig = plt.figure(figsize=(8 + 4 * (generated is not None), 6))
ims = []
for i in range(len(driving)):
cols = [source]
cols.append(driving[i])
if generated is not None:
cols.append(generated[i])
im = plt.imshow(np.concatenate(cols, axis=1), animated=True)
plt.axis('off')
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, repeat_delay=1000)
plt.close()
return ani
HTML(display(source_image, driving_video).to_html5_video())
error (python):
Traceback (most recent call last):
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\utils\timing.py", line 27, in <module>
import resource
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
ModuleNotFoundError: No module named 'resource'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\jpdyb\Documents\first-order\python system\load images.py", line 6, in <module>
from IPython.display import HTML
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\__init__.py", line 49, in <module>
from .terminal.embed import embed
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\terminal\embed.py", line 19, in <module>
from IPython.terminal.ipapp import load_default_config
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\terminal\ipapp.py", line 30, in <module>
from IPython.core.magics import ScriptMagics
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\core\magics\__init__.py", line 21, in <module>
from .execution import ExecutionMagics
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\core\magics\execution.py", line 46, in <module>
from IPython.utils.timing import clock, clock2
File "C:\Users\jpdyb\AppData\Roaming\Python\Python39\site-packages\shiboken2\files.dir\shibokensupport\__feature__.py", line 142, in _import
return original_import(name, *args, **kwargs)
File "C:\Users\jpdyb\AppData\Local\Programs\Python\Python39\lib\site-packages\IPython\utils\timing.py", line 64, in <module>
clocku = clocks = clock = time.clock
AttributeError: module 'time' has no attribute 'clock'

Related

How to name a figure following its histogram name in matplotlib pyplot using savefig

I use the script
import matplotlib.pyplot as plt
import numpy as np
import yoda
def readScatter2D(histname, filename):
histos = yoda.core.read(filename+".yoda")
x = []
y = []
h = histos[histname]
for b in h:
x.append(b.x())
y.append(b.y())
plt.plot([x],[y], 'bo')
plt.savefig(str(histname)+".pdf")
readScatter2D("totalCh", "properties_file")
Compiling this with python3 gives me the error:
Traceback (most recent call last):
File "enhancement.py", line 18, in <module>
readScatter2D("totalCh", "properties_file")
File "enhancement.py", line 16, in readScatter2D
plt.savefig(str(histname)+".pdf")
File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 697, in savefig
res = fig.savefig(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 1573, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 2252, in print_figure
**kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_pdf.py", line 2519, in print_pdf
file = PdfFile(filename)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_pdf.py", line 422, in __init__
fh = open(filename, 'wb')
IOError: [Errno 2] No such file or directory: 'totalCh.pdf'
I do not understand why matplotlib cannot name the file while saving, by following the histogram names. What is the solution to save the figure following the original histogram? I am using matplotlib version 2.0.2

Reading csv file into Pycharm incurred error

I just want to read a csv file into Pycharm but due to some reason it's not doing it properly.
Here is my code:
import csv
import os
import pandas as pd
path = '/Users/amy/Desktop/data_analysis/additionaldata/df1.csv'
df=pd.read_csv('path', sep=',')
It returned error
Traceback (most recent call last):
File "<input>", line 3, in <module>
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/harper/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/__init__.py", line 55, in <module>
from pandas.core.api import (
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/harper/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/core/api.py", line 24, in <module>
from pandas.core.groupby import Grouper, NamedAgg
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/harper/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/core/groupby/__init__.py", line 1, in <module>
from pandas.core.groupby.generic import ( # noqa: F401
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/core/groupby/generic.py", line 44, in <module>
from pandas.core.frame import DataFrame
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/core/frame.py", line 114, in <module>
from pandas.core.series import Series
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/core/series.py", line 84, in <module>
import pandas.plotting
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/plotting/__init__.py", line 59, in <module>
from pandas.plotting._core import (
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/plotting/_core.py", line 17, in <module>
import pandas.plotting._matplotlib # noqa
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/plotting/_matplotlib/__init__.py", line 3, in <module>
from pandas.plotting._matplotlib.boxplot import (
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/pandas/plotting/_matplotlib/boxplot.py", line 4, in <module>
from matplotlib.artist import setp
File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/Users/amy/PycharmProjects/testing/venv/lib/python3.7/site-packages/matplotlib/__init__.py", line 5, in <module>
df=pd.read_csv('path', sep=',')
AttributeError: module 'pandas' has no attribute 'read_csv'
I also tried this
import csv
import os
import pandas as pd
path = '/Users/amy/Desktop'
df=pd.read_csv("df1.csv")
which didn't work either.
What's wrong? I have read a few other posts but still not sure how to do this. Any help is appreciated. Thanks
Simply add open() to open the file before passing it into pandas.read_csv():
import pandas as pd
path = '/Users/amy/Desktop/data_analysis/additionaldata/df1.csv'
df = pd.read_csv(open(path), sep=',')
(Note: 'path' is only a string with value 'path' if you want the actual path, there shouldn't be any brackets.)

Issue with tkinter, python and seaborn: _tkinter.TclError: no display name and no $DISPLAY environment variable

The story
pandas, numpy, seaborn, matplotlib are installed on the system without errors. I took this code example from http://seaborn.pydata.org/examples/many_pairwise_correlations.html
Snippet
from string import letters
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white")
# Generate a large random dataset
rs = np.random.RandomState(33)
d = pd.DataFrame(data=rs.normal(size=(100, 26)),
columns=list(letters[:26]))
# Compute the correlation matrix
corr = d.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
square=True, xticklabels=5, yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
It results in the following error:
Traceback (most recent call last):
File "seaborn-example.py", line 4, in <module>
import seaborn as sns
File "/usr/local/lib/python2.7/site-packages/seaborn/__init__.py", line 6, in <module>
from .rcmod import *
File "/usr/local/lib/python2.7/site-packages/seaborn/rcmod.py", line 8, in <module>
from . import palettes, _orig_rc_params
File "/usr/local/lib/python2.7/site-packages/seaborn/palettes.py", line 12, in <module>
from .utils import desaturate, set_hls_values, get_color_cycle
File "/usr/local/lib/python2.7/site-packages/seaborn/utils.py", line 12, in <module>
import matplotlib.pyplot as plt
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
globals(),locals(),[backend_name],0)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 6, in <module>
from six.moves import tkinter as Tk
File "/usr/local/lib/python2.7/site-packages/six.py", line 203, in load_module
mod = mod._resolve()
File "/usr/local/lib/python2.7/site-packages/six.py", line 115, in _resolve
return _import_module(self.mod)
File "/usr/local/lib/python2.7/site-packages/six.py", line 82, in _import_module
__import__(name)
File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 39, in <module>
import _tkinter # If this fails your Python may not be configured for Tk
ImportError: No module named _tkinter
Referred Install tkinter for Python for installing tkinter
yum install -y tkinter tk-devel
Then I followed this for rebuilding Python
https://github.com/h2oai/h2o-2/wiki/installing-python-2.7-on-centos-6.3.-follow-this-sequence-exactly-for-centos-machine-only
And got this when I tried the rebuilding - still some issue with tkinter:
Traceback (most recent call last):
File "seaborn-example.py", line 22, in <module>
f, ax = plt.subplots(figsize=(11, 9))
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 1203, in subplots
fig = figure(**fig_kw)
File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 535, in figure
**kwargs)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 81, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 89, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1745, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
What is wrong here?
At the beginning of the file
import matplotlib
matplotlib.use('Agg')

scipy.interpolate leads to ImportError

my setup is
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
I have scipy 0.17 and cartopy '0.14.2'.
All I'm trying to do is
plt.axes(projection=ccrs.PlateCarree())
and it leads to this:
Traceback (most recent call last):
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-93-636aeb1a7fc6>", line 1, in <module>
plt.axes(projection=ccrs.PlateCarree())
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 867, in axes
return subplot(111, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 1022, in subplot
a = fig.add_subplot(*args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/matplotlib/figure.py", line 987, in add_subplot
self, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/matplotlib/projections/__init__.py", line 100, in process_projection_requirements
projection_class, extra_kwargs = projection._as_mpl_axes()
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/cartopy/crs.py", line 150, in _as_mpl_axes
import cartopy.mpl.geoaxes as geoaxes
File "/opt/pycharm-2016.2/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/cartopy/mpl/geoaxes.py", line 52, in <module>
from cartopy.vector_transform import vector_scalar_to_grid
File "/opt/pycharm-2016.2/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/cartopy/vector_transform.py", line 26, in <module>
from scipy.interpolate import griddata
File "/opt/pycharm-2016.2/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/scipy/interpolate/__init__.py", line 158, in <module>
from .interpolate import *
File "/opt/pycharm-2016.2/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/scipy/interpolate/interpolate.py", line 12, in <module>
import scipy.special as spec
File "/opt/pycharm-2016.2/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/scipy/special/__init__.py", line 629, in <module>
from .basic import *
File "/opt/pycharm-2016.2/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
module = self._system_import(name, *args, **kwargs)
File "/usr/local/anaconda2/envs/myenv3/lib/python3.5/site-packages/scipy/special/basic.py", line 14, in <module>
from ._ufuncs import (ellipkm1, mathieu_a, mathieu_b, iv, jv, gamma, psi, zeta,
ImportError: cannot import name 'zeta'
Deep down this appears to be a scipy problem, but I have the newest there - what's going on here?
It turned out to be a problem with the scipy installation coming from conda. Creating a new environment and freshly installing scipy solved the issue.

Pyalgotrade - AttributeError: 'SequenceDatasSeries' object has no attribute 'getHighDataSeries'

I'm using pyalgotrade to write a trading algo. I got the error above and can't seem to fix it. I'm trying to use the "SLOW STOCHASTIC", any help on solving this error and getting the slow stochastic to work is greatly appreciated:
Error:
C:\Users\...\Desktop>python bobo.py
Traceback (most recent call last):
File "bobo.py", line 114, in <module>
main()
File "bobo.py", line 110, in main
run_strategy(10,inst,2,14,5,2,3)
File "bobo.py", line 102, in run_strategy
myStrategy = MyStrategy(feed, inst, smaPeriod,emaPeriod,rsiPeriod,fastk_period,slowk_period,slowd_period)
File "bobo.py", line 26, in __init__
self.__stoch = indicator.STOCH(self.__prices,fastk_period,slowk_period,slowd_period)
File "C:\Users\...\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 803, in STOCH
ret = call_talib_with_hlc(barDs, count, talib.STOCH, fastk_period, slowk_period, slowk_matype, slowd_period, slowd_matype)
File "C:\Users\...\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 93, in call_talib_with_hlc
high = bar_ds_high_to_numpy(barDs, count)
File "C:\Users\...\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 45, in bar_ds_high_to_numpy
return value_ds_to_numpy(barDs.getHighDataSeries(), count)
AttributeError: 'SequenceDataSeries' object has no attribute 'getHighDataSeries'
Code:
from pyalgotrade.tools import yahoofinance
from pyalgotrade import strategy
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.technical import stoch
from pyalgotrade import dataseries
from pyalgotrade.technical import ma
from pyalgotrade import technical
from pyalgotrade.technical import highlow
from pyalgotrade import bar
from pyalgotrade.talibext import indicator
from pyalgotrade.technical import rsi
import numpy
import talib
class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed,instrument,smaPeriod,emaPeriod,rsiPeriod,fastk_period,slowk_period,slowd_period):
strategy.BacktestingStrategy.__init__(self, feed, 1000) #change portfolio amount
self.__position = None
self.__instrument = instrument
self.setUseAdjustedValues(True)
self.__prices = feed[instrument].getPriceDataSeries()
self.__sma = ma.SMA(self.__prices, smaPeriod)
self.__ema = ma.EMA(self.__prices, emaPeriod)
self.__rsi = rsi.RSI(self.__prices, rsiPeriod)
self.__stoch = indicator.STOCH(self.__prices,fastk_period,slowk_period,slowd_period)
Now I'm getting the error:
Traceback (most recent call last):
File "bobo.py", line 103, in <module>
main()
File "bobo.py", line 99, in main
run_strategy(inst,10,250,14,5,5,5)
File "bobo.py", line 90, in run_strategy
myStrategy = MyStrategy(feed, inst, smaPeriod,emaPeriod,rsiPeriod,fastk_period,slowk_period,slowd_period)
File "bobo.py", line 28, in __init__
self.__stoch = indicator.STOCH(feed[instrument],fastk_period,slowk_period,slowd_period)
File "C:\Users\JDOG\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 803, in STOCH
ret = call_talib_with_hlc(barDs, count, talib.STOCH, fastk_period, slowk_period, slowk_matype, slowd_period, slowd_matype)
File "C:\Users\JDOG\Anaconda2\lib\site-packages\pyalgotrade\talibext\indicator.py", line 105, in call_talib_with_hlc
return talibFunc(high, low, close, *args, **kwargs)
File "talib/func.pyx", line 9388, in talib.func.STOCH (talib\func.c:87125)
Exception: inputs are all NaN
Try this:
self.__stoch = indicator.STOCH(feed[instrument],fastk_period,slowk_period,slowd_period)
The stochastic oscillator is expecting a bar dataseries, not a regular one.

Categories

Resources