Saravanan666/pypi-org huggingface dataset:
Package: graphpatch
graphpatchgraphpatchis a library for activation patching onPyTorchneural network models. You use it by first wrapping your model in aPatchableGraphand then running
operations in a context created byPatchableGraph.patch():model = GPT2LMHeadModel.from_pretrained(
   "gpt2-xl",
   device_map="auto",
   load_in_8bit=True,
   torch_dtype=torch.float16
)
tokenizer = AutoTokenizer.from_pretrained("gpt2-xl")
inputs = tokenizer(
   "The Eiffel Tower, located in", return_tensors="pt", padding=False
).to(torch.device("cuda"))
# Note that all arguments after the first are forwarded as example inputs
# to the model during compilation; use_cache and return_dict are arguments
# to GPT2LMHeadModel, not graphpatch-specific.
pg = PatchableGraph(model, **inputs, use_cache=False, return_dict=False)
# Applies two patches to the multiplication result within the activation function
# of the MLP in the 18th transformer layer. ProbePatch records the last observed value
# at the given node, while ZeroPatch zeroes out the value seen by downstream computations.
with pg.patch("transformer.h_17.mlp.act.mul_3": [probe := ProbePatch(), ZeroPatch()]):
   output = pg(**inputs)
# Patches are applied in order. probe.activation holds the value prior
# to ZeroPatch zeroing it out.
print(probe.activation)graphpatchcan patch (or record) any intermediate Tensor value without manual modification of the
underlying model’s code. See full documentationhere.Requirementsgraphpatchrequirestorch>=2as it usestorch.compile()to build the
computational graph it uses for activation patching. As oftorch>=2.1.0,
Python 3.8–3.11 are supported.torch==2.0.*do not support compilation on Python 3.11; you
will get an exception if you try to usegraphpatchon such a configuration.graphpatchautomatically supports models loaded with features supplied byaccelerateandbitsandbytes. For example, you can easily usegraphpatchon multiple GPU's and with quantized
inference:model = LlamaForCausalLM.from_pretrained(
   model_path, device_map="auto", load_in_8bit=True, torch_dtype=torch.float16
)
pg = PatchableGraph(model, **example_inputs)Installationgraphpatchis available onPyPI, and can be installed viapip:pip install graphpatchOptionally, you can installgraphpatchwith the "transformers" extra to select known compatible versions oftransformers,accelerate,bitsandbytes, and miscellaneous optional requirements of these packages to quickly get started with multi-GPU and quantized inference on real-world models:pip install graphpatch[transformers]DemosSee thedemosfor some practical usage examples.DocumentationSee the full documentation onRead the Docs.
Package: graphpca
Produces a low-dimensional representation of the input graph.Calculates the ECTD[1]of the graph and reduces its dimension using PCA. The
result is an embedding of the graph nodes as vectors in a low-dimensional
space.Graph data in this repository is courtesy of the mind-blowingly coolUniversity of Florida Sparse Matrix Collection.Python 3.x and 2.6+.UsageDraw a graph, including edges, from a mat file>>> import scipy.io
>>> import networkx as nx
>>> import graphpca
>>> mat = scipy.io.loadmat('test/bcspwr01.mat')
>>> A = mat['Problem'][0][0][1].todense()  # that's just how the file came
>>> G = nx.from_numpy_matrix(A)
>>> graphpca.draw_graph(G)Get a 2D PCA of a high-dimensional graph and plot it.>>> import networkx as nx
>>> import graphpca
>>> g = nx.erdos_renyi_graph(1000, 0.2)
>>> g_2 = graphpca.reduce_graph(g, 2)
>>> graphca.plot_2d(g_2)ContributingIssues and Pull requests are very welcome! [On GitHub](https://github.com/brandones/graphpca).[1]https://www.info.ucl.ac.be/~pdupont/pdupont/pdf/ecml04.pdf
Package: graph-pes
graph-pes- Potential Energy Surfaces on Graphsgraph-pesis a Python framework for training Potential Energy Surface (PES)
models that operate on graph representations of atomic structures.
Under-the-hood, this relies on Pytorch/Geometric for efficient tensor operations.Batteries are included:easy data manipulations: see docs relating toAtomicGraph, intuitive batching, easy conversion from ase etc.easy construction of PES models: implementpredict_local_energies, easy to save, load and shareuseful primitives: PerSpeciesParametereasy training: forces, energies, well conditioned losses etc.Installationpipinstallgraph-pesMinimal examplefromgraph_pesimportGraphPESModelfromgraph_pes.dataimportconvert_to_graphs,AtomicGraphfromgraph_pes.trainingimporttrain_modelfromase.ioimportreadimporttorch# 1. define a modelclassLennardJones(GraphPES):def__init__(self):super().__init__()self.sigma=nn.Parameter(torch.tensor(1.0))self.epsilon=nn.Parameter(torch.tensor(1.0))defpredict_local_energies(self,graph:AtomicGraph)->torch.Tensor:central_atoms,neighbours=graph.neighbour_indexdistances=graph.neighbour_distances# calculate pairwise interactionsx=(self.sigma/distances)**6pairwise_interaction=4*self.epsilon*(x**2-x)# sum over neighbours to get per-atom contributionsreturntorch.scatter_add(torch.zeros(graph.n_atoms,device=graph.device),central_atoms,pairwise_interaction)# 2. load some structuresstructures=read('structures.xyz',index=':10')# 3. convert to graphs (e.g. using a radius cutoff)graphs=convert_to_graphs(structures,cutoff=5.0)# 4. train the modelmodel=LennardJones()train_model(model,graphs,max_epochs=100)
Package: graphpipe
GraphPipe for pythonGraphPipe for python consists of the flatbuffer implementation (generated from
thegraphpipe project), utilities for
converting between flatbuffers and python types, a client for making calls
to graphpipe services, and some simple examples.To learn more about GraphPipe, see ourdocumentationBuildYou can install from pypi like so:pip install graphpipeYou an also install directly from github with pip like so:pip install git+https://github.com/oracle/graphpipe-pyThis is a pure python package, your setup.py knowledge should do the trick
if you are have checked out the code from github.DevelopThe tox tests can be run viamake testif you have docker installed.To update the graphpipe flatbuffer files, you will need tomake pythonin
the graphpipe project and copy the generated files into this repository'sgraphpipe/graphpipefb/directoryTo build installation packages:python setup.py sdist bdist_wheel
Package: graphpipe-tf
GraphPipe helpers for TensorFlowThis package contains helpers and examples for using GraphPipe with tensorflow.
It contains a new plug-in operation for tensorflow that makes a call to a
GraphPipe remote model from within a local tensorflow graph.  The new operation
is called remote_op and communicates with the remote model using libcurl and
the GraphPipe protocol.Additionaly, a new keras layer is included based on the remote operation.  This
allows you to include a layer in a keras model that makes a remote call.Finally, various examples are included of serving tensorflow models in python.
For production, a more performant server likegraphpipe-tfis
recommended, but the python server is useful for experimentation.List Of ExamplesJupyter Notebook: serving and querying VGG with
GraphPipeComplete client/server exampleSimple tensorflow model serverKeras to GraphDefUsing a remote operationTensorflow graph to GraphDefBuildBuilding manually requires a few libraries to be installed, but the Makefile
will happily run a build for you in a docker container.make buildSeebuild_linux.shfor the additional headers besides libcurl that you will
need to build the C library. (From tensorflow and flatbuffers)If you've successfully built the C library, to build installation packages:python setup.py bdist_wheelNote that these are not manylinux wheels and depend on libcurl being installed
Package: graphPlot
graphPlotA python module for plotting (directed) Graphs using a simulation of springs
and charged particlesSee thedocsfor more info includingmathematical explanation,examples, andclass definitions.You can import this module with PIP.$python3-mpipinstallgraphPlot--upgradeTODO:Upgrade to "second order backwards" approximation inSpringBoardadd smart detect of max size for animationChange_increment()to use matrix operationsadd fixed node capabilitiesGravitational force is just to take care of disconnected graphs - is it necessary?Make normalization "less invasive"CythonizeIntegrate planarity testsAdd add self loop arrowsAdd curved arrowsAdd copy constructorsAdd__eq__s for other classesAdd__repr__s for other classesCheck if the check in move() is most effective
Package: graph-polisher
graph-polisher[[TOC]]Graph polisher is a library that helps you clean your plotly figures.
This library was inspired by the book "Storytelling with Data by Cole
Nussbaumer Knaflic (https://www.kobo.com/us/en/ebook/storytelling-with-data).UsageTo start our graph polishing, we will create a basic bar graph:importpandasaspdimportplotly.expressaspxreport_data=[{'name':'Time Sheets','exported':394},{'name':'Schedules','exported':171},{'name':'overtime','exported':457},{'name':'Time-off','exported':93},{'name':'Shift Requests','exported':30},]df=pd.DataFrame(report_data)fig=px.bar(df,title='Exported Reports',x='name',y='exported')fig.show()Cleaning the GraphNext, we will remove all the unnecessary information from the graph. By removing
unnecessary things from the graph, we will then be able to focus on important
information that will help us drive the user to where we want them to focus on.To remove all that default unnecessary information with graph-polisher
do the following:Remove grid lines and backgroundGrid lines usually compete with the information being shown. If you really think
that you should include them, make them thin and grey so it doesn't call
attention.importgraph_polishergraph_polisher.remove_grids(figure=fig)graph_polisher.remove_background(figure=fig)fig.show()Send to backgroundThe dark colors (black text, bold text) of the graph also calls for attention.
We can easily make them less attention grabbing by sending them to
the background. Sending them to the background will set the text color to a more neutral
color like grey.graph_polisher.send_to_background(fig)fig.show()Notice the difference between the default bar graph and our new version.Default Bar PlotNo Distractions Bar PlotNow you have a graph that you can easily add intentional attention grabbing
information so that your user is guided through the information you are trying
to present.Deploying pip libraryBuild the pip library package to deploy to pip:python3setup.pysdistbdist_wheelPublish to pip. You can follow stepshereNote that you will need to install twine and register your pypi. Usually in the file~/.pypircpython3-mtwineupload--repositorypypidist/*Installationpipinstallgraph-polisherTestingTo test this project run:pytestNotebook Example (with unnotebook)Prerequisite:https://www.docker.com/You can use this to see how the library modifies the plots. We are usingunnotebookto plot the examples.Build and pushnotebookimage:dockerbuild.-tgraph-polisherRun notebookdocker-composeupnotebookordockerrun--rm-it\-v/Users/rigo/Documents/Projects/notebooks/stock-predictions:/notebooks\-p8899:8899uncluttererOpenhttp://localhost:8899/and open the notebook you want to run.
Package: graphpro
GraphProGraphPro is a versatile and pluggable OO python library designed for leveraging deep graph learning representations to gain insights into structural proteins and their conformations. With its wide range of functionalities, we provide a comprehensive framework for researchers and practitioners to explore and analyze complex protein structures.GraphPro harnesses the power of deep learning techniques specifically tailored for graph data, enabling users to capture and model intricate relationships within protein structures. By representing proteins as graphs, where nodes correspond to atoms and edges denote pairwise interactions, DeepGraph facilitates the extraction of valuable structural information.One of the key advantages of GraphPro is its pluggable nature, which allows users to seamlessly integrate different components and modules. This flexibility empowers researchers to experiment with various deep learning architectures, graph neural networks, and graph representation learning methods. Users can easily customize and combine these modules to fit their specific research needs and optimize their analyses.InstallationUsing pip:pip install graphproDocumentationYou can access the documentation of this packages under the following link:Read the docsHow to citeFernandez. P, Dantu, S.C, Pandini. A. "GraphPro: a python framework for protein deep geometrical learning". 2023
Package: graph-progression
ProgressionCreate a progression of recommendations from a user-supplied recommender. For more info, see ourofficial docsGeneralThis package was made for a specific use-case but should work with anycontent-basedrecommendation engine and possibly user-based recommenders.The initial use case was to create a visual progression of artwork recommendations. This was done to create interesting collections of fine artworks powered by our computer vision recommendation engine.To see an example, see oursamples.QuickstartInstallpip install graph-progressionImplementProgession has a full sample set to show the functionality of the package w/o the need of a recommender.fromgraph_progressionimportDFSProgressor,random_walkprogressor=DFSProgressor()progressor.create_progression(0,random_walk,progression_length=3)# [0, 8114, 9353]progressor.graph# {# 0: [8114, 5298, 2050, 4837, 1376, 2924, 8689, 8000, 2171, 3246],# 8114: [9353, 8647, 8768, 8391, 8555, 8879, 9102, 9481, 9282, 8142]# }As you can see, progession generates "recommendations" at each step, uses them to populate a graph (for memoization), and then continues on. Not shown here, but it also has the intelligence to backtrack using the graph if it ends a recommendation (node) with no recommedations (edges).FeaturesRecommendation progression via sequential depth-first searchMemoizationFlexible API that can take as inputs:Starter graphRecommendation algorithmPost recommendation filtersSelection algorithmProgession lengthCreditsThis package was created withCookiecutterand themgancita/cookiecutter-pypackageproject template.
Package: graphpy
A Python implementation of edges, vertices, and graphsUseThere are two types of each object:UndirectedandDirected.To begin, import one of the graph classes:from graphpy.graph import UndirectedGraphand create a graph from a dictionary of vertex vals:# graph with vertices 'v0' and 'v1', with an edge between them

g = UndirectedGraph.from_dict({'v0': [('v1',)],
                               'v1': []})or from a list of vertices and a list of edges:g = UndirectedGraph.from_lists([('v0',), ('v1',)],
                               [('v0', 'v1')])You can also initialize a graph, then add vertices and edges:g = UndirectedGraph()

g.add_vertex('v0')
g.add_vertex('v1')
g.add_edge(('v0', 'v1'))A vertex’s val can be any hashable object, like a string, int, tuple, etc.:# graph with vertices 'v0', 1, and (2, 2), with some edges

g = UndirectedGraph.from_dict({'v0': [(1,)],
                               1: [('v0',), ((2, 2),)],
                               (2, 2): [(1,)]})Retrieve vertex and edge objects:# v is an UndirectedVertex object, and e is an UndirectedEdge object

v = g.get_vertex('v0')
print v.degree

e = g.get_edge(('v0', 'v1'))
print e.verticesIterate through a graph’s vertices:for v in g:
    print vPerform graph algorithms, such as search:paths = g.search(start='v0', method='depth_first')
print pathsCreate graphs with vertices and edges that have whatever attributes you want (for example, edge weights):g = UndirectedGraph.from_lists([('v0', {'city': 'Paris'}), ('v1', {'city': 'London'})],
                               [('v0', 'v1', {'weight': 5})])>From there, use graphs to model situations, implement more graph algorithms, and whatever else you desire. And, as always, have fun!(The tests found on Github athttps://github.com/tscizzle/graphpy/tree/master/testsgive many more examples and showcase the rest of the library’s functionality.)DocumentationFind the full documentation at:http://graphpy.readthedocs.org/en/latestInstallationIf you don’t have pip, get pip at:https://pip.pypa.io/en/stable/installingRun the commandpip install graphpyin your terminal to get the graphpy library.To test your installation, start a Python interpreter with thepythoncommand in your terminal and make sure you can runimport graphpyin it without getting an error.ContributeFind the code on Github at:https://github.com/tscizzle/graphpySupportContact me (Tyler Singer-Clark) attscizzle@gmail.comwith any questions or concerns.LicenseThe project is licensed under the MIT license.
Package: graphpython
graphpyThis is a package for the manipulation of graphs
made for a class of graphs in the Brazilian university 'Universidade Tecnologica Federal do Paraná'Installationpip install graphpythonComplete DocumentationGraphto use this class, the main element isGraph class. With this class, you will be able to fill the graph with vertex and edges and do all the necessary operationsGraph([directed]): create a graphdirected: Defaults to False.
tells if the graph is directed or notCode example# Create a new graphfromgraphpy.graphimportGraphgp=Graph()# add a new vertexgp.add_vertex('vertex1')# to get the create vertex, you can use the [] operatorvertex1=gp['vertex1']Vertex operationsThe base of all graph is the vertex, to create a new vertex you got to use the follow functionsgp.add_vertex(name, [value]): create a new vertex and insert to the graphname: Unique identification to the vertex inside the graphvalue: optional value to the vertexgp.get_vertex(name)orgp[name]: return the vertex from the graphname: Unique identification to the vertex inside the graphgp.get_all_vertex(): get a list with all vertex from the graphgp.adjacents_vertex(vtx): get all adjacent vertex from one vertexvtx: vertex you want to know the adjacentgp.remove_vertex(vertex_to_remove): Remove a vertex and all the connections he havevertex_to_remove: vertex you want to removeCode examplefromgraphpy.graphimportGraphgp=Graph()gp.add_vertex('01')gp.remove_vertex(gp['01'])Search in the graphThe main class has a search method and to use, you need to pass a by params an strategy to make the search.Implement a new search strategyIn the class has two class strategies already implemented:BFSstrategyDFSstrategyfromgraphpy.graphimportGraphfromgraphpy.BFSstrategyimportBFSstrategygraph=Graph()graph.search(BFSstrategy(INITIAL_VERTEX))To extend all the search types you can create a new strategy extending the SearchStrategy class from search_strategy.fromgraphpy.search_strategyimportSearchStrategyclassDFSstrategy(SearchStrategy):def__init__(self):self.__predecessors={}self.__firstSee={}self.__close={}self.__time=0def__dfs_visit(self,vertex):self.__time=self.__time+1self.__firstSee[vertex]=self.__timevertex.set_color(1)foradjacentinself.get_adjacent_list()[vertex]:ifadjacent.get_color()==0:self.__predecessors[adjacent]=vertexself.__dfs_visit(adjacent)vertex.set_color(2)self.__time+=1self.__close[vertex]=self.__timedefsearch(self):# colors:#   white: not visited#   grey: in the queue#   black: nothing more to doforkeyinself.get_adjacent_list():# set color for all vertices to whitekey.set_color(0)self.__predecessors[key]=Noneself.__time=0forkeyinself.get_adjacent_list():ifkey.get_color()==0:self.__dfs_visit(key)returnself.__firstSee,self.__close,self.__predecessors
Package: graphql2python
GRAPHQL2PYTHONgraphql2pythonis a tool that generates python code out of your GraphQL schema.
If you are using python as GraphQL client you can to generate
pydantic data-model withgraphql2python. The documentation forgraphql2pythoncan be found athttps://denisart.github.io/graphql2python.GraphQL query generation moved tohttps://github.com/denisart/graphql-queryThe special example forgqlusershere.QuickstartInstall with pippipinstallgraphql2pythonCreate the following file# graphql2python.yamlschema:./schema.graphqloutput:./model.pyand run the following commandgraphql2pythonrender--config./graphql2python.yamlConfig referenceGlobal keywordskeyworddescriptionschemaA path to the target GraphQL schema file.outputA file name for outputpyfile.license_fileAn optional path to a file with license for outputpyfile.optionsOptional options for render of outputpyfile.Options keywordskeywordsdescriptionmax_line_lenThe maximum of line length of outputpyfile. Default is120.name_suffixA suffix for invalid field name (as python object name). Default is"_".each_field_optionalEach fields of interfaces and objects are optional. Default isfalse.add_from_dictAddfrom_dict(dict -> model) method to the general class. Default isfalse.add_to_dictAddto_dict(model -> dict) method to the general class. Default isfalse.scalar_pytypesA dict with python types for custom GraphQL scalars. Maps from scalar name to python type name. Default is empty dict.fields_settingSettings for interfaces or objects fields. Maps from object name to a dict with setting. Default is empty dict.fields_settingkeywords for some object namekeywordsdesciptionaliasAn alias for a field (see Field.alias for pydantic). Default is null.new_nameA new name for a field. Default is null.An example forgraphql2python.yamlconfig:# graphql2python.yamlschema:./schema/schema.graphqloutput:./model/model.pylicense_file:./LICENSEoptions:scalar_pytypes:String:strFloat:floatInt:intID:strBoolean:boolDateTime:datetimeDate:datemax_line_len:79each_field_optional:truefields_setting:MyObjectName:from:alias:fromnew_name:correct_from
Package: graphql-adapter
GraphQL AdapterThegraphql_adaptermodule is a Python package that simplifies interactions with GraphQL servers. It abstracts away some of the pain points of using Python with GraphQL by providing a streamlined, asynchronous interface for sending GraphQL queries and mutations.Installationpip install graphql-adapterUsageThegraphql_adaptermodule exports a single async functiongraphql_request.Here's an example of how to use it:fromgraphql_adapterimportgraphql_request# A simple example queryquery="""query {test {field1field2}}"""variables={"key1":"value1","key2":"value2"}response=awaitgraphql_request(query=query,variables=variables,graphql_server="http://localhost:4000/graphql",query_path="./gql")print(response)Function Parametersquery: The name of the GraphQL query or mutation. This should match the name of a.gqlfile in yourquery_pathdirectory.variables: A dictionary of variables to pass to the GraphQL query or mutation.graphql_server: The URL of your GraphQL server.headers(optional): A dictionary of headers to include in the request. Default is an empty dictionary.query_path(optional): The relative path to the directory containing your.gqlfiles. Default is./gql.Return ValuesThe function will return the data from the GraphQL server's response. This data is processed as follows:If the server returns an error, the function will raise an exception.If the query was a mutation and the data contains areturningfield, the function will return the value of thereturningfield.If the data is a list, the function will return the first item in the list.If the data is a dictionary with only one item, the function will return that item.Please note that due to the async nature of the function, you shouldawaitthe function call to get the response.
Package: graphql-api
GraphQL-APIFramework for building a GraphQL API with PythonInstallationPippip install graphql-apiRun the Unit TestsTo run the tests.pip install pipenv
pipenv install --dev
pipenv run python -m pytest tests --cov=graphql_apiDocsThe documentation is public, and is generated using Sphinx.GraphQL-API DocumentationBuild documentationTo build a local static HTML version of the documentation.pip install pipenv
pipenv install sphinx
pipenv run sphinx-build docs ./public -b htmlSimple Examplefromgraphql_apiimportGraphQLAPIapi=GraphQLAPI()@api.type(root=True)classMathService:@api.fielddefis_odd(self,number:int)->str:return"No"if(num%2)else"Yes"query='''query {isOdd(number: 5)}'''result=api.executor().execute(query)print(result.data)$ python example.py
>>> {'isOdd': 'No'}