dgraph-flex 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ from .dgraph_flex import DgraphFlex # Import the DgraphFlex class
@@ -0,0 +1,218 @@
1
+ #! /usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import argparse
5
+ import os
6
+ import glob
7
+ import sys
8
+ import json
9
+ from pathlib import Path
10
+ import textwrap
11
+ from glob import glob
12
+ import yaml
13
+
14
+ from graphviz import Digraph
15
+ import matplotlib.pyplot as plt
16
+ # import networkx as nx
17
+ # import pandas as pd
18
+ # import numpy
19
+ # import seaborn as sns
20
+
21
+
22
+ # from dotenv import dotenv_values # pip install python-dotenv
23
+ # import yaml # pip install pyyaml
24
+
25
+ """
26
+
27
+
28
+
29
+ """
30
+
31
+ __version_info__ = ('0', '1', '0')
32
+ __version__ = '.'.join(__version_info__)
33
+
34
+ version_history = \
35
+ """
36
+ 0.1.0 - initial version
37
+ """
38
+
39
+
40
+
41
+ class DgraphFlex:
42
+
43
+ def __init__(self, **kwargs):
44
+
45
+ # initialize the graph
46
+ self.graph = {}
47
+
48
+
49
+ # load self.config
50
+ self.config = {}
51
+ for key, value in kwargs.items():
52
+ self.config[key] = value
53
+
54
+ # load the graph description from the yaml file
55
+ # self.load_graph()
56
+
57
+ pass
58
+
59
+
60
+ def read_yaml(self, yamlpath, version=1.0):
61
+ "read in the yaml config file"
62
+ with open(yamlpath, 'r') as file:
63
+ self.graph = yaml.safe_load(file)
64
+
65
+ if self.graph['GENERAL']['version'] > version:
66
+ print(f"Error: Supports up to {version}, this is version {self.graph['GENERAL']['version']}")
67
+ sys.exit(1)
68
+
69
+ return self.graph
70
+
71
+ def cmd(self, cmd):
72
+ if cmd == 'plot':
73
+ self.read_yaml(self.config['yamlpath'])
74
+ self.load_graph()
75
+
76
+ def load_graph(self, graph=None, index=0):
77
+ """
78
+ Load a graph definition from a yaml file into a graphviz object
79
+
80
+
81
+ set the edge attributes starting from the first character to the third character
82
+
83
+ --> == These indicate a direct causal influence. For example, A --> B means that variable A directly causes variable B
84
+ o-> == Indicates that either A causes B, or there's an unobserved confounder affecting both A and B, or both.
85
+ <-> == Indicates the presence of an unobserved confounder affecting both variables.
86
+ --- == These represent a relationship between variables, but the direction of causality is uncertain.
87
+ o-o == Indicates that either A causes B, B causes A, or there's an unobserved confounder, or any combination of these.
88
+
89
+ """
90
+
91
+
92
+ # create the graph object
93
+ self.dot = Digraph( format='png')
94
+
95
+ # set the node attributes
96
+ self.dot.attr('node', shape='oval')
97
+
98
+ if graph is None:
99
+ # use the graph from the object
100
+ graph = self.graph
101
+
102
+ # start with the edges in self.graph
103
+ for edge in graph['GRAPHS'][index]['edges']:
104
+
105
+ edge_attr = {
106
+ "dir": "both",
107
+ "label": "",
108
+ }
109
+
110
+ # set default values for arrowhead and arrowtail
111
+ arrowhead = 'normal'
112
+ arrowtail = 'none'
113
+
114
+ # set the arrowhead and arrowtail based on the edge type
115
+ if edge['edge_type'] == 'o->':
116
+ arrowtail='odot'
117
+ elif edge['edge_type'] == 'o-o':
118
+ arrowtail='odot'
119
+ arrowhead='odot'
120
+
121
+ # create info structure to ease access to edge information
122
+ label = ''
123
+ color = 'black'
124
+
125
+ if edge.get('properties',False):
126
+ if edge['properties'].get('strength', None) is not None:
127
+ label = f"{edge['properties']['strength']}"
128
+ # check for pvalue
129
+ if edge['properties'].get('pvalue', None) is not None:
130
+ label += f"\n{edge['properties']['pvalue']}"
131
+ if edge['properties'].get('color', None) is not None:
132
+ color = edge['properties']['color']
133
+ # create the edge object
134
+ self.dot.edge( edge['source'], edge['target'],
135
+ arrowtail=arrowtail,
136
+ arrowhead=arrowhead,
137
+ dir='both',
138
+ label=label,
139
+ color=color,)
140
+ #**edge_attr)
141
+
142
+
143
+ pass
144
+
145
+ # render
146
+
147
+ print(self.dot.source)
148
+
149
+ # save gv source
150
+ self.gv_source = self.dot.source
151
+
152
+ self.dot.format = 'png'
153
+ self.dot.render(filename = 'dgflex',
154
+ format='png',
155
+
156
+ )
157
+ pass
158
+
159
+ def modify_existing_edge(self, dot, from_node, to_node, **kwargs):
160
+ """Modifies the attributes of an existing edge in a Graphviz graph.
161
+
162
+ Args:
163
+ dot: The Graphviz Graph object.
164
+ from_node: The name of the starting node of the edge.
165
+ to_node: The name of the ending node of the edge.
166
+ **kwargs: The attributes to modify (e.g., color='blue', style='dotted').
167
+ """
168
+
169
+ for edge in dot.body:
170
+ if edge.tail[0] == from_node and edge.head[0] == to_node:
171
+ for key, value in kwargs.items():
172
+ edge.attr[key] = value
173
+ return # Exit after modifying the edge
174
+
175
+ print(f"Edge from '{from_node}' to '{to_node}' not found.")
176
+
177
+ if __name__ == "__main__":
178
+
179
+ # provide a description of the program with format control
180
+ description = textwrap.dedent('''\
181
+
182
+ Class to support directed graph display in support of causal structure analysis.
183
+
184
+
185
+ ''')
186
+
187
+ parser = argparse.ArgumentParser(
188
+ description=description, formatter_class=argparse.RawTextHelpFormatter)
189
+
190
+ # handle a single file on command line argument
191
+ parser.add_argument('file', type=str, help='input file')
192
+
193
+
194
+
195
+ parser.add_argument("--cmd", type = str,
196
+ help="cmd - [plot], default plot",
197
+ default = 'plot')
198
+
199
+ parser.add_argument("-H", "--history", action="store_true", help="Show program history")
200
+
201
+ # parser.add_argument("--quiet", help="Don't output results to console, default false",
202
+ # default=False, action = "store_true")
203
+
204
+ parser.add_argument("--verbose", type=int, help="verbose level default 2",
205
+ default=2)
206
+
207
+ parser.add_argument('-V', '--version', action='version', version=f'%(prog)s {__version__}')
208
+
209
+ args = parser.parse_args()
210
+
211
+ if args.history:
212
+ print(f"{os.path.basename(__file__) } Version: {__version__}")
213
+ print(version_history)
214
+ exit(0)
215
+
216
+ obj = DgraphFlex( yamlpath = args.file, verbose = args.verbose)
217
+
218
+ obj.cmd('plot')
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Kelvin O. Lim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.2
2
+ Name: dgraph_flex
3
+ Version: 0.1.0
4
+ Summary: A package for working with directed graphs
5
+ Author-email: "Kelvin O. Lim" <lim.kelvino@gmail.com>
6
+ Project-URL: Homepage, https://github.com/kelvinlim/dgraph_flex
7
+ Project-URL: Bug Tracker, https://github.com/kelvinlim/dgraph_flex/issues
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: graphviz
15
+ Requires-Dist: pyaml
16
+ Requires-Dist: matplotlib
17
+
18
+ # dgraph_flex
19
+
20
+ Package to support flexible storage of directed graphs, specifically for the support of
21
+ directed graphs and causal structure analysis.
22
+
23
+ ## unit tests
24
+
25
+ ```
26
+ python -m unittest tests/*.py
27
+ ```
28
+
29
+ ## build
30
+
31
+ ```
32
+ python -m build
33
+
34
+ # upload
35
+ twine upload dist/*
36
+
37
+ ```
38
+
39
+ ## sample usage
40
+
41
+ Here is a sample yaml file describing a graph
42
+ ```yaml
43
+
44
+ GENERAL:
45
+ version: 1.0
46
+ framework: dgraph_flex
47
+
48
+ GRAPHS:
49
+ - name: graph1
50
+ edges:
51
+ - label: edge1
52
+ source: A
53
+ target: B
54
+ edge_type: -->
55
+ properties:
56
+ strength: 0.5
57
+ pvalue: 0.01
58
+ color: green
59
+ - label: edge2
60
+ source: B
61
+ target: C
62
+ edge_type: -->
63
+ properties:
64
+ strength: -0.5
65
+ pvalue: 0.001
66
+ color: red
67
+ - label: edge3
68
+ source: C
69
+ target: E
70
+ edge_type: o->
71
+ properties:
72
+ strength: 0.5
73
+ pvalue: 0.0001
74
+ - label: edge4
75
+ source: B
76
+ target: D
77
+ edge_type: o-o
78
+ properties:
79
+
80
+ ```
81
+ Here is python code that reads in the graph and outputs a png
82
+
83
+ ```python
84
+
85
+ from dgraph_flex import DgraphFlex
86
+
87
+ obj = DgraphFlex(yamlpath='graph_sample.yaml')
88
+ obj.cmd('plot')
89
+
90
+
91
+
92
+ ```
@@ -0,0 +1,7 @@
1
+ dgraph_flex/__init__.py,sha256=eSHOSOCMDNA9Ua9MVwneyiLt26WmCXeOsD-gBeoBtH0,66
2
+ dgraph_flex/dgraph_flex.py,sha256=BuOEIjvT2sGG0a1MlPmAy_KeBJOMl9JXFCVLvu5zhdc,6808
3
+ dgraph_flex-0.1.0.dist-info/LICENSE,sha256=ODYZfsol95LsdE8oetDplmT53-mpZ42Cbg5wIGMYpm0,1069
4
+ dgraph_flex-0.1.0.dist-info/METADATA,sha256=IbfnFFuHK1eQXy5q0uAduIziNdWIx9GNBa3TuB_tK6w,1807
5
+ dgraph_flex-0.1.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
6
+ dgraph_flex-0.1.0.dist-info/top_level.txt,sha256=P0o3hBJQevidvMJDvLOxjSwXiqC_sXJ7ntqRCOZpEaY,12
7
+ dgraph_flex-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ dgraph_flex