Colored graph isomorphism? - networkx

I have two colored graphs. I want to determine if they are isomorphic, with the condition that the isomorphism must preserve vertex color. Is there an algorithm in networkx to do this?
The graphs are undirected and simple.

Check the documentation for is_isomorphic. It takes an optional argument nodes_match which is a function that tests some condition on the two nodes. It is called by node_match(G1.node[n1], G2.node[n2]). So in this case, you want a function that tests whether the colors are matching.
import networkx as nx
def colors_match(n1_attrib,n2_attrib):
'''returns False if either does not have a color or if the colors do not match'''
try:
return n1_attrib['color']==n2_attrib['color']
except KeyError:
return False
G=nx.Graph()
G.add_node(1, color='y')
G.add_node(2, color='b')
H=nx.Graph()
H.add_node('a', color='y')
H.add_node('b', color = 'b')
nx.is_isomorphic(G,H,node_match=colors_match)
>True
H.add_node('c', color='r')
nx.is_isomorphic(G,H,node_match=colors_match)
>False

Related

Is it possible to not use cardinality constraint to generate solution candidates in clingo?

I'm learning Answer Set Programming by solving the zebra puzzle.
I found some solution examples online.
But someone told me that I can solve the puzzle without using cardinality constraint macro to generate solution Candidates.
Like without using this
{ color(House, Color) : colors(Color) }= 1 :- houses(House).
{ color(House, Color) : houses(House) }= 1 :- colors(Color).
the goal is to generate different models with a unique combination of color(House, Color).
Is this possible without {atom: atom}=1:-atoms.?
You can do this with inequality constraints, and a weak constraint to generate the maximal number of combinations.
% Generate assignments of colors to houses.
{ color(House, Color) } :- houses(House), colors(Color).
% A house can only have one color.
:- color(House, Color_1), color(House, Color_2), houses(House),
colors(Color_1), colors(Color_2), Color_1 != Color_2.
% Each color can only be assigned to one house.
:- color(House_1, Color), color(House_2, Color), colors(Color),
houses(House_1), houses(House_2), House_1 != House_2.
% Generate a maximal number of combinations (i.e. all of them).
:~ color(House, Color), houses(House), colors(Color). [-1#0, House, Color]
Although, this needlessly more verbose than your current encoding.

Editing the labels on a flow chart with DiagrammeR

I’m trying to make a flow chart with R. Attached is the chart I made in word (which is what I'm trying to get to). I don’t want to copy and paste it, I want to actually make it in R. I’ve been using DiagrammeR to try, and the code is below.
I'm having the main trouble with the labels, how to change some parts to bold and make them a nice distance away from the nodes. I've added in the blue and pink boxes in my code, which I like.
Code:
library(DiagrammeR)
graph <- "
digraph boxes_and_circles{
# Add node statements
# This states that all following nodes have a box shape
node[
shape=box,
style=rounded,
fontname=Helvetica,
penwidth=2,
fixedsize = true
width=4
]
# Connect the nodes with edge statements
edge[
arrowhead = normal,
arrowtail = none
]
# These are the main nodes at top of graph
'##1'->'##2'
[label=' Cleaning Function:
Text to lower case
Contractions expanded
Numbers replaced
Abbreviations expanded (Qdap)
NA’s ignored
Kerns replaced
White space removed', fontname=Helvetica, fontsize=20, fontweight=bold]
'##2'->'##3'
'##2'->'##4'
# Make subnodes with boxes around for tidy text grouping
# graph, node, and edge definitions
graph [
compound = true,
nodesep = 1,
ranksep = 0.25,
color = pink
]
# subgraph for tidy text, direct the flow
subgraph cluster0 {
'##3'->'##5'
[label=' -Tokenization
-Lemetisation
-Stop words removed', fontname=Helvetica, fontsize=20, fontweight=bold]
}
# Make subnodes with boxes around for Dictionary grouping
# graph, node, and edge definitions
graph [
compound = true,
nodesep = 1,
ranksep = .25,
color = blue
]
# subgraph for Dictionary direct the flow
subgraph cluster1 {
node [
fixedsize = true,
width = 3
]
'##4'->'##6' [label=' Scoring function (sentimentr)
Inner Join (dplyr)',fontname=Helvetica]
'##6'->'##7' [label=' Grouping
Summarise (dplyr)',fontname=Helvetica]
'##7'->'##8'
}
#Add a graph statement to change the properties of the graph
graph[nodesep=1] #this modifies distance between nodes
}
# Name the nodes
[1]: 'Response Data'
[2]: 'Clean Data'
[3]: 'Tidy Text'
[4]: 'Dictionary Creation'
[5]: 'Visualisation'
[6]: 'Sentiment Lexicon'
[7]: 'Summarised Text'
[8]: 'Visualisation and Statistics'
"

Clingo: Compare String Literals by Order (Index)?

I have defined a color palette called tableau10 in Clingo:
tableau10(blue;orange;red;teal;green;yellow;purple;pink;brown;gray).
Is there a way to compare the colors by the order they appear in my color definition? (e.g., blue = 0, orange = 1, red = 2, ...)
My goal is to be able to claim things like blue < orange, blue < gray...
The predicate tableau10 is unordered. To do such comparisons you'd have to encode order in one way or another. You could for example assign numbers to the colors value(blue, 1). value(orange, 2). ... and compare the associated numbers when necessary, or you could write lessthan(blue, orange). lessthan(orange, red). ... lessthan(brown,gray). and also add the transitivity rule lessthan(A, C) :- lessthan(A, B), lessthan(B, C).

Unity is returning material color slightly wrong

I have this mini task in my game where you need to click trophies to change color of the wood on them. I have two arrays of colors, one is an array containing all possible colors and the other one contains four colors (the answer) as follows:
I've double checked that the colors are equal between the two arrays. For example the purple in Colors-array has exactly the same r, g, b & a values as the purple in the Right Order-array.
To check whether the trophies has correct color I just loop through them and grab their material color. Then I check that color against the Right Order-array but it's not quite working. For example when my first trophy is purple it should be correct, but it's not because for some reason Unity is returning slightly different material color than excepted:
Hope somebody knows why this is happening.
When you say, they are exactly same color, I assume you are referring rgb values from Color Inspector, which are not precise values.
Now I dont know what could be causing in different values of colors but
You can write an extension method to compare the values after rounding them to closest integer.
public static class Extensions
{
public static bool CompareRGB(this Color thisColor, Color otherColor)
{
return
Mathf.RoundToInt(thisColor.r * 255) == Mathf.RoundToInt(otherColor.r * 255) &&
Mathf.RoundToInt(thisColor.b * 255) == Mathf.RoundToInt(otherColor.b * 255) &&
Mathf.RoundToInt(thisColor.g * 255) == Mathf.RoundToInt(otherColor.g * 255);
}
}
usage:
Color red = Color.Red;
red.CompareRGB(Color.Red); // true;
red.CompareRGB(Color.Green); // false;
Hope this helps.
I would use a palette. This is simply an array of all the possible colors you use (sounds like you have this). Record, for each "trophy", the INDEX into this array, at the same time you assign the color to the renderer. Also, record the index for each "button", at the same time you assign the color to the renderer.
Then you can simply compare the palette index values (simple integers) to see if the color matches.

World.QueryAABB giving incorrect results in libgdx

I'm trying to implement mouse selection for my game. When I QueryAABB it looks like it's treating objects much larger than they really are.
Here's what's going on in the image
The blue box is an actor containing a body that I'd like to select
The outline on the blue box is drawn by Box2DDebugRenderer
The mouse selects a region on the screen (white box), this is entirely graphical
The AABB is converted to meters and passed to QueryAABB
The callback was called for the blue box and turned it red
The green outline left behind is a separate body to check if my conversions were correct, this is not used for the actual selection process
It seems to be connected to my meter size, the larger it is, the more inaccurate the result is. At 1 meter = 1 pixel it works perfectly.
Meter conversions
val MetersToPixels = 160f
val PixelsToMeters = 1/MetersToPixels
def toMeters(n: Float) = n * PixelsToMeters
def toPixels(n: Float) = n * MetersToPixels
In the image I'm using MetersToPixels = 160f so the inaccuracy is more visible, but I really want MetersToPixels = 16f.
Relevant selection code
val x1 = selectPos.x
val y1 = selectPos.y
val x2 = getX
val y2 = getY + getHeight
val (l,r) =
if (x2 < x1)
(x2,x1)
else
(x1,x2)
val (b,t) =
if (y2 < y1)
(y2,y1)
else
(y1,y2)
world.QueryAABB(selectCallback, toMeters(l),toMeters(b), toMeters(r),toMeters(t))
This code is inside the act method of my CursorActor class. And selectPos represents the initial point where the use pressed down the left mouse button and getX and getY are Actor methods giving the current position. The next bit sorts them because they might be out of order. Then they are converted to meters because they are all in pixel units.
selectCallback: QueryCallback
override def reportFixture(fixture: Fixture): Boolean = {
fixture.getBody.getUserData match {
case selectable: Selectable =>
selected += selectable
true
case _ => true
}
}
Selectable is a trait that sets a boolean flag internally after the query which helps determines the color of the blue box. And selected is a mutable.HashSet[Selectable] defined inside of CursorActor.
Other things possibly worth noting
I'm new to libgdx and box2d.
The camera is scaled x2
My Box2DDebugRenderer uses the camera's combined matrix multiplied by MetersToPixels
From what I was able to gather, QueryAABB is naturally inaccurate for optimization. However, I've hit a roadblock with libgdx because it doesn't have any publicly visible function like b2testOverlap and from what I understand, there's no plan for there to be one any time soon.
I think my best solution would probably be to use jbox2d and pretend that libgdx's physics implementation doesn't exist.
Or as noone suggested I could add it to libgdx myself.
UPDATE
I decided to go with a simple solution of gathering the vertices from the fixture's shape and using com.badlogic.gdx.math.Intersector against the vertices of the selection. It works I guess. I may stop using QueryAABB all together if I decide to switch to using a sensor for the select box.