How to read the note value in the score? - python

I am doing something like reading the MIDI info. Currently, I just read the onset and offset from PrettyMIDI. However, I found that the onset and offset is not really accurate(i hope it shows somthing like 1, 2.5, 3,4,6). It goes with something like 1,43, 2.34. Like this
So I am wondering how to read the exact note value.
For example, my expected result is [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,] in this image.
This is my current code.
import os
import sys
from matplotlib import pyplot as plt
from matplotlib import patches
from matplotlib import colors
import pretty_midi
import pandas as pd
import IPython.display as ipd
sys.path.append('..')
# import libfmp.c1
fn = os.path.join('..', 'data', 'C1', "Canon_in_D__Violin_Solo_.mid")
midi_data = pretty_midi.PrettyMIDI(fn)
midi_list = []
for instrument in midi_data.instruments:
for note in instrument.notes:
start = note.start
end = note.end
pitch = note.pitch
velocity = note.velocity
midi_list.append([start, end, pitch, velocity])
midi_list = sorted(midi_list, key=lambda x: (x[0], x[2]))
df = pd.DataFrame(midi_list, columns=['Start', 'End', 'Pitch', 'Velocity'])
html = df.to_html(index=True)
ipd.HTML(html)
Thanks

Related

Python time series: omitted values after using statsmodels.tsa.seasonal.seasonal_decompose?

Could anyone tell me what I did wrong that my first and last six observations are omitted in the final outcome?
I used the statsmode.tsa.seasonal_decompose to do seasonal adjustment.
Thanks.
import os
import statsmodels.api as sm
import pandas as pd
import numpy as np
#pd.options.display.mpl_style = 'default'
%matplotlib inline
#Load csv data#
cpi = pd.read_csv('/home/pythonwd/thai cpi.csv')
cpi = cpi.dropna()
#Create date and time series#
cpi['date'] = pd.to_datetime(cpi['date'], dayfirst=True)
cpi = cpi.set_index('date')
#Seasonal adjustment#
dec = sm.tsa.seasonal_decompose(cpi["cpi"],model='multiplicative')
dec.plot()
Data before the #Seasonal adjustment# line:
enter image description here
Data afterwards:
enter image description here

Calculate Max DrawDown

I am using pyfolio to calcuate the maxdrawdown and other risk indicator. What should be adjusted to get the correct value?
Near 27% should be the right maxdrawdown, I don't why some negative value is returned. And it seems the whole drawdown table is not corrected or as expected.
Thanks in advance
benchmark files
results files
import pandas as pd
import pyfolio as pf
import os
import matplotlib.pyplot as plt
from pandas import read_csv
from pyfolio.utils import (to_utc, to_series)
from pyfolio.tears import (create_full_tear_sheet,
create_simple_tear_sheet,
create_returns_tear_sheet,
create_position_tear_sheet,
create_txn_tear_sheet,
create_round_trip_tear_sheet,
create_interesting_times_tear_sheet,)
test_returns = read_csv("C://temp//test_return.csv", index_col=0, parse_dates=True,header=None, squeeze=True)
print(test_returns)
benchmark_returns = read_csv("C://temp//benchmark.csv", index_col=0, parse_dates=True,header=None, squeeze=True)
print(benchmark_returns)
fig = pf.create_returns_tear_sheet(test_returns,benchmark_rets=benchmark_returns,return_fig=True)
fig.savefig("risk.png")
maxdrawdown = pf.timeseries.max_drawdown(test_returns)
print(maxdrawdown)
table = pf.timeseries.gen_drawdown_table(test_returns)
print(table)

Convert Python String to Latex Formula

