Python - Creating simple Algebraic Decision Diagram (ADD) with py-mdd or dd packages
I would like to create and ouput a graphical representation with Python 3 of an Algebraic Decision Diagram (ADD) [Bahar et al.].
Here an example of an ADD to output:
The inputs a
and b
are Boolean values. A plain edge corresponds to set the variable to True
, and a dotted edge to False
. The outputs are integers.
The function in the example could be expressed as:
def my_function(a, b):
if a == False and b == False:
return 2
if a == False and b == True:
return 1
if a == True and b == False:
return 1
if a == True and b == True:
return 0
Or as a list of dictionnaries:
my_add = [{'a': False, 'b': False, 'output': 2},
{'a': False, 'b': True, 'output': 1},
{'a': True, 'b': False, 'output': 1},
{'a': True, 'b': True, 'output': 0},]
How can I generate the graphical representation of this function as an ADD?
Which package is better suited for that: dd or py-mdd?
Many thanks!
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
how do I dissable debian python path/recursion limit
so, as of late, I've been having path length limit and recursion limit issues, so I really need to know how to disable these.
I can't even install modules like discord.py!!!!
-
TypeError: 'float' object cannot be interpreted as an integer on linspace
TypeError Traceback (most recent call last) d:\website\SpeechProcessForMachineLearning-master\SpeechProcessForMachineLearning-master\speech_process.ipynb Cell 15' in <cell line: 1>() -->1 plot_freq(signal, sample_rate) d:\website\SpeechProcessForMachineLearning-master\SpeechProcessForMachineLearning-master\speech_process.ipynb Cell 10' in plot_freq(signal, sample_rate, fft_size) 2 def plot_freq(signal, sample_rate, fft_size=512): 3 xf = np.fft.rfft(signal, fft_size) / fft_size ----> 4 freq = np.linspace(0, sample_rate/2, fft_size/2 + 1) 5 xfp = 20 * np.log10(np.clip(np.abs(xf), 1e-20, 1e100)) 6 plt.figure(figsize=(20, 5)) File <__array_function__ internals>:5, in linspace(*args, **kwargs) File ~\AppData\Local\Programs\Python\Python39\lib\site-packages\numpy\core\function_base.py:120, in linspace(start, stop, num, endpoint, retstep, dtype, axis) 23 @array_function_dispatch(_linspace_dispatcher) 24 def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, 25 axis=0): 26 """ 27 Return evenly spaced numbers over a specified interval. 28 (...) 118 119 """ --> 120 num = operator.index(num) 121 if num < 0: 122 raise ValueError("Number of samples, %s, must be non-negative." % num) TypeError: 'float' object cannot be interpreted as an integer
What solution about this problem?
-
IndexError: list index out of range with api
all_currencies = currency_api('latest', 'currencies') # {'eur': 'Euro', 'usd': 'United States dollar', ...} all_currencies.pop('brl') qtd_moedas = len(all_currencies) texto = f'{qtd_moedas} Moedas encontradas\n\n' moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars'] while len(moedas_importantes) != 0: for codigo, moeda in all_currencies.items(): if codigo == moedas_importantes[0]: cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date'] texto += f'{moeda} ({codigo.upper()}) = R$ {cotacao} [{data}]\n' moedas_importantes.remove(codigo) if len(moedas_importantes) == 0: break # WITHOUT THIS LINE, GIVES ERROR
Why am I getting this error? the list actually runs out of elements, but the code only works with the if
-
How can I speed up the routing process in OSMNX?
Say I have two taxi orders with Origin1、Destination1 and Origin2、Destination2(O1,O2,D1,D2). I want to calculate the possibility of ridesharing, so I need the path between two different points. And, here's my code:
def path_time(point1, point2): path = ox.distance.shortest_path(road, point1, point2, weight='travel_time') if path is None: #If there isn't a path, a big weight will be set, and it won't be selected during the matching process. route_time = 9999 else: route_time = int(sum(ox.utils_graph.get_route_edge_attributes(road, path, "travel_time"))) return route_time,path
Since there is four points, I need to do this six times, where tp means travel path :
tpO1O2 = path_time(O1,O2) tpO1D1 = path_time(O1,D1) tpO1D2 = path_time(O1,D2) tpO2D1 = path_time(O2,D1) tpO2D2 = path_time(O2,D2) tpD1D2 = path_time(D1,D2)
It's okay if I only have two points, but I got a 2 million order set, and each order has hundreds of potential matched orders. So this will take me a lot of time.
Does anyone knows how can I speed up this process? Thank you!
-
How to properly plot a tree (27k nodes) using a circular tree / leave layout
I have this (unbalanced) tree with 27k+ nodes. It is an hierachy. Now I would to plot it as such to obtain a plot something like this (no idea how you would describe it, but I would call it a circular leave tree...?
However, I am unable to achieve such a result unfortunately. I have already tried
igraph
,Networkx
,Maltego
,Graphviz
,Gephi
. Hopefully someone can help me / give me tips & tricks or hints.Maltego
Gives me quiet easily the following. However I cannot export it to pdf. Furthermore it has this wierd expansion on the top going to the left. I would be able to 'manually' (minimize) move it. However that is not what I would like.
This is btw in my view (with the manual fix) the best result. But I cannot export it to vector or high-res image.
igraph
import igraph as ig bigGraphAsTupleList = (('a','b'),('b','c'),('b','d'), ..., ('c','e')) g = ig.Graph.TupleList(bigGraphAsTupleList) layout = g.layout("rt_circular") #fr (fruchterman reingold), tree, circle, rt_circular (reingold_tilford_circular) # bbox = size of picture ig.plot(g,layout=layout,bbox=(10000,10000),target='mygraph.png')
This gives me something like below.
fruchterman reingold (so much overlap of nodes and connections)
Networkx
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_edge(...) #build graph nx.draw_circular(G) #nx.draw_spring(G) #nx.draw_spectral plt.draw() plt.show()
Graphviz (via Networkx)
Also a wierd result a bit similar as the next one Maltego. However
import networkx as nx import matplotlib.pyplot as plt import pydot from networkx.drawing.nx_pydot import graphviz_layout G = nx.Graph() G.add_edge(...) #build graph pos = graphviz_layout(G, prog="circo") plt.figure(1,figsize=(60,60)) nx.draw(G, pos,node_size=10) plt.show(block=False) plt.savefig("Graph.png", format="PNG")
-
Object and Pointers Graph Representation in Ruby
I am studying how to represent a graph in memory with Objects and Pointers in ruby and cannot find a representation of this anywhere. Can anyone point me in the right direction of how to build this ds?
-
Convert binary to string c++
I am trying to convert a string of binary to a string of ascii characters in c++.
I have tried a lot of things and none of them worked. Someone know how can I do it?
This is the function that supposed to convert the binary to string. But it's not working. I believe this is because of the size limitations that integers have.std::string convertBinaryToStr(std::string binaryToConvert) { unsigned long long number = std::stol(binaryToConvert, 0, 2); return std::bitset<BIT_IN_BYTES>(number).to_string(); }
possibale input: "011110110101110000100010011010000110010101111001010111000010001000111010001000000011000101111101"
expacted output:
"{"hey": 1}"- I tried to convert the binary string to integer using
stol
but the end string binary representation can be more than the max value of integers. - I can replace the string to vector of chars is it's halpful.
- I tried to convert the binary string to integer using
-
Determine in Java, whether a file is a picture, having only binary data
The situation is this: in my code I download a picture from the Internet as an array of bytes:
byte[] imageBytes
. And then I make the object of myMyImage
class:public class MyImage { private String imageName; private byte[] data; // Constructor, getters, setters }
Create object:
MyImage myimg = new MyImage("some_name", imageBytes);
Then I use my resulting object.
I have a question: can I somehow make sure, that I downloaded the picture file?
It seems that each file type has its own signature (that is, the first bytes of the file). But there are a lot of different types of files. And if I compare the signature of my file with all existing types of signatures, then these will be very large checks.
Is it possible to make the check simpler: do I currently have an image (no matter what type) or not image?
Why do I want to do this: what if the user mistakenly passes a link not to an image, but to a file of a different type (for example, an archive). And in this case, I would like to determine in the code that the wrong file was downloaded and give the user an appropriate error message.
-
fetch last item of core data array
In my swift code below my goal is fetch the last image of the core data array. Right now my code is having a runtime error with indexpath. I dont know if you need to use a index path to do this. I have also added a screenshot that features all of the core data info.
var pic = UIImageView() func loadImage(){ if let imageData = itemNamez[IndexPath.last(pic)] { let coredataLoadedimage = UIImage(data: imageData) pic.image = coredataLoadedimage } }