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.
Related
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
I have the following code:
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
m = Chem.MolFromSmiles('c1cc(C(=O)O)c(OC(=O)C)cc1')
substructure = Chem.MolFromSmarts('C(=O)O')
print(m.GetSubstructMatches(substructure))
m
Which produces the following plot.
However the code above doesn't produce the high resolution image.
I'd like to have the SVG.
I tried this:
drawer = rdMolDraw2D.MolDraw2DSVG(400,200)
drawer.DrawMolecule(m,highlightAtoms=m.GetSubstructMatch(Chem.MolFromSmarts('C(=O)O')))
drawer.FinishDrawing()
svg = drawer.GetDrawingText().replace('svg:','')
SVG(svg)
But I get:
What's the right way to do it?
The code can be tested in my Google Colab.
GetSubstructMatch returns only the first match. Use GetSubstructMatches. There are multiple scenarios here depending on the rdkit version you've installed. In the latest rdkit version (2021.09.2), the following code should work.
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
from copy import deepcopy
def increase_resolution(mol, substructure, size=(400, 200)):
mol = deepcopy(mol)
substructure = deepcopy(substructure)
drawer = rdMolDraw2D.MolDraw2DSVG(size[0], size[1])
# highlightAtoms expects only one tuple, not tuple of tuples. So it needs to be merged into a single tuple
matches = sum(mol.GetSubstructMatches(substructure), ())
drawer.DrawMolecule(mol, highlightAtoms=matches)
drawer.FinishDrawing()
svg = drawer.GetDrawingText()
return svg.replace('svg:','')
mol = Chem.MolFromSmiles('c1cc(C(=O)O)c(OC(=O)C)cc1')
substructure = Chem.MolFromSmarts('C(=O)O')
SVG(increase_resolution(mol, substructure))
If you're getting Value Error: Bad Conformer id error then either update the rdkit package to the latest version or try this:
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
from copy import deepcopy
def increase_resolution(mol, substructure, size=(400, 200), kekulize=True):
mol = deepcopy(mol)
substructure = deepcopy(substructure)
rdDepictor.Compute2DCoords(mol)
if kekulize:
Chem.Kekulize(mol) # Localize the benzene ring bonds
drawer = rdMolDraw2D.MolDraw2DSVG(size[0], size[1])
# highlightAtoms expects only one tuple, not tuple of tuples. So it needs to be merged into a single tuple
matches = sum(mol.GetSubstructMatches(substructure), ())
drawer.DrawMolecule(mol, highlightAtoms=matches)
drawer.FinishDrawing()
svg = drawer.GetDrawingText()
return svg.replace('svg:','')
mol = Chem.MolFromSmiles('c1cc(C(=O)O)c(OC(=O)C)cc1')
substructure = Chem.MolFromSmarts('C(=O)O')
SVG(increase_resolution(mol, substructure, kekulize=True))
If for some cases like structures with chirality introduced in them as part of the SMILES string, it may fail to work. For such cases, set kekulize=False.
I'm trying to get a new raster making looping through all array and using a search window 25x25 pixels. I wonder if you know a better way to do this because it takes too much time with my approach.
import sys
import os
import numpy as np
import math
from osgeo import gdal, osr, gdal_array, gdalnumeric
from osgeo.gdalnumeric import *
numpy.warnings.filterwarnings('ignore')
def mean_neighbors(M,x,y,w=1):
l = []
for i in range(max(0,x-w), x+(w+1)):
for j in range(max(0,y-w), y+(w+1)):
try:
t = M[i][j]
l.append(t)
except IndexError:
pass
return np.mean(l)
raster_file = gdal.Open('image.tif', gdal.GA_ReadOnly)
rst = gdalnumeric.BandReadAsArray(raster_file.GetRasterBand(1))
cob = np.zeros(rst.shape)
for i in range(rst.shape[0]):
for j in range(rst.shape[1]):
cob[i][j] = mean_neighbors(rst, i, j, 25) # want to optimize this function
Moving window mean is a very common function that you should not need to write yourself. Here are two fast implementations you can use:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.window.Rolling.mean.html
https://github.com/kwgoodman/bottleneck (move_mean)
I'd like to 1. iterate through a directory of images and turn each image into a NumPy array. I think I have accomplished this with the following code:
import tensorflow as tf
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
from PIL import Image
import os
myimages = []
path_to_images = 'images_animation'
filenum = len([name for name in os.listdir(path_to_images) if os.path.isfile(os.path.join(path_to_images, name))])
#loops through available pngs
for p in range(1, filenum):
## Read in picture
fname = "images_animation/image%03d.png" % p
img = mpimg.imread(fname)
imgplot = plt.imshow(img)
# append AxesImage object to the list
myimages.append([imgplot])
for n, im in enumerate(myimages):
img = Image.open(fname).convert("L")
arr = np.array(img
print(arr)
If I can make this code better or more efficient, please feel free to tell me how.
Now, I'd like to 2. turn these NumPy arrays into TFRecords. What is the best way to do so? I'm near clueless as how to do this, so I have not done much to solve it myself, so I'm looking for a solution.
I want to use MayaVI for visualization of large simulation data, saved as a VTKUnstructuredGrid (or here TVTK Unstructured Grid). After loading the Grid, I want to quickly update the grid points using numpy arrays, without changing anything else in the model.
So far I update the points and then call the modified()-method, which flushes the complete pipeline and thus slows down the visualization a lot. My question is now: Is there any chance to update the points in a VTKDataset without reloading the whole pipeline?
I am doing the visualization using Traits; simplified my code looks like:
import numpy as np
from enthought.traits.api import HasTraits, Range, Instance, on_trait_change
from enthought.traits.ui.api import View, Item, HGroup, HSplit, VSplit
from enthought.tvtk.pyface.scene_editor import SceneEditor
from enthought.mayavi.tools.mlab_scene_model import MlabSceneModel
from enthought.mayavi.core.ui.mayavi_scene import MayaviScene
from enthought.mayavi import mlab
from enthought.tvtk.api import tvtk
from enthought.mayavi.modules.surface import Surface
from enthought.tvtk.pyface.scene_editor import SceneEditor
class Visu(HasTraits):
timestep = Range(50,100,50)
pts = tvtk.Points()
ugrid = tvtk.UnstructuredGrid()
scene = Instance(MlabSceneModel, ())
view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene), height=250, width=300, show_label=True),HGroup('_', 'timestep'), resizable=True )
#on_trait_change('scene.activated')
def ini(self):
filename = 'original3dplot'
reader = tvtk.LSDynaReader(file_name = filename)
reader.update()
self.ugrid = reader.get_output()
self.surface = self.scene.mlab.pipeline.surface(self.ugrid)
#on_trait_change('timestep')
def update_visu(self):
update_coord = np.loadtxt('newcoordinates'+str(self.timestep))
self.pts.from_array(update_coord)
self.ugrid.points = self.pts
self.ugrid.modified()
visualization = Visu()
visualization.configure_traits()