Python 3 Creating visual representations - python

I'm going to be creating visual representations of numeric sums, which can have contents such as:
constants, functions, operators and arguments.
I would like to be able to represent each of those things seperatly with adjustable properties such as line width, size, font size, colour etc.
My program loops round a math problem, and solves it - however I need to draw how to solve the math problem step by step, using boxes and lines (maybe animation? however static boxes and lines are okay)
I've already tried using tkinter however it doesn't seem to have the functionality I require.
I have no knowledge with graphical representation in any computing language so could anyone suggest something I could do this with? (I have to use a python back-end as I already have the code to calculate the math problem in python).
The output would preferbly be a window upon running the .exe
here is an example of the type of visulisation that I need to draw.
(each picture is a different example with modified atributes such as line width etc)
the numbers are passed in via variables and so are the operators - however the lines should be automatically placed.

If it doesn't need to be interactive, you could always write a SVG file, which can then be opened in any number of programs (including most web browsers). You wouldn't need any extra modules or libraries to accomplish this, just open a file and start writing text to it. You could even achieve animation later I believe. A quick google turned up svgwrite which is a python module intended to make writing to SVG files easier, but SVG as is, is a pretty simple XML format so you don't technically even need another module for it (this just ought to make it a bit easier).

Related

python plotting and image viewing library with equivalent of MATLABs datatips

Currently, I use MATLAB extensively for analyzing experimental scientific data (mostly time traces and images). However, again and again I keep running into fundamental problems with the MATLAB language and I would like to make the switch to python. One feature of matlab is holding me back however: its ability to add datatips to plots and images.
For a line plot the datatip is a window next to one of the data points that shows its coordinates. This is very useful to quickly see where datapoints are and what their value is. Of course this can also be done by inspecting the vectors that were used to plot the line, but that is slightly more cumbersome and becomes a headache when trying to analyze loads of data. E.g. let's say we quickly want to know for what value of x, y=0.6. Moving the datatip around will give a rough estimate very quickly.
For images, the datatip shows the x and y coordinates, but also the greyscale value (called index by MATLAB) and the RGB color. I'm mainly interested in the greyscale value here. Suppose we want to know the coordinates of the bottom tip of the pupil of the cat's eye. A datatip allows to simply click that point and copy the coordinates (either manually or programmatically). Alternatively, one would have to write some image processing script to find this pixel location. For a one time analysis that is not worthwhile.
The plotting library for python that I'm most familiar with and that is commonly called the most flexible is matplotlib. An old stock overflow question seems to indicate that this can be done using mpldatacursor and another module seems to be mplcursors. These libraries do not seem to be compatible with Spyder, however, limiting their usability. Also, I imagine many python programmers would be using a feature like datatips, so it seems odd to have to rely on a 3rd party module.
Now on to the actual question: Is there any module (or simple piece of code that I could put in my personal library) to get the equivalent of MATLAB's datatips in all figures generated by a python script?

Programmatically altering stl CAD files with Python

I have many stl CAD files for 3D printing and I was wondering how I can manipulate an individual CAD file by making a simple change programatically. Like if I want to double the dimensions of everything in the CAD file, how could I accomplish this in python? I could convert it to gcode if that makes things simpler.
I have come across FreeCad but I am not sure if this is the easiest and best way of programmatically altering CAD files. I also wanted an option that allows for freedom of manipulation beyond just size, maybe also seeing how I can programmatically alter the shape of the CAD file.
Well to be precise, STL files are even not meshes, but triangles soups. Which means that triangles are even not connected to each other (well they need to be adjacent to be used by software generatif g-code, but no obligation else)
just for clarification: g-code format is just a sequence of instructions for the machines (3d-printers, etc) so it's very good for printers, but also certainly the worst format to manipulate geometry.
one solution
you can use the python pymadcad module to deal with STL files
So for simple transformation operations (such as scale, translation etc)
from madcad import *
part = read('path/to/your_file.stl')
transformed = part.transform(mat3(2)) # scale by a factor 2 (diagonal matrix of 2)
write(transformed, 'path/to/output_file.stl')
If you need more complex operations (such as booleans, chamfers, etc) you will need to make the triangle connected again before the desired operations.
from madcad import *
part = read('path/to/your_file.stl')
part.mergeclose() # merge points at the same location
# your desired operations (example)
transformed = union(part, icosphere(vec3(1,1,1), 3.)) # add a sphere a diameter 3
write(transformed, 'path/to/output_file.stl')
note
pymadcad is internally using numpy-stl to import stl files, if you need only basic manipulations you can also only install that one
STL files are meshes. Their exterior is defined by triangulated surfaces. Meshes are notoriously difficult to modify after the fact. That's why you always want to save your designs in the native format and also in an open solid format like .STP or .IGES.
That said, simple scaling of a mesh is pretty easy and can be done trivially in FreeCAD.
You can do it in the gui in the mesh design workbench or through python. Here's a post about that:
https://forum.freecadweb.org/viewtopic.php?t=9109#p74047
FreeCAD also has some tools to convert a mesh into a solid. Results are usually less than spectacular but might be good enough depending on your needs. Search on the FreeCAD forum for posts about converting or look here: https://wiki.freecadweb.org/FreeCAD_and_Mesh_Import
Gcode doesn't say anything about the model itself. It specifies where a tool should move so it's just a series of directives that move a tool from place to place at a given speed. Going from Gcode to a model that you can edit is pretty difficult or impossible.

How does Photoshop convert type format to a rasterized layer?

