vtkOBJImporter color mapping for k3d - python-3.x

Following the code here, one can get granular vtkPolyData to pass to k3d in python. However I am currently assigning color to k3d like so;
def rgb2hex(r,g,b):
return eval("0x{:02x}{:02x}{:02x}".format(r,g,b))
#using the actors from [referenced code][1] to get the granular actors from .OBJ
col = actor.GetProperty().GetDiffuseColor()
rgb2hex(int(col[0]*255),int(col[1]*255),int(col[2]*255))
This is ugly and inefficient. vtkPolyDataMapper should be already handling the color, so there must be a way of doing this in a more direct way. How can one use the vtkPolyDataMapper to get a list of colors to pipe to the k3d.vtk_poly_data() color argument?
mapper = actor.GetMapper()
mapper.SetInputData(vtkPolyData)

VTK does not natively provide this formatting (0xrrggbb) for color. You always have to deal with 3-components floats or integers.

Related

Zoom-out for manim Axes

Suppose we have an Axes object and a graph plotted in the coordinate system defined by these axes.
Is it possible to "zoom-out" by one or both axes, so we can see more of the graph, while the dimensions of the Coordinate system on the screen are kept constant?
For example, I've tried using the ValueTracker for both x_range properties of the Axes and the graph but it gives strange and unexpected results.
class Test(Scene):
def construct(self):
x_max_tracker = ValueTracker(0.0)
axes = always_redraw(lambda: Axes(
(-np.pi, x_max_tracker.get_value(), 0.5), (-5., 5.),
width=8, height=10
))
xsin_graph = always_redraw(
lambda: axes.get_graph(
lambda x: 0.5*x*np.sin(x)-1, color=BLUE,
x_range=[-np.pi, x_max_tracker.get_value()]
)
)
self.play(
Write(axes, lag_ratio=0.01, run_time=1), ShowCreation(xsin_graph)
)
self.wait(2)
self.play(x_max_tracker.animate.set_value(4*np.pi), run_time=2)
Additional, but connected question: is it possible to give the position of the coordinate system (Axes) at initiation?
UPDATE
I have defined a method generate_axes() which: 1) generates the Axes object; 2) Places it at specified coordinates on the Scene.
Now, if I am calling the always_redraw method on this generate_axes() method (keeping the x_tracker from the code above to control the x_range) then I could obtain nice "zoom-out/in" animation by calling play(x_tracker.animate.set_value(X)).
However, this doesn't change the axes variable, which is, apparently, still keeping the pointer on the first initial Axes object with not modified x_range. I thought that always_redraw() creates a new mobject each frame? Somehow this updated object is transferred to the Scene to be displayed but can't be accessed! For example, if I print axes.x_range after the end of the animation I am getting the initial x_range value.
P.S.: I am using the manimgl package, so the method always_redraw is probably not from the standard manim package. But it is generally the add_updater with become
Currently, Axes unfortunately do not support the sort of rescaling you would like to use. The easiest way to achieve this sort of behavior probably is by implementing a custom animation that repeatedly updates the axes and any curves within with become.
And as for your second question: Axes are always drawn in a way such that the center of the mobject is in the scene origin. You can move them to where you would like to show them, and only add them after moving.
Update
.become creates a new mobject, yes, but then only transfers some of the new mobject's properties and attributes to the original mobject. If there are some attributes that you need updated, it is best if you simply updated them yourself in your method -- which is also why using a general updater function is more flexible than always_redraw.
And for future reference: make sure to say right away whether you are working with manim or manimgl, they are substantially different in some aspects.

Need Help creating class hierarchy in Python