I did try to use Sympy for converting Strings containing math equations to Latex code and Display these Equations as an image.
for Example i did try to use Sympy on:
K(Y) = M * X + B
This does not work in Sympy. (at least for me)
This will work in Sympy. ( at least for me)
M*X + B
Maybe someone's got a hint how to change the following to sucessfully embed my Equations inside a GUI:
import random
import os
import pikepdf
import fitz # PyMuPDF, imported as fitz for backward compatibility reasons
from kivymd.uix.label import MDLabel
import sympy as syp
from sympy import *
from sympy.abc import _clash1
from functools import partial
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
import io
from kivy.uix.image import Image
from kivy.graphics.context_instructions import Color
from kivy.graphics.vertex_instructions import Rectangle
from kivy.properties import StringProperty, Clock
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from PIL import Image, ImageChops
from io import BytesIO as StringIO
import matplotlib.pyplot as plt
b = ["Lineare Beispielfunktion"]
a = ["K ( X) = M * X + B ", 1, 5]
Gleichung = a[0]
Gleichung = latex(sympify(Gleichung))
def render_latex(formula, fontsize=12, dpi=3000, format_='svg'):
"""Renders LaTeX formula into image.
"""
fig = plt.figure(figsize=(0.01, 0.01))
fig.text(0, 0, u'${}$'.format(formula), fontsize=fontsize)
buffer_ = StringIO()
fig.savefig(buffer_, dpi=dpi, transparent=True, format=format_, bbox_inches='tight',
pad_inches=0.0)
plt.close(fig)
return buffer_.getvalue()
image_bytes = render_latex(Gleichung,fontsize=80, dpi=200, format_='jpg')
with open('Image_toDisplay', 'wb') as image_file:
image_file.write(image_bytes)
I got the function to generate der Image from Stackoverflow ( can't find source on stackoverflow right now),
But you can find it here (thanks for helping to add source):
on Github by tonyseek
My Problem is the way iam using Sympy. Obviously I do use it the wrong way.
Any recommendations are welcome.
Okay i did try Something which ist not nice but did work for me I will sketch the concept and show code afterwards:
split String on '='
a) using (import re) and: re.split('=', Gleichung)
List Element[0] is part before '=' List Element[1] is part after '='
use Sympy to render latex code for each Element
join new strings ( latex code strings) by '='
give this new string into shown function
Gleichung = a[0]
Gleichung_split = re.split('=', Gleichung)
Gleichung_back = Gleichung_split [1]
Gleichung_front = Gleichung_split [0]
Gleichung_front = latex(sympify(Gleichung_front))
Gleichung_back = latex(sympify(Gleichung_back))
Gleichung_split [0]= Gleichung_front
Gleichung_split [1] = Gleichung_back
s = "="
Gleichung_print = s.join(Gleichung_split )
image_bytes = render_latex(Gleichung_print ,fontsize=80, dpi=200,
format_='jpg')
with open('Image_toDisplay', 'wb') as image_file:
image_file.write(image_bytes)
Additional Information: Gleichung is german for Equation. If there is anything i should change or a more pythinic way to do this feel free to contribute.
And one important thing: the render to latex function i got from Stack Overflow if you know the source give me a hint i would like to link this into my question.

pandas.DataFrame returns Series not a Dataframe

I am working with a series of images. I read them first and store in the list then I convert them to dataframe and finally I would like to implement Isomap. When I read images (I have 84 of them) I get 84x2303 dataframe of objects. Now each object by itself also looks like a dataframe. I am wondering how to convert all of it to_numeric so I can use Isomap on it and then plot it.
Here is my code:
import pandas as pd
from scipy import misc
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import matplotlib.pyplot as plt
import glob
from sklearn import manifold
samples = []
path = 'Datasets/ALOI/32/*.png'
files = glob.glob(path)
for name in files:
img = misc.imread(name)
img = img[::2, ::2]
x = (img/255.0).reshape(-1,3)
samples.append(x)
df = pd.DataFrame.from_records(samples)
print df.dtypes
print df.shape
Thanks!

Python Importing data with multiple delimiters

In Python, how can I import data that looks like this:
waveform [0]
t0 26/11/2014 10:53:03.639218
delta t 2.000000E-5
time[0] Y[0]
26/11/2014 10:53:03.639218 1.700977E-2
26/11/2014 10:53:03.639238 2.835937E-4
26/11/2014 10:53:03.639258 2.835937E-4
26/11/2014 10:53:03.639278 -8.079492E-3
There are two delimiters, : and white space. I want to get rid of the date 24/11/2014 and delete the semicolons so that the time array looks like 105303.639218, etc. So is there a way to specify two delimiters in the code, or is there a better way to analyse the data?
So far I have got:
import numpy as np
import matplotlib.pyplot as plt
_, time, y = np.loadtxt('data.txt', delimiter=':', skiprows=5)
plt.plot(time,y)
plt.show()
You can do this:
time = '10:34:20.454068'
list_ = time.split(':')
''.join(list_)
# '103420.454068'
for each row.
Maybe it's sort of a roundabout way of doing this, but...
import numpy as np
import matplotlib.pyplot as plt
mydata = np.loadtxt('data.txt', dtype='string', skiprows=5)
time = mydata[:,1]
time = np.array([s.replace(':','') for s in time])
y = np.array(mydata[:,2])
plt.plot(time,y)
plt.show()

Categories