I have been thinking of fonts quite recently. I find the whole process of a keystroke converted to a character displayed in a particular font quite fascinating. What fascinates me more is that each character is not an image but just the right bunch of pixels switched on (or off).
In Photoshop when I make a text layer, I am assuming it's like any other text layer in a word processor. There's a glyph attached to a character and that is displayed. So technically it's still not an 'image' so as to speak and it can be treated as a text in a word processor. However, when you rasterize the text layer, an image of the text is created with the font that was used. Can somebody tell me how Photoshop does this? I am assuming there should be a lookup table with the characters' graphics which Photoshop accesses to rasterize the layer.
I want to kind of create a program where I generate an image of the character that I am pressing (in C or Python or something like that). Is there a way to do this?
Adobe currently has publicly accessible documentation for the Photoshop file format. I've needed to extract information from PSD files (about a year ago, but actually the ancient CS2 version of Photoshop) so I can warn you that this isn't light reading, and there are some parts (at least in the CS2 documentation) that are incomplete or inaccurate. Usually, even when you have file format documentation, you need to do some reverse engineering to work with that file format.
Even so, see here for info about the TySh chunk from Photoshop 6.0 (not sure at a quick glance if it's still the current form for text - "type" to Photoshop).
Anyway, yes - text is stored as a sequence of character codes in memory and in the file. Fonts are basically collections of vector artwork, so that text can be converted to vector paths. That can be done either by dealing with the font files yourself, using on operating system call (there's definitely one for Windows, but I don't remember the name, it's bugging me now so I might figure it out later), or using a library.
Once you have the vector form, that's basically Bezier paths just like any other vector artwork, and can be rendered the same way.
Or to go directly from text to pixels, you just ask e.g. Windows to draw the text for you - perhaps to a memory DC (device context) if you don't want to draw to the screen.
FreeType is an open source library for working with fonts. It can definitely render to a bitmap. I haven't checked but it can probably convert text to vector paths too - after all it needs to do that as part of rendering to pixels anyway.
Cairo is another obvious library to look at for font handling and much more, but I've never used it directly myself.
wxWidgets is yet another obvious library to look at, and uses a memory-DC scheme similar to that for Windows, though I don't remember exact class/method names. Converting text to vectors might be outside wxWidgets scope, though.

Dynamic font sizing/layout in Python/PIL

I have a problem where I need to programmatically lay out text and output a raster image. My initial approach is based around Python and PIL (or Pillow), however I am reasonably language agnostic (as long as it runs on Linux).
I have a list of several thousand long strings, roughly a paragraph each. The naive approach is to use Python's textwrap and PIL's font.getsize() and iterate to find the optimal size, but this seems inefficient to me - there are a lot of strings, and this is potentially running on a Rasperry Pi.
I feel that this is probably a solved problem, but I haven't been able to find a decent solution - I'm not tied to Python/PIL if another stack has a better solution (something in LaTeX? Even matplotlib or something?).
Flexibility to achieve more complex layouts would be a bonus, as well - for example, down the track I would like to treat one part of text as a special case, by increasing the font size and flowing the other text around it.
Any pointers or ideas greatly appreciated.
I would use cairo (2d graphics) and pango ("pretty" text formatting/layout) libraries (they both have binding for python):
http://cairographics.org/tutorial/
http://zetcode.com/gui/pygtk/pangoII/
http://cairographics.org/pycairo_pango/

Recommendations for a simple 2D graphics python library that can output to screen and pdf?

I'm looking for an easy-to-use graphics lib for python that can output to screen as well as pdf. So, I would use code to draw some stuff (simple prims like ovals, rectangles, lines and points) to screen and then when things look good, have it output to pdf.
If you use Tkinter, you can draw on a Canvas widget, then use its .postscript method to save the contents as a PostScript file, which you can convert to PDF using ps2pdf.
postscript(self, cnf={}, **kw)
Print the contents of the canvas to a postscript
file. Valid options: colormap, colormode, file, fontmap,
height, pageanchor, pageheight, pagewidth, pagex, pagey,
rotate, witdh, x, y.
Matplotlib should be able to do it. See event handling here: http://matplotlib.sourceforge.net/examples/event_handling/index.html
You can use the Python Imaging Library for drawing images which can easily be displayed in various UIs, e.g. by displaying a jpg. Then, use ReportLab. Here's an example which shows how to use ReportLab with an image.
I'm not sure what you mean by drawing to "screen", i.e. if you're working with a specific UI toolkit. But if it's acceptable to draw and display PDFs without using an intermediate image (jpg, etc), then you might consider the PyX library, which makes it quite simple to do graphics with PDFs.
You could look into matplotlib, which is mainly for plotting but you could probably do some basic drawing.
Then there is pygame. But I'm not so sure if it can generate a pdf, however you can do 2D graphics with it.
There is something called ReportLab that can generate pdf's. Here is a bunch of tutorials using it.
This is a tricky question, because there are so many libraries available - there is a trade-off between beauty/easiness.
What I've done and works great is to produce the Postscript directly, it is not difficult at all, and you can preview it using Ghostview; converting tyo PDF is trivial (ps2pdf). Learning how to tell Postscript to create lines and circles is extremely simple.
If you want more extensibility, then go to Matplotlib, but beware of the many times when it will "decide for you what looks best" even if you don't like it.
Good luck.
Creating PDFs is always a pain, it doesn't make sense if you do not aim to lose sanity.
With that said, you are aiming to do two completely different things: when you draw to screen you draw into a raster bitmap, while PDFs are mostly dynamic, like HTML. (unlike HTML they are more prone to be the same over different platforms, but that's beside the point)
If you really want to do that, the solution might be finding something that outputs PDFs, and then showing the generated PDF on screen at every step.
I guess that's the only way to have WYSIWYG results.

Categories