Given some input, find the optimal weightings for edges of a graph to maximize some output
I have a directed graph that describes the relationship between items (nodes) via recipes (edges).
Simple example of a recipe: 2 Iron Ore => 1 Iron Ingot
.
I want to find a weighting for each recipe (that is to say the number of times each recipe should be applied) such that given some starting number of items, it produces the maximum amount of a specified item.
How can I go about finding this weighting for each recipe?
Note: All weightings must be nonnegative (they can be decimal). No weightings can result in more input being required than the amount available.
That's the main problem I'm trying to solve, but following that, the next thing I want to then solve is taking energy usage into account. Each recipe will either use some amount of energy or produce some amount of energy.
How can I ensure that when finding the weightings, the energy production minus the energy consumption is nonnegative?
Thanks in advance for any advice :)
do you know?
how many words do you know
See also questions close to this topic

How to evaluate Integer Operation Per Second
I've developed a cuda algorithm for counting sort:
/** * @brief This function implement the counting sort algorithm of the array 'array'. * @param array Pointer to the array used in counting sort. * @param dim_array Size of the array 'array'. * @param counts The array containing the */ __global__ void kernelCountingSort(int *array, int dim_array, int *counts) { // define index int i = blockIdx.x * blockDim.x + threadIdx.x; // check that the thread is not out of the vector boundary if (i >= dim_array) return; int count = 0; int el = array[i]; for (int j = 0; j < dim_array; ++j) { int le = array[j]; if (le < el) count++; else if (le == el && j < i) count++; } counts[count] = el; }
I'm trying to compute the number of integer operations per second of this algorithm. Therefore, to get the total number of integer operation, I supposed that I need to count only the additions operations on
count
variable. So I build this method:int countIO(int dim_array){ int s=0; for(int i=dim_array;i>0;i) s+=i; s+=dim_array; return s; }
This method compute how much
count
variable increment occur in the algorithm, but I've a question: Do I need to include the number of increments on thej
variable in the loop, as I made here:s+=dim_array;
?Generally, is it correct the way I computed the total number of integer operation?
PS. Finally, to obtain the number of integer operations per second I going to divide total integer operation with elasped time of the algorithm, expressed in seconds.

Algorithmus (Graphen)
We are looking for an algorithm that determines the number of connected components. In addition, it should be stored for each node to which connected component it belongs.
 Which known Algorithm can be used to deal with this it as efficiently as possible? and why

Different potential function for the same problem has the same amortized or not?
If I set the potential function as 2 multiple the size of the heap.
The operation for the insert and delete operation might be both
O(logn)
.I check that the definition of the potential function that my potential function is correct.
But the answer for the problem that the insertion took
O(logn)
and the extractmin tookO(1)
.So, it's there any problem that has different potential functions result in different amortized time complexity ?
I think that maybe I set the wrong potential function.
Because I think the amortized method result the same amortized time complexity, right ?

How to create and update an item in DynamoDB?
I am trying to create an item immediately on page load and then allow the user to update that item, but I am unable to pass the data from the newly created item in the db to a button.
For example, a user navigates to a page (/park/yell) and is with a page about Yellowstone National Park. Under the hood, if the user is logged in, they can update that status of a button ("Want to Visit", "Visited").
To accomplish this feature, I am using Client Side Rendering with (SWR) with SSG in Next.js to render the pages. I chose to SSG these pages because there a possible 493 pages and the only dynamic piece is this button.
Steps taken:
 Call a fetcher function (SWR) to create a new item in the database if no object exists
const fetcher = async (owner, code) => { try { // if a site exists for the query parameter, return the first item as userData (there will only be 1 item) const {data} = await API.graphql({ query: listSites, variables: { filter: { code: {eq: code}, owner: {eq: owner}, }, }, }) const userData = data?.listSites?.items[0] // if no item in the database exists for the query paramter, create a new item with the following key value pairs if (userData == null) { const siteInfo = { id: uuidv4(), name: fullName, code: parkCode, img: url, owner: user?.username, bookmarked: false, visited: false, } // A site does not exist, create a new entry await API.graphql({ query: createSite, variables: {input: siteInfo}, authMode: 'AMAZON_COGNITO_USER_POOLS', }) console.log(`${name} added for the first time`) } return userData  null } catch (err) { console.log('Site not added by user', data, err) } } // if the user is logged in call fetcher to fetch the user's data on this particular park from the query paramter const {data, error} = useSWR( user ? [user?.username, parkCode] : null, fetcher )
 Use the data from the fetcher function to update the button state
Once a user navigates to a new park page for the first time, a site is added to the database with bookmarked and visited set to false. If a user clicks a button to update the state of the datbase, for instance change bookmarked to visited, I get an error of
data: null errorInfo: null errorType: "DynamoDB:DynamoDbException" locations: Array [ {…} ] message: "Invalid FilterExpression: Syntax error; token: \"AND\", near: \" AND (\" (Service: DynamoDb, Status Code: 400, Request ID: OPOE1M36L00M55IRGPJLSAR2RJVV4KQNSO5AEMVJF66Q9ASUAAJG, Extended Request ID: null)" path: Array [ "listSites" ]
What seems to be occuring is that from the time a user navigates to a page, the database does not reflect the changes when a user goes to click a button to update the database.
const handleDBQuery = async () =>{ await API.graphql({ query: updateSite, variables: { input: { id: data?.id, bookmarked: true, owner: user?.username, }, }, authMode: 'AMAZON_COGNITO_USER_POOLS', }) } return ( <button onClick={handleDBQuery}>Update database</button> )
This is the user flow that is causing me issues:
 User navigates to a page they have never visted (ex// /park/yell)
 Because a user is logged in and they have never visited this page, a new object with the above
siteInfo
settings is created for the first time.  The user clicks a button to change the state of the button, thus altering the database item as well. When they do this, an error is thrown saying that the id of the object they want to update is undefined.
My hunch
Because the graphQL query,
updateSite
isgenerated at build time, the result of generating a new object in the database is not reflected on an initial page visit by the user.How can I ensure that by the time a user visits a page for the first time, the button to interact with multiple key value pairs in the database is instantiated?
Here is a video of the UI and error
Notes
This error only occurs the first time a user navigates to a particular page. After the refresh the page or visit the same page again, the button to update the state works.

NetworkX Draw weighted graph from dictionary
I want to plot undirected graph with weights on edges. Here's how my data looks like:
{ "A": ["B": 2, "C": 3], "B": ["A": 2, "C": 1, "D": 1, "E": 4], "C": ["A": 3, "B": 1, "F": 5], "D": ["B": 1, "E": 1], "E": ["B": 4, "D": 1, "F": 1], "F": ["C": 5, "E": 1, "G": 1], "G": ["F": 1] }
What I have tried to plot this data:
gr = { from_: { to_: {'weight': w} for to_, w in to_nodes.items() } for from_, to_nodes in data.items() } g = nx.from_dict_of_dicts(gr, create_using=nx.DiGraph) pos = nx.spring_layout(g, k=10) nx.draw_networkx(g, arrows=False) labels = {e: g.edges[e]['weight'] for e in g.edges} nx.draw_networkx_edge_labels(g, pos, edge_labels=labels) plt.show()
After this I get graph which looks like it is drawn twice. I think the problem in using
nx.draw_networkx(g, arrows=False)
andnx.draw_networkx_edge_labels(g, pos, edge_labels=labels)
in the same time: one line gives me undirected graph with no weights and another one gives me directed with weights. But I need to get undirected graph with weights on edges... Sincenx.draw_networkx_edge_labels()
has no argument to make it undirected, I can't use just this method. But I also can't use justnx.draw_networkx()
. How can I combine this options and finally get undirected graph with weights on edges? 
How to create a graph in excel from data table in c#
I am using
EPPLUS
version(v4.0.30319) , and i have data in datatable as shown below.But i am getting error in below code forLoadFromCollection
DataTable dt = null; ExcelPackage pckGraph = null; string path = @"D:\PTP\graph\ptpgraph.xlsx"; try { dt = CreateDatatable(); var file_Summary = new FileInfo(path); if (File.Exists(path)) File.Delete(path); using (pckGraph = new ExcelPackage(file_Summary)) { ExcelWorksheet wsSummary = pckGraph.Workbook.Worksheets.Add("PTPGraph"); ExcelChart chart = wsSummary.Drawings.AddChart("chart", eChartType.ColumnClustered); chart.XAxis.Title.Text = "Months"; //give label to xaxis of chart chart.XAxis.Title.Font.Size = 10; chart.YAxis.Title.Text = "Usage(kwh)"; //give label to Yaxis of chart chart.YAxis.Title.Font.Size = 10; chart.SetSize(1200, 300); chart.SetPosition(1, 0, 5, 0); OfficeOpenXml.Table.TableStyles.Medium1); wsSummary.Cells[1, 1].LoadFromCollection(dt); } } catch (Exception ex) { } private static DataTable CreateDatatable() { DataTable dt = new DataTable(); dt.Columns.Add("Field",typeof(string)); dt.Columns.Add("Differences", typeof(string)); dt.Rows.Add(new object[] { "Remote Tx Frequency","412" }); dt.Rows.Add(new object[] { "Hub Tx Frequency", "388" }); dt.Rows.Add(new object[] { "Remote Modulation", "622" }); dt.Rows.Add(new object[] { "Remote ChannelBW", "383" }); dt.Rows.Add(new object[] { "Remote TxPower", "725" }); dt.Rows.Add(new object[] { "Hub TxPower", "681" }); dt.Rows.Add(new object[] { "Remote Ant Polarisation", "407" }); dt.Rows.Add(new object[] { "Remote Equipment Type", "449" }); dt.Rows.Add(new object[] { "Remote Equipment Vendor", "369" }); return dt; }

Given a Graph and 2 vertices u and v ,verify that each finite maximal path starting from u does not pass through v
Given a Graph and 2 vertices u and v, verify in linear time that each finite maximal path starting from u does not pass through v.
A path is said to be maximal if it cannot be further extended, so if it is infinite or ends in a well vertex
I was thinking to use a dfs to solve it, but I'm not so sure

Convert python functions (shortestpath/ prediction function using nx.adamic_adar_index) into API
So in this project im trying to find the link prediction in the social networks.
I have done my test with some of the algorithms, and I decided to work with the Adamic radar algorithm.
And I wanted to do an HTML interface to get the prediction in.
so I dunno how to convert the python function into APIs, I tried with fastApi but nothing happened.
Can you please help me?
So here is my code.
import numpy as np import random import networkx as nx from tqdm import tqdm import re import matplotlib.pyplot as plt from sklearn.metrics import roc_curve from sklearn.metrics import auc from sklearn.metrics import roc_auc_score # load nodes details with open("/content/drive/MyDrive/fbpagesfood.nodes") as f: fb_nodes = f.read().splitlines() # load edges (or links) with open("/content/drive/MyDrive/fbpagesfood.edges") as f: fb_links = f.read().splitlines() len(fb_nodes), len(fb_links) # capture nodes in 2 separate lists node_list_1 = [] node_list_2 = [] for i in tqdm(fb_links): node_list_1.append(i.split(',')[0]) node_list_2.append(i.split(',')[1]) fb_df = pd.DataFrame({'node_1': node_list_1, 'node_2': node_list_2}) # create graph G = nx.from_pandas_edgelist(fb_df, "node_1", "node_2") # plot graph plt.figure(figsize=(10,10)) pos = nx.random_layout(G, seed=23) nx.draw(G, with_labels=True, pos = pos, node_size = 280, alpha = 0.6, width = 1) from networkx.algorithms.shortest_paths.weighted import dijkstra_path def dijkstrapath(source,target): print('Returns the shortest path from source to target in a weighted graph G') if (source and target) in G: x = dijkstra_path(G , source= source, target= target, weight="weight") print(x) # else: # print('nodes are not in the graph') dij = dijkstrapath('0','54') dij # Remove 20% of the edges proportion_edges = 0.2 edge_subset = random.sample(G.edges(), int(proportion_edges * G.number_of_edges())) # Create a copy of the graph and remove the edges G_train = G.copy() G_train.remove_edges_from(edge_subset) # Prediction using Adamic Adar pred_adamic = list(nx.adamic_adar_index(G_train)) score_adamic, label_adamic = zip(*[(s, (u,v) in edge_subset) for (u,v,s) in pred_adamic]) pred_adamic*100
** so this is the function that I want to use in my HTML so I guess I need it as an API. HOW TO DO THIS . **
**BUT IF OF COURSE THERE IS ANOTHER IDEA PLEASE TELL ME, I AM A BEGINNER **
# Prediction using Adamic Adar def prediction__(u,v): if u in G and v in G: preds = nx.adamic_adar_index(G, [(u, v)]) for u, v, p in preds: print('(%d, %d) > %.8f' % (u, v, p)) else: print('nodes not found')
this what I have done in fastAPI but nothing works of course because it's wrong
from fastapi import FastAPI , Response, status from colabcode import ColabCode from pydantic import BaseModel # Modeling app = FastAPI(title="Link Prediction", description="Prediction Model of Future Connections between Facebook Pages", version="1.0") app = FastAPI() # class allNodes(BaseModel): # node1: int # node2 : int # prediction = {} @app.get("/") def read_root(): return {"Hello": "World"} # @app.get("/prediction") # async def get_prediction(Node1, Node2) > allNodes: # if Node1 and Node2 in G: # preds = nx.adamic_adar_index(G, Node1, Node2) # for Node1, Node2, p in preds: # print('(%d, %d) > %.8f' % (Node1, Node2, p)) @app.get("/shortPath") def dijkstrapath(source,target): if (source and target) in G: x = dijkstra_path(G , source= source, target= target, weight="weight") return x
THANK YOU IN ADVANCE FOR YOUR HELP

How is a cut lonely if there are often multiple edges crossing a cut in a connected undirected graph?
I'm learning the requirements for finding a minimum spanning tree for a connected, undirected graph with distinct edge costs. One of the requirements is that there must be no cycles created in the tree, and the reason given for why a cycle isn't created by, for example Prim's algorithm, is that "an edge which is the only edge crossing a cut cannot create a cycle" (Lonely cut corollary). However, when I look at a cut, I normally see multiple edges crossing the cut. They do not necessarily connect the same two vertices, but there are multiple edges nevertheless. Shouldn't the lonely cut corollary be worded as "an edge which is the only one crossing a cut and connecting two specific vertices in each set"? Or am I just misunderstanding the corollary?