def getConnection(): try: conn = tg.TigerGraphConnection(host=hostname, graphname=graphname, username=username, password=password, useCert=False, version='3.0.5', dev=True) #usercert=false secret = None #conn.createSecret() token = None return conn except Exception as e: print(e) print('There was an error. Make sure to start your box and try again')
""" Unit tests for pyTigerGraph getStatistics, runInterpretedQuery, getInstalledQueries, runInstalledQuery """ import main import pyTigerGraph as tg from connection import config conn = tg.TigerGraphConnection(host=config["host"], username="******", gsqlVersion="3.0.5", password=config["password"], useCert=True) class Testmain: def test_get_statistics(self): conn.gsql(''' CREATE VERTEX Test (PRIMARY_ID id STRING) WITH primary_id_as_attribute="true" ''', options=[]) conn.gsql('''CREATE GRAPH TestGraph(Test)''', options=[]) conn.graphname = "TestGraph" conn.apiToken = conn.getToken(conn.createSecret()) val = conn.getStatistics() # Drops the graph created conn.gsql(''' USE GRAPH TestGraph DROP VERTEX Test DROP GRAPH TestGraph ''') # Assert assert val == {}
else: graphName = args.graphName maxClients = args.maxClients numTargetPatients = args.numTargetPatients numDevices = args.numDevices verbose = args.verbose if args.dataSource is None: dataSource = dataLocation + "/" + str(populationSize) + "_patients/csv" else: dataSource = args.dataSource print(f'INFO: Running queries as {userName}') # connect to TG server conn = tg.TigerGraphConnection(host='http://' + hostName, graphname=graphName, username=userName, password=passWord) # initialize the graph, load queries, # cache SW vectors in vertices and Load FPGA memories # should be needed only once if not args.noInitGraph: print(f'INFO: Data size: Total {populationSize} Patients') print(f'INFO: Creating graph {graphName}...') cmd = [ initGraphScript, "-u " + userName, "-p " + passWord, "-g " + graphName, "-s " + dataSource ] tStart = time.perf_counter() sp.run(cmd) print(
def get_data(): try: graph = tg.TigerGraphConnection( host="https://synthea.i.tgcloud.io", graphname="MedGraph", apiToken="0g18ehjsq00pkcke6m0pc673o7rjalfs") selectAll = graph.runInstalledQuery("grab_All_3d_demo", sizeLimit=40000000) patients = selectAll[0]['data'] other = selectAll[1]['other'] edges = selectAll[2]['@@edgeList'] nodes = [] links = [] for i in range(len(patients)): patient_last = patients[i]['attributes']['lastName'] patient_first = patients[i]['attributes']['firstName'] nodes.append({ "id": patients[i]['attributes']['patient_id'], "description": "Patient Name: " + patient_first + " " + patient_last, "group": 0 }) for i in range(len(other)): if other[i]['v_type'] == 'Address': nodes.append({ "id": other[i]['v_id'], "description": "Address: " + other[i]['v_id'], "group": 4 }) elif other[i]['v_type'] == 'ImagingStudies': nodes.append({ "id": other[i]['v_id'], "description": "Imaging: " + other[i]['attributes']['bodySiteDescription'] + ", " + other[i]['attributes']['modalityDescription'], "group": 8 }) elif other[i]['v_type'] == 'Allergies': nodes.append({ "id": other[i]['v_id'], "description": other[i]['attributes']['description'], "group": 9 }) for i in range(len(edges)): if edges[i]['to_type'] == "Address": links.append({ "source": edges[i]['from_id'], "target": edges[i]['to_id'], "group": 15 }) if edges[i]['to_type'] == "Allergies": links.append({ "source": edges[i]['from_id'], "target": edges[i]['to_id'], "group": 16 }) if edges[i]['to_type'] == "ImagingStudies": links.append({ "source": edges[i]['from_id'], "target": edges[i]['to_id'], "group": 16 }) data = {"nodes": nodes, "links": links} response = jsonify(data) return response except Exception as ex: response = jsonify({"Message": str(ex)}) return response
''' Create Graph + Queries ''' import pyTigerGraph as tg conn = tg.TigerGraphConnection(host="https://discord.i.tgcloud.io", password="******", gsqlVersion="3.0.5", useCert=True) # print(conn.gsql('''DROP ALL''', options=[])) print(conn.gsql(''' CREATE VERTEX Message (PRIMARY_ID message_id STRING, message_content STRING) WITH primary_id_as_attribute="true" CREATE VERTEX Channel (PRIMARY_ID channel_id STRING, channel_name STRING) WITH primary_id_as_attribute="true" CREATE VERTEX Category (PRIMARY_ID category_id STRING, category_name STRING) WITH primary_id_as_attribute="true" CREATE VERTEX User (PRIMARY_ID id STRING, username STRING, avatar STRING, discriminator STRING) WITH primary_id_as_attribute="true" CREATE VERTEX Year (PRIMARY_ID year STRING) WITH primary_id_as_attribute="true" CREATE VERTEX Month (PRIMARY_ID month STRING) WITH primary_id_as_attribute="true" CREATE VERTEX Day (PRIMARY_ID day STRING) WITH primary_id_as_attribute="true" CREATE UNDIRECTED EDGE CHANNEL_CATEGORY (FROM Channel, TO Category) CREATE UNDIRECTED EDGE SENDER (FROM Message, TO User) CREATE UNDIRECTED EDGE MENTIONS (FROM Message, TO User) CREATE UNDIRECTED EDGE MESSAGE_CHANNEL (FROM Message, TO Channel) CREATE UNDIRECTED EDGE MESSAGE_YEAR (FROM Message, TO Year) CREATE UNDIRECTED EDGE MESSAGE_MONTH (FROM Message, TO Month) CREATE UNDIRECTED EDGE MESSAGE_DAY (FROM Message, TO Day) CREATE UNDIRECTED EDGE USER_YEAR (FROM User, TO Year) CREATE UNDIRECTED EDGE USER_MONTH (FROM User, TO Month)
# Grab text file and read in data with open ('streamlit.txt', 'r') as file: x = file.read().split(' ') print(x) host = x[0] username = x[1] password = x[2] graphname = x[3] cert = False if x[4] == 'True': cert = True # Connect to graph, run query graph = tg.TigerGraphConnection(host=host, username=username, graphname=graphname, password=password, useCert=cert) API_Secret = graph.createSecret() API_Token = graph.getToken(API_Secret, setToken=True, lifetime=None)[0] results = graph.runInstalledQuery("streamlit") df = pd.DataFrame(results[0]["s2"]) data = flat_table.normalize(df) data = data[['v_id', 'attributes.Age', 'attributes.Sex', 'attributes.Location.latitude', 'attributes.Location.longitude']] # Filtering the data based on the sex filter input if(len(sex)==1): data = data[data['attributes.Sex']==sex[0]] data = data[data['attributes.Age'].between(left=min_age, right=max_age)]
server="hub.graphistry.com", username="******", password="******") # In[3]: import pyTigerGraph as tg TG_HOST = "https://halal.i.tgcloud.io" TG_USERNAME = "******" TG_PASSWORD = "******" TG_GRAPH = "halal" TG_SECRET = "gh9urnvt8aa0hk2tppic1r9vck0jmumj" conn = tg.TigerGraphConnection(host=TG_HOST, graphname=TG_GRAPH, username=TG_USERNAME, password=TG_PASSWORD) print(conn.getToken(TG_SECRET, "1000000")) #uses a lifetime of 1,000,000 seconds # In[ ]: query = "ProductManufactureLink" resultTG = conn.runInstalledQuery(query) results = resultTG[0]['@@tupleRecords'] ProdMan = pd.DataFrame(results) # In[ ]: # In[ ]:
landing_page = lp.get_page() other_page = op.get_page() ''' TigerGraph Connection Parameters: ''' hostname = "dashtemplate.i.tgcloud.io" username = "******" graphname = "MyGraph" password = "******" conn = tg.TigerGraphConnection(host=hostname, graphname=graphname, username=username, password=password, useCert=True) secret = conn.createSecret() token = conn.getToken(secret, setToken=True) print(conn.gsql('ls')) ''' display_page callback: ---------------------------------------------- Output: - page-content: Corresponding page to be displayed from url. - session: Any data that needs to be stored in browser before loading.
def __init__(self, config: Config): self.conn = tg.TigerGraphConnection(host=config.tg_host, graphname=config.tg_graph, username=config.tg_username, password=config.tg_password, apiToken=config.tg_api_key)
import pyTigerGraph as tg #######################################"" configs = { "host": "https://<your_box>.i.tgcloud.io", "password": "******", "graphname": "<your_graph>", "secret": "<your_secret>" } #######################################" conn = tg.TigerGraphConnection(host=configs['host'], password=configs['password'], gsqlVersion="3.0.5", useCert=True, graphname=configs['graphname']) conn.apiToken = conn.getToken(configs['secret']) conn.gsql("USE graph {}".format(configs['graphname'])) #######################################" def nlu_md(): res = conn.gsql("SELECT type,intent,value FROM nlu LIMIT 100") intent = "" nlus = {} order = [] for element in res: order.append(element["v_id"]) order = sorted([int(x) for x in order]) for element in order: for e in res:
import dash_html_components as html import dash_bootstrap_components as dbc from dash.dependencies import Input, Output import dash_table from collections import defaultdict import plotly.express as px import plotly.graph_objects as go import pyTigerGraph as tg import pandas as pd import flat_table # Create connection to TG Cloud graph = tg.TigerGraphConnection( host="https://61af4f31021c449e85f690cbec28ef7a.i.tgcloud.io", graphname="MyGraph", apiToken="r72kccg1jaso02s8gn20fskgfnh7brim" ) # Query to grab all authors, publication doi, number of publications parsAuth = graph.runInstalledQuery("AuthorSearchDash", {}, timeout=20000, sizeLimit=40000000) # Query to grab publication doi, title, URL parsPubs = graph.runInstalledQuery("GrabPubs", {}, timeout=20000, sizeLimit=40000000) # Sort Publication data df_pub = pd.DataFrame(parsPubs[0]) df1_pub = flat_table.normalize(df_pub) df2_pub = df1_pub.rename(columns={'Pubs.attributes.Pubs.id': 'Doi', 'Pubs.attributes.Pubs.pub_title': 'Title', 'Pubs.attributes.Pubs.pub_url': 'URL'}) df3_pub = df2_pub[['Doi', 'Title', 'URL']]
import pyTigerGraph as tg import streamlit as st import pandas as pd import flat_table import plotly.express as px from streamlit_agraph import agraph, Config, Node, Edge import json import matplotlib.pyplot as plt import matplotlib from documentation import docs graph = tg.TigerGraphConnection( host="https://9f5d92a5037b47ea9431606ee29032a3.i.tgcloud.io", graphname="MyGraph", apiToken="jh0ppbq90n7lfdu0khe57vthv8n7eqij" ) # make a connection to TigerGraph Box authToken = graph.getToken("jh0ppbq90n7lfdu0khe57vthv8n7eqij", "100000000000000000") print(authToken) menuItems = [ 'Tiger Graph Data Analysis', 'Automatic Data Analysis', 'Documentation' ] st.sidebar.title('Easy Analysis') itemSelected = st.sidebar.selectbox('', menuItems) github = '''[ Fork/Star on Github]()''' st.sidebar.info(github) if itemSelected == 'Tiger Graph Data Analysis': st.title('Covid-19 Data Analysis')
import dgl import networkx as nx import torch from gcn import GCN import torch.nn as nn import torch.nn.functional as F import cfg numEpochs = 10 wantedTopic = "Saxophone" unwantedTopic = "Falkland_Islands" #In future, determine automatically through the inverse of PageRank/other centrality algo graph = tg.TigerGraphConnection( ipAddress="https://wikipediagraph.i.tgcloud.us", apiToken=cfg.token, graphname="WikipediaGraph") # connection to graph articleToNum = { } # translation dictionary for article name to number (for dgl) numToArticle = {} # translation dictionary for number to article name i = 0 def createEdgeList(result): # returns tuple of number version of edge global i if result["article1"] in articleToNum: fromKey = articleToNum[result["article1"]] else: articleToNum[result["article1"]] = i numToArticle[i] = result["article1"]