-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.cpp
337 lines (299 loc) · 9.36 KB
/
graph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <unordered_map>
#include "graph.h"
#include "variable.h"
#include "function.h"
#include <queue>
#include <cmath>
#include <math.h>
#include <iterator>
#include <sstream>
#include <algorithm>
using namespace std;
template <class Container>
void split1(const string& str, Container& cont)
{
istringstream iss(str);
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(cont));
}
// helper function that checks whether the given string is number or not.
bool isNumber(const string& s)
{
char* end = 0;
double val = strtod(s.c_str(), &end);
return end != s.c_str() && val != HUGE_VAL;
}
int Graph::getVariable(string inp){
int res;
if( isNumber(inp) ){
double val = stod(inp.c_str());
idCount++;
name[idCount] = inp;
vars[idCount] = new Variable(idCount, inp, val);
res = idCount;
type[idCount] = VARIABLE;
numCount++;
vars[idCount]->initialized = 1;
vars[idCount]->isNum = 1;
}
else{
if(id.find(inp)==id.end()){
idCount++;
id[inp] = idCount;
name[idCount] = inp;
vars[idCount] = new Variable(idCount, inp);
res = idCount;
type[idCount] = VARIABLE;
}
else{
res = id[inp];
}
}
return res;
}
int Graph::getFunction(string fnc){
idCount++;
id[fnc] = idCount;
name[idCount] = fnc;
type[idCount] = FUNCTION;
Function *f;
if(fnc.compare("mult")==0)
f = new Multiplication(idCount, fnc);
else if(fnc.compare("add")==0)
f = new Addition(idCount, fnc);
else if(fnc.compare("subs")==0)
f = new Subtraction(idCount, fnc);
else if(fnc.compare("divide")==0)
f = new Division(idCount, fnc);
else if(fnc.compare("sin")==0)
f = new Sine(idCount, fnc);
else if(fnc.compare("cos")==0)
f = new Cosine(idCount, fnc);
else if(fnc.compare("identity")==0)
f = new Identity(idCount, fnc);
else if(fnc.compare("tan")==0)
f = new Tangent(idCount, fnc);
else if(fnc.compare("acos")==0)
f = new ArcCosine(idCount, fnc);
else if(fnc.compare("asin")==0)
f = new ArcSine(idCount, fnc);
else if(fnc.compare("atan")==0)
f = new ArcTangent(idCount, fnc);
else if(fnc.compare("exp")==0)
f = new Exponential(idCount, fnc);
else if(fnc.compare("log")==0)
f = new Log(idCount, fnc);
else if(fnc.compare("log10")==0)
f = new Log10(idCount, fnc);
else if(fnc.compare("pow")==0)
f = new Power(idCount, fnc);
else if(fnc.compare("sqrt")==0)
f = new Sqrt(idCount, fnc);
fncs[idCount] = f;
return idCount;
}
void Graph::addAssignment(string lvalue, string rvalue,long status) {
vector<string> words;
split1(rvalue,words);
//<var> = <var>
if(status==1){
addUnaryFunction("identity",words[0],lvalue);
}
//<var> = <func> <var>
else if(status==2){
addUnaryFunction(words[0],words[1],lvalue);
}
//var = <func> <var> <var>
else if(status==3){
addBinaryFunction(words[0],words[1],words[2],lvalue);
}
}
void Graph::addUnaryFunction(string fnc, string inp, string out){
int fId = getFunction(fnc);
int inpId = getVariable(inp);
int outId = getVariable(out);
fncs[fId]->addInput(vars[inpId]);
fncs[fId]->setOutput(vars[outId]);
vars[inpId]->addTo(fncs[fId]);
vars[outId]->setFrom(fncs[fId]);
}
void Graph::addBinaryFunction(string fnc, string inp1, string inp2, string out){
int fId = getFunction(fnc);
int inpId1 = getVariable(inp1);
int inpId2 = getVariable(inp2);
int outId = getVariable(out);
fncs[fId]->addInput(vars[inpId1]);
fncs[fId]->addInput(vars[inpId2]);
fncs[fId]->setOutput(vars[outId]);
vars[inpId1]->addTo(fncs[fId]);
vars[inpId2]->addTo(fncs[fId]);
vars[outId]->setFrom(fncs[fId]);
}
void Graph::readGraph(char argv[]){
ifstream infile(argv);
string line;
getline(infile, line);
vector<string> firstLine;
split1(line,firstLine);
if(firstLine[0]=="input"){
inputNodes.push_back(getVariable(firstLine[1]));
while(infile.good()){
getline(infile, line);
if(line == "")
break;
vector<string> words;
split1(line,words);
if(words[0]=="input")
inputNodes.push_back(getVariable(words[1]));
else if(words[0]=="output")
outputNode = getVariable(words[1]);
//assignment
else{
string rValue = "";
for(int i=0;i<words.size()-2;i++)
rValue += words[2+i] + " ";
addAssignment(words[0],rValue,words.size()-2);
}
}
}
else{
cout << "Wrong format: First line must start with string 'input'";
}
}
vector<int> Graph::topologicalSort() {
vector< pair<int,int>> nodes;
vector<int> result;
//calculate the indegrees of variable nodes
for (auto it : vars){
if(it.second->from == nullptr){
nodes.push_back(make_pair(it.first,0));
}
else {
nodes.push_back(make_pair(it.first, 1));
}
}
//calculate the indegrees of function variables
for(auto it : fncs){
nodes.push_back(make_pair(it.first,(int)it.second->inputs.size()));
}
while(!nodes.empty()){
int currentNode;
int index;
for(int i=0;i<nodes.size();i++){
if(nodes[i].second==0){
currentNode = nodes[i].first;
index=i;
if(type[currentNode] == VARIABLE){
for(int j = 0;j < vars[currentNode]->to.size();j++){
int neighborFunc = vars[currentNode]->to[j]->id;
for(int t = 0; t < nodes.size();t++){
if(nodes[t].first==neighborFunc){
nodes[t].second--;
break;
}
}
}
}
else if(type[currentNode]== FUNCTION){
int neighborVar = fncs[currentNode]->output->id;
for(int t = 0; t < nodes.size();t++){
if(nodes[t].first==neighborVar){
nodes[t].second--;
break;
}
}
}
break;
}
}
result.push_back(currentNode);
nodes.erase(nodes.begin()+index);
}
reverse(result.begin(),result.end());
return result;
}
bool Graph::isCyclic(){
bool cycledetected = 1;
for(auto it : vars){
if(it.second->from == nullptr)
cycledetected = 0;
}
return cycledetected;
}
double Graph::forwardPass(vector<string> inputNames,vector<string> inputValues){
int varCount = numCount; //counts the number of variables to which a number is assigned
//set the values of inputs
for(int i=0;i<inputNames.size();i++){
unordered_map<string,int>::iterator it;
it = id.find(inputNames[i]);
// Check if iterator points to end of map
if (it != id.end())
{
vars[it->second]->value = stod(inputValues[i]);
vars[it->second]->initialized = 1;
varCount++;
}
else
{
cout << "Element Not Found" << endl;
}
}
while(varCount != vars.size()){
for (auto it : fncs){
int initCount = 0;
for(int j=0;j < (*(it.second)).inputs.size();j++){
if((*((*(it.second)).inputs[j])).initialized == 0)
initCount++;
}
//means that inputs of current function are ready
if((initCount == 0) && (it.second)->processed==0){
(*(it.second)).doForward();
varCount++;
}
}
}
for (auto it : vars){
if(it.second->isNum == 0)
it.second->initialized = 0;
}
for (auto it : fncs)
it.second->processed = 0;
return vars[outputNode]->value;
}
void Graph::backwardPass(){
vector<int> initVec;
for(int i=0;i<topologicalSort().size();i++){
initVec.push_back(topologicalSort()[i]);
}
//initialize the derivatives
for(auto it : vars){
if(it.first==outputNode){
it.second->derivative=1;
}
else{
it.second->derivative=0;
}
}
//skip the output variable, we've done it above which is df_df
for(int i=1;i<initVec.size();i++){
if(type[initVec[i]] == VARIABLE){
vector<int> visitedFuncIds;
for(int j=0;j<vars[initVec[i]]->to.size();j++){
bool visited = 0;
for(int t = 0;t<visitedFuncIds.size();t++){
if(visitedFuncIds[t] ==vars[initVec[i]]->to[j]->id)
visited = 1;
}
if(!visited){
vars[initVec[i]]->derivative += (vars[initVec[i]]->to[j]->doBackward(initVec[i]))*(vars[initVec[i]]->to[j]->output->derivative);
visitedFuncIds.push_back(vars[initVec[i]]->to[j]->id);
}
}
}
}
};
Graph::~Graph() {
}