How to create floating figures in reStructuredText / Sphinx? - python-sphinx

I want to have a figure with text wrapped around it.
This is what I'm saying:
Installation of Optional Accessories
====================================
.. warning:: Never plug in or unplug a Hand Robot or a Grasp Sensor while the robot is turned on, as the system will not function properly and damage to the robot could occur.
Installing a Hand Robot
-----------------------
.. _`fig-attach-hand-robot`:
.. figure:: attach-hand-robot.*
:scale: 40%
:align: right
Attach Hand Robot
Make sure the robot is turned off as described in the section :ref:`turn-off-robot`.
Take the hand robot out of the grounded bin that sits on top of the electrical panel (if you have an adjustable height table) or sits on top of the rear table (if you have a fixed height table). Make sure not to touch the pins on the electrical wiring while doing so. Insert the conical protrusion of the hand robot into the conical receptacle (see :ref:`fig-attach-hand-robot`). Once the hand robot is supported by the InMotion Arm Robot, make sure the two knobs below the Hand Robot have engaged and sprung in. If they have not, twist them until they do as shown (see :ref:`fig-knobs-in`).
and this screenshot of PDF output is what I'm getting.
Why is the figure caption centered, rather than under the image?
Why isn't the body text ("Make sure ..." and "Take the ...") on the LEFT of the image, rather than underneath it? I want the figure to float right and have the text on its left.

I have found that figures float to the side with :figwidth: and :align: specified. (Using the readthedocs theme.)
.. figure:: images/myimage.jpg
:figwidth: 40%
:align: right
https://docutils.sourceforge.io/docs/ref/rst/directives.html#figure

So, I did some research into reStructuredText and it seems what you want is not actually possible.
The documentation for the figure and the image directives never mention the ability to wrap text around the object.
This might be a feature request to provide to the Sphinx developers although I suspect they'll reject it because it isn't explicitly mentioned in the rst specification.
I was hoping the bounty would garner this some attention but I suspect is hasn't.

Though it is too late but maybe the answer would help future people.
You can use the sidebar directive to put the image.
.. sidebar:: mandatory_title. Use can use image caption here
.. Figure:: 1.png

In order to deal with images as they were part of the text you may actually use substitutions.
Here an extract from the documentation that can be helpful:
The |biohazard| symbol must be used on containers used to
dispose of medical waste.
.. |biohazard| image:: biohazard.png
I hope this helps

If anyone else runs into this problem then this bit of code might be a help. I decided that I didn't want to hack the actual sphinx code so I made a very short python script applied to the generated _build/latex/pi3d_book.tex to convert the \includegraphics that had \hfill before or after into wrapped images. There will be lots of things that stop this working such as putting images inside lists or scaling images. The sphinx directives in my rst are like
.. image:: perspective.png
:align: right
You obviously have to change the file names and paths to suit your setup. From my spinx project I run
$ make latexpdf
$ python wrapfix.py # or whatever you call this file
program listing of wrapfix.py
import subprocess
with open("_build/latex/pi3d_book.tex", "r") as f:
tx = f.read().splitlines()
txnew = []
flg1 = True
for line in tx:
if line == "" and flg1:
txnew += ["\\usepackage{wrapfig}",""]
flg1 = False # just do this once before first blank line
elif "includegraphics{" in line and "hfill" in line:
fname = line.split("{")[2].split("}")[0]
if line.startswith("{\\hfill"): # i.e. right justify
fl_type = "R"
else:
fl_type = "L"
txnew += ["\\begin{wrapfigure}{" + fl_type + "}{0.35\\textwidth}",
"\\includegraphics[width = 0.3\\textwidth]{" + fname + "}",
"\\end{wrapfigure}"]
else:
txnew += [line]
txnew = "\n".join(txnew)
with open("_build/latex/pi3d_book.tex", "w") as fo:
fo.write(txnew)
subprocess.Popen(["pdflatex", "pi3d_book"], cwd="/home/jill/pi3d_book/_build/latex")

Related

Repeat or reference a figure in another rst file