I have a hierarchy of data that i would like to build using classes instead of hard coding it in. The structure is like so:
Unit (has name, abbreviation, subsystems[5 different types of subsystems])
Subsystem ( has type, block diagram(photo), ParameterModel[20 different sets of parameterModels])
ParameterModel (30 or so parameters that will have [parameter name, value, units, and model index])
I'm not sure how to do this using classes but what i have made kindof work so far is creating nested dictionaries.
{'Unit':{'Unit1':{'Subsystem':{'Generator':{Parameter:{'Name': param1, 'Value':1, 'Units': 'seconds'}
like this but with 10-15 units and 5-6 subsystems and 30 or so parameters per subsystem. I know using dictionaries is not the best way to go about it but i cannot figure out the class sharing structure or where to start on building the class structure.
I want to be able to create, read, update and delete, parameters in a tkinter gui that i have built as well as export/import these system parameters and do calculations on them. I can handle the calculations and the import export but i need to create classes that will build out this structure and be able to reference each individual unit/subsystem/parameter/value/etc
I know thats alot but any advice? ive been looking into the factory and abstract factory patterns in hope to try and figure out how to create the code structure but to no avail. I have experience with matlab, visual basic, c++, and various arduio projects so i know most basic programming but this inheritance class structure is something i cannot figure out how to do in an abstract way without hardcoding each parameter with giant names like Unit1_Generator_parameterName_parameter = ____ and i really dont want to do that.
Thanks,
-A
EDIT: Here is one way I've done the implementation using a dictionary but i would like to do this using a class that can take a list and make a bunch of empty attributes and have those be editable/callable generally like setParamValue(unit, susystem, param) where i can pass the unit the subsystem and then the parameter such as 'Td' and then be able to change the value of the key,value pair within this hierarchy.
def create_keys(list):
dict = {key: None for key in list}
return dict
unit_list = ['FL','ES','NN','SF','CC','HD','ND','TH'] #unit abbreviation
sub_list = ['Gen','Gov','Exc','PSS','Rel','BlkD']
params_GENROU = ["T'do","T''do","T'qo","T''qo",'H','D','Xd','Xq',"Xd'","Xq'","X''d=X''q",'Xl','S(1.0)','S(1.2)','Ra'] #parameter names
dict = create_keys(unit_list)
for key in dict:
dict[key] = create_keys(sub_list)
dict[key]['Gen'] = create_keys(params_GENROU)
and inside each dict[unit][Gen][ParamNames] there should be a dict containing Value, units(seconds,degrees,etc), description and CON(#basically in index for another program we use)

PyQt: Obtain all pixels inside QPolygon

In PyQt 5, is there a way to obtain all pixel positions that would be modified by a call to QPainter.drawPolygon for a QPainter object constructed with some QImage as an argument without actually drawing the polygon? Ideally I would like to obtain separate sets of pixel positions for the polygon's border and for all pixels inside the polygon.
Just like #ekhumoro said, QPolygon is a subclass of QVector (that is, a QList). However, in Pyqt this is a Python array and not a QList. I got runtime errors when trying to iterate over this list, because it was inside the QPolygon object and there was no getter. In this case, in PyQt the solution is not very efficient. You need to iterate over each pixel of the image, creating a QPoint with pixel coordinates and checking if the QPolygon contains this point through the containsPoint method. There aren't many implementation details, but consider the following code snippet.
array_qpoints = [] # this array will have all the QPoints
polygon = QPolygon([
QPoint(140,234),
QPoint(126,362),
QPoint(282,409),
QPoint(307,273),
QPoint(307,233),
])
# let's consider a 640x480 image
for x in range(640):
for y in range(480):
point = QPoint(x, y)
if polygon.containsPoint(point, Qt.FillRule.OddEvenFill):
array_qpoints.append(point)
You can get the coordinates of each pixel by calling the x() and y() methods for each element in array_qpoints.
for point in array_qpoints:
x = point.x()
y = point.y()
# do what you want with the information
I'm posting this answer for others who visit this question and are looking for a solution by code. Since it's been several years, if you've found a better solution, please post :)

Placing "markers" in MathJax math expressions

Suppose I have some equation, say:
$$\underbrace{ \frac{a}{b} }_{c}$$
And, I want to get the location of the $c$ in the HTML/CSS/SVG output of MathJax.
Is there a way to do this? I.e. I'd like to do something like:
$$\underbrace{ \frac{a}{b} }_{c\invisiblemarkerXYZ}$$
then be able to do a query to get the DOM element corresponding with invisiblemarkerXYZ
Thanks!
EDIT this is what I want to do:
Equation 1 = $$\underbrace{\frac{a}{b}}{A}$$
Equation 2 = $$A = \sum_{i=1}^n i$$
Now, I want to draw a line (via SVG) of the two A's. Thus, I need some way to obtain the location of the MathJax elements.
You can use \cssId{XYZ}{c} to set the id="XYZ" on the element used for the c, and can then use document.getElementById("XYZ") to obtain that DOM element. But the output from MathJax's HTML-CSS and SVG processors is not designed to be manipulated after the fact. For example, in general you will not be able to get the dimensions of the element from the HTML-CSS output as the offsetHeight and offsetWidth may not be what you expect them to be. (The height is frequently set to 0, for example.)
Can you say something more about what you are trying to accomplish?

How can I render mixed-colour text in DirectWrite?

I want to use DirectWrite for mixed-colour text formatting (syntax highlighting, to be precise), but can't seem to find a way to do it, either in the Layout or Typography options. The only option is passing a Brush when rendering the text, which doesn't work for me because I basically have just one Layout. Help!
Use IDWriteTextLayout::SetDrawingEffect to apply drawing effects on subranges. If you're using DWrite with D2D DrawTextLayout, which it sounds like you are, then that drawing effect would just be a brush (such as ID2D1Brush via CreateSolidColorBrush or one of the gradient brushes). If you have implemented your own IDWriteTextRenderer for IDWriteTextLayout::Draw, then the drawing effect can be whatever you interpret it to be. In the IDWriteTextRenderer::DrawGlyphRun callback, you then call QueryInterface on the drawingEffect parameter, or if you are certain it is your own type, just static_cast it directly.
// ... create the colored brushes and determine where to draw ...
wchar_t const* text = L"Red Green";
dwriteFactory->CreateTextLayout(....., OUT &textLayout);
DWRITE_TEXT_RANGE textRange1 = {0,3}, textRange2 = {4,5};
textLayout->SetDrawingEffect(redBrush, textRange1);
textLayout->SetDrawingEffect(greenBrush, textRange2);
renderer->DrawTextLayout(point, textLayout, defaultBrush);

Resources