I have two files named a.rst and b.rst, both of which contain a good deal of text. In a.rst, I define a figure:
.. figure:: ../images/some-image.png
:scale: 70%
:align: center
:alt: Some Text
Some Caption
I would like to have the same image and caption in b.rst with the same figure number, But repeating the above code gives me a new figure.
As a compromise, I can refer to this image in b.rst using the :numref: directive, but that does not resolve to the figure. It only displays the name as a piece of code.
I understand that these are two question, but I think they are sufficiently related. How can I repeat or reference a figure defined in a rst file in another file.
Edit to elaborate on the expected output:
I want the resulting files to have the following content:
a.html:
Fig. 1 + caption
Fig. 2 + caption
Fig. 3 + caption
b.html:
Fig. 4 + caption
Fig. 2 + caption
Fig. 5 + caption
Effectively, this would add the figure to b.rst not as a separate entity, but merely as a mirror of what was in a.rst. This is similar to what was discussed here.
Assuming you want to repeat the exact same content in two different files, put that content into a separate file, then include that file wherever you want it to appear.
includeme.rst
Note document root relative path.
.. figure:: /images/some-image.png
:scale: 70%
:align: center
:alt: Some Text
Some Caption
a.rst and b.rst
Below this paragraph should appear an image.
..include:: /includeme.rst
EDIT
To remove the figure number, set numfig to False. This will avoid the incongruent figure numbering, but won't solve it. I think that's the best you can achieve, as Sphinx automatically numbers figures (and other objects) otherwise.

Crazy values on morph targets in unreal engine 4

Oy I'm doing some animations in Maya 2019 and I have some issues once exporter in Unreal Engine 4.20.
For exporting I use the File > Game Exporter menu. (Any other export workflow I tried so far resulted in a freezing import in Unreal).
Everything goes well using the Game Exporter, I do have some errors when imported in UE4 but it all looks fine, except for one thing:
My character's face is all messed up. After some digging, I discovered it's all about some of the face's morph targets having insane values:
If I manually put all those insane values to 0, everything looks fine. What could cause this?
If I check the mesh asset, the morph targets are limited from -1 to 1 and they look as they should look when I move the slider.
The errors I have when importing my animation are:
Imported bone transform is different from original. Please check Output Log to see detail of error.
Mesh [Geometry have no name] in the fbx file is not reference by any hierarchy node.
Thanks for any help.
Sometimes the hard way is actually the simplest way.
I couldn't have anything working using Game Exporter or using plugins, so I made myself a script for baking my animation including my corrective morphs and exported the result in FBX 2018. It works.
So here's how I made up my script:
First I selected my export selection set (it contains my geometry and deforming joints), then clicked Key > Bake Simulation (you have to be in Animation set menu to have the key menu displayed). I open the script editor and copy the command line starting by "bakeResults" (it's easy to find it if you have selected plenty of things just before: it's a massively long line at the end of the script editor).
From there I have my script base, but it doesn't include the baking of my blend shapes.
So, for each object with blend shapes to bake:
select the object in the outliner
double click its blend shape input in the channel box
copy its name
paste it at the end of the script, just before the };
make sure to respect the syntax: each list element must be between two " and separated with a comma and space , . No comma nor space after the last element before };
It looks something like this:
bakeResults -simulation true -t "1:60" -sampleBy 1 -oversamplingRate 1 -disableImplicitControl true -preserveOutsideKeys true -sparseAnimCurveBake false -removeBakedAttributeFromLayer false -removeBakedAnimFromLayer false -bakeOnOverrideLayer false -minimizeRotation true -controlPoints false -shape true {"element_to_bake", "another_thing_to_bake"};
But with much more elements in the list.
Notice the -t "1:60" in the line: it's the frame range you want to bake. You will need to adapt those numbers to your needs.
Once you have this line, I recommend you save it in a file somewhere.
To use it, SAVE YOUR PROJECT BEFORE BAKING, then paste the script in the MEL command line at the bottom left corner of the UI, adapt the time range if needed, then press ⏎ ENTER to execute the baking script.
When the baking is finished, you can export your FBX and then reload your saved project file.

Clear the current path in Cairo

In some Ruby code which uses Cairo, I need to draw a number of fills over a single path. This is part of a graphics application, where multiple fills may be stacked on top of each other using different blend modes.
Each fill is drawn using fill_preserve to preserve the path so that the next fill can occur over the same path without retracing it. This is done somewhat like so:
rectangle_data.each do |rectangle_datum|
context.rectangle(*rectangle_datum.rectangle)
fill_data.each do |fill_datum|
context.set_source_rgba(*fill_datum.color)
context.fill_preserve
end
end
The problem is that this leaves the path even after all fills have taken place, which means that individual shapes are just drawn as one huge filled shape.
To solve this, I'd simply need to clear the current path manually, but I can't figure out how to do this. I've had a look through the documentation for Cairo::Context through Google Translate but I can't find it. (The docs are in Japanese!)
How can I manually clear a Cairo context's current path?
I had a look over Cairo::Context#methods and found #new_path, which does just what I'm after. So you can do:
rectangle_data.each do |rectangle_datum|
context.rectangle(*rectangle_datum.rectangle)
fill_data.each do |fill_datum|
context.set_source_rgba(*fill_datum.color)
context.fill_preserve
end
context.new_path
end

Smooth animation of three shapes in SciLab

This answer provides a nice way to make smooth animations in SciLab. I now have to write a simulation of a body attached to two strings (and therefore its movement regarding some additional forces).
The code in the link works well to render movement of a single point and, unfortunately, I didn't manage to make an animation of a point + two lines using this method. If someone is curious, I tried this code to do it:
frametime=(tk-t0)/Nt//defining the waitnig time
plot(Y(1,1),Y(2,1),"o")//plotting the point
plot([0;Y(1,1)],[0;Y(2,1)],style=1)
plot([D;Y(1,1)],[0;Y(2,1)],style=1)//plotting the two initial lines
h1_compound = gce();
h_point=h1_compound.children
h_point.mark_size = 20;
h_point.mark_background = 2;
h_line1=h_compound.children
h_line2=h_compound.children
//h_axes = gca();
//h_axes.data_bounds = [0,-1;10,1];
realtimeinit(frametime);
for i=1:Nt//my vectors have Nt points
realtime(i);//wait "frametime" seconds before drawing the new position
h_point.data=[Y(1,i),Y(2,i)];
h_line1.data=[[0;Y(1,i)],[0;Y(2,i)]]
h_line2.data=[[D;Y(1,i)],[0;Y(2,i)]]
end
The question is: is there any way to make an animation of three shapes without making axes blink (as it is with the window refreshment) or other wierd stuff?
Since you didn't create a MCVE I can't reproduce your exact problem. But you may try to add drawlater(); before, and drawnow(); after your data modification to see if it does help with blinking or not.
Or you may get much better looking result by saving your plots in every round with xs2gif and assemble the animation with another gifmaker progam (there are free online sites to do this, however with some limitations). If you need to present your result, you should do this step anyway.

Latex - Is it possible to have text on top of images?

I want to create something like a leaflet/magazine using Latex. Is it possible to place text on top of an image and style the text freely?
Any links to examples of something like this?
I usually do something like
\usepackage{tikz}
...
\begin{tikzpicture}
\draw (0, 0) node[inner sep=0] {\includegraphics[width=4cm]{imagefile.png}};
\draw (1, 1) node {Hello world};
\end{tikzpicture}
A very good toolset for manipulating images is pgf/TikZ pdf doc.
See \pgfimage for examples. It allows to mix text and image freely. There are many ways to do it. One of them is to use layers (p. 220 of pgfmanual). The pgf manual contains many simple examples, and is very precise.
Another solution is to use the lpic package: the homepage contains some examples.
You can find other examples for pfg and TikZ here and here for many impressive examples.
You can also define the text after the image and then offset it using negative vertical space. Because it follows after the image in the LaTeX source, it will be drawn on top of the image instead of underneath it.
\includegraphics[...]{...}
\vspace*{-20ex} % Tune this to the image height.
\begin{center}
Text
\end{center}
\vspace*{20ex} % The spacing above but without the minus.
Another solution is the textpos package which allows you to specify boxes at absolute positions on the page. The boxes can overlap, so you can put the figure in one box, and text in another box on top of it.
I realise that the question is old and answer is accepted, but for completeness would like to propose an alternative approach for making leaflets in LaTeX.
Specifically, the leaflet document style served me really well for this purpose.
A good blog post wrt background image can be found here. There are a couple of packages that are required to use in order to make the proposed approach work, but were not mentioned in the blog post:
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{transparent}
As already suggested, you can annotate the different parts of the figure using TikZ. However, sometimes it might even better to use numbers to reference the different parts and explain them in the figure caption.
To easily get the precise relative positions (which is often tedious) and to generate LaTeX code automatically, you could use the new web-based LaTeX Overlay Generator, which I built for such cases. This is just a small interactive tool, which helps you to find the right locations.
Another way to do this, admittedly not using LaTeX, would simply be to edit the image with photoshop or gimp or something like that. I guess your option in terms of typesetting mathematics might be fairly limited doing it this way.
Otherwise I'd endorse using tikz.
Are you sure you want to do it in LaTeX? Desktop publishing software might be more suited to your needs... Something like scribus might be easier than tikz in terms of learning curve, depending on what you want to do.
I'd like to add on to #midtiby's answer...
You can also specify the text position using a relative position, like so:
\usepackage{tikz}
...
\begin{tikzpicture}
\node[inner sep=0] (image) at (0,0) {\includegraphics[width=4cm]{imagefile.png}};
\node[above=0 of image] {Hello world};
\end{tikzpicture}

Resources