forked from GiulioRossetti/ndlib-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathndrest.py
2503 lines (2032 loc) · 92.7 KB
/
ndrest.py
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
from flask import Flask, request
import shelve
import past
from future.utils import iteritems
try:
import dumbdbm
except ImportError:
from future.moves.dbm import dumb as dumbdbm
import glob
import os
import dynetx as dn
from utils import generators
from flask_cors import CORS
from flask_restful import Resource, Api
from flask_apidoc import ApiDoc
import ndlib.models.DynamicDiffusionModel as DD
import ndlib.models.ModelConfig as mc
import ndlib.models.epidemics.ThresholdModel as tm
import ndlib.models.epidemics.SIRModel as sir
import ndlib.models.epidemics.SIModel as si
import ndlib.models.epidemics.SISModel as sis
import ndlib.models.epidemics.SEIRModel as seir
import ndlib.models.epidemics.SEISModel as seis
import ndlib.models.epidemics.ProfileModel as ac
import ndlib.models.epidemics.ProfileThresholdModel as pt
import ndlib.models.epidemics.IndependentCascadesModel as ic
import ndlib.models.epidemics.KerteszThresholdModel as jt
import ndlib.models.opinions.VoterModel as vm
import ndlib.models.opinions.QVoterModel as qvm
import ndlib.models.opinions.MajorityRuleModel as mrm
import ndlib.models.opinions.SznajdModel as sm
import ndlib.models.opinions.CognitiveOpDynModel as cop
import ndlib.models.opinions.AlgorithmicBiasModel as ab
import ndlib.models.dynamic.DynSIModel as dsi
import ndlib.models.dynamic.DynSIRModel as dsir
import ndlib.models.dynamic.DynSISModel as dsis
import json
import shutil
import networkx as nx
from networkx.readwrite import json_graph
import uuid
import copy
import logging
from logging.handlers import RotatingFileHandler
__author__ = "Giulio Rossetti"
__email__ = "[email protected]"
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 20MB limit for uploads
api = Api(app)
doc = ApiDoc(app=app)
CORS(app)
max_number_of_nodes = 100000
min_number_of_nodes = 200
# Status code
success = 200
created = 201
bad_request = 400
unauthorized = 401
forbidden = 403
not_found = 404
unavailable = 451
not_implemented = 501
# Request Logging
logger = logging.getLogger('werkzeug')
handler = RotatingFileHandler('logs/access.log.gz', maxBytes=1000, backupCount=1)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
app.logger.addHandler(handler)
def update_model(md, status):
config = mc.Configuration()
# nodes conf
if 'nodes' in status:
for cn, cc in iteritems(status['nodes']):
for n, v in iteritems(cc):
config.add_node_configuration(cn, int(n), float(v))
# edges conf
if 'edges' in status:
for ce in status['edges']:
config.add_edge_configuration('threshold', (int(ce['source']), int(ce['target'])), float(ce['weight']))
# model conf
for k, v in iteritems(md.params['model']):
config.add_model_parameter(k, v)
if 'model' in status:
for me, mv in iteritems(status['model']):
config.add_model_parameter(me, float(mv))
# status conf
if 'status' in status:
for se, sv in iteritems(status['status']):
if se in md.available_statuses:
config.add_model_initial_configuration(se, list(map(int, sv)))
md.set_initial_status(config)
return md
def config_model(token, model_name, model):
if len(glob.glob("data/db/%s/configuration*" % token)) > 0:
db_model = load_data("data/db/%s/models" % token)
r = db_model['models']
keys = r.keys()
if len(keys) > 0:
mid = len([int(x.split("_")[1]) for x in keys if model_name == x.split("_")[0]])
db_name = '%s_%s' % (model_name, mid)
else:
db_name = "%s_0" % model_name
db_conf = load_data("data/db/%s/configuration" % token)
mod = update_model(model, db_conf)
db_model['models'][db_name] = mod
db_model.close()
db_model = load_data("data/db/%s/models" % token)
r = db_model['models']
keys = r.keys()
if len(keys) > 0:
mid = len([int(x.split("_")[1]) for x in keys if model_name == x.split("_")[0]])
db_name = '%s_%s' % (model_name, mid)
else:
db_name = "%s_0" % model_name
r[db_name] = {}
db_model['models'] = r
db_model.close()
db_md_conf = load_data("data/db/%s/%s" % (token, db_name))
r = db_md_conf
r[db_name] = model
db_md_conf = r
db_md_conf.close()
def load_data(path):
db = dumbdbm.open(path)
db_net = shelve.Shelf(db)
return db_net
class Experiment(Resource):
"""
@apiDefine Experiment Experiment
An experiment represents the analytical unit of this REST API, it is composed by:
<ul>
<li>A single network</li>
<li>One or more diffusion models</li>
</ul>
In order to perform an experiment the user should:
<ol>
<li><a href="#api-Experiment-getexp">Request a token</a>, which univocally identifies the experiment</li>
<li><a href="#api-Resources">Select</a> and <a href="#api-Networks">load</a> resource using a
Network Generator or loading an existing Graph</li>
<li><a href="#api-Models">Select</a> one, or more, diffusion model(s)</li>
<li>(optional) Use the <a href="#api-Experiment-configure">advanced configuration</a> facilities</li>
<li><a href="#api-Iterators">Execute</a> the simulation</li>
<li>(optional) <a href="#api-Experiment-resetexp">Reset</a> the experiment status, modify the models/network</li>
<li><a href="#api-Experiment-deleteexp">Destroy</a> the experiment </li>
</ol>
"""
def get(self):
"""
@api {get} /api/Experiment Create
@ApiDescription Setup a new experiment and generate a its unique identifier.
An experiment is described by the Network (only one) and Models associated to it.
@apiVersion 0.1.0
@apiName getexp
@apiGroup Experiment
@apiSuccess {String} token The token identifying the experiment.
@apiExample [python request] Example usage:
get('http://localhost:5000/api/Experiment')
"""
token = str(uuid.uuid4())
directory = "data/db/%s" % token
if not os.path.exists(directory):
os.makedirs(directory)
db_net = load_data("%s/net" % directory)
db_models = load_data("%s/models" % directory)
r = db_models
r['models'] = {}
db_models = r
db_net.close()
db_models.close()
return {'token': token}, success
def delete(self):
"""
@api {delete} /api/Experiment Destroy
@ApiDescription Delete all the resources (the network and the models) attached to the specified experiment.
@apiVersion 0.1.0
@apiParam {String} token The token identifying the experiment.
@apiName deleteexp
@apiGroup Experiment
@apiExample [python request] Example usage:
delete('http://localhost:5000/api/Experiment', data={'token': token})
"""
token = str(request.form['token'])
try:
shutil.rmtree("data/db/%s" % token)
except:
return {"Message": "Wrong Token"}, bad_request
return {'Message': "Experiment Destroyed"}, success
class ExperimentStatus(Resource):
def post(self):
"""
@api {post} /api/ExperimentStatus Describe
@ApiDescription Describe the resources (Network and Models) involved in the experiment.
@apiVersion 0.1.0
@apiName describeexp
@apiGroup Experiment
@apiParam {String} token The token identifying the experiment.
@apiExample {python} [Python request] Example usage:
post('http://localhost:5000/api/ExperimentStatus')
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
result = {}
db_net = load_data("data/db/%s/net" % token)
try:
exp = db_net
net_info = {k: v for k, v in iteritems(exp['net']) if k != 'g'}
result['Network'] = net_info
db_net.close()
except:
return {'Message': 'No resources attached to this token'}, not_found
try:
db_model = load_data("data/db/%s/models" % token)
exp = db_model['models']
model_names = exp.keys()
db_model.close()
models = {}
for model in model_names:
db_model = load_data("data/db/%s/%s" % (token, model))
exp = db_model
models[model] = exp[model].get_info()
db_model.close()
result['Models'] = models
return result
except:
return {'Message': 'No resources attached to this token'}, not_found
def put(self):
"""
@api {put} /api/ExperimentStatus Reset
@ApiDescription Reset the status of models attached to the specified experiment.
If no models are specified all the current experiment statuses will be reset.
@apiVersion 0.1.0
@apiParam {String} token The token identifying the experiment.
@apiParam {String} models String of comma separated model names.
@apiName resetexp
@apiGroup Experiment
@apiExample [python request] Example usage:
put('http://localhost:5000/api/ExperimentStatus', data={'token': token, 'models': 'model1,model2'})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
ml = []
if 'models' in request.form:
ml = request.form['models'].split(',')
db_models = load_data("data/db/%s/models" % token)
exp = db_models['models'].keys()
db_models.close()
try:
ml = [c for c in ml if c != '']
models = ml if len(ml) > 0 else exp
for model_name in models:
db_mod = load_data("data/db/%s/%s" % (token, model_name))
r = db_mod
md = copy.deepcopy(r[model_name])
md.reset()
md.reset()
db_mod[model_name] = md
db_mod.close()
except:
return {'Message': 'Parameter error'}, bad_request
return {'Message': 'Experiment cleaned'}, success
#######################################################################################
class Graph(Resource):
def post(self):
"""
@api {post} /api/GetGraph Get Network
@ApiDescription Return the json representation of the network analyzed
@apiVersion 0.5.0
@apiName expgraphs
@apiGroup Networks
@apiParam token The token
@apiSuccessExample {json} Response example:
{
"directed": false,
"graph": {
"name": "barabasi_albert_graph(5,1)"
},
"links": [
{
"source": 0,
"target": 1
},
{
"source": 0,
"target": 2
},
{
"source": 0,
"target": 3
},
{
"source": 0,
"target": 4
}
],
"multigraph": false,
"nodes": [
{
"id": 0
},
{
"id": 1
},
{
"id": 2
},
{
"id": 3
},
{
"id": 4
}
]
}
@apiExample [python request] Example usage:
post('http://localhost:5000/api/GetGraph'data={'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
# res = json.load(open("resources/networks.json"))['networks']
# available = True
# for net in res:
# if net['name'] == db_net['net']['name']:
# available = net['open_access']
# break
# if available:
g = db_net['net']['g']
if isinstance(g, dn.DynGraph) or isinstance(g, dn.DynDiGraph):
res = dn.json_graph.node_link_data(g)
else:
res = json_graph.node_link_data(g)
#else:
# db_net.close()
# return {"Message": "Dataset in read-only access."}, unavailable
except:
db_net.close()
return {"Message": "No graph resource assigned to the experiment"}, not_found
db_net.close()
return res, success
class Resources(Resource):
"""
@apiDefine Resources Resources
Endpoints belonging to this family provide access to resources, networks and models, listing and lookup
facilities.</br>
They also handle the destruction phase of experiment resources.
"""
class UploadNetwork(Resource):
def put(self):
"""
@api {put} /api/UploadNetwork Upload Network
@ApiDescription
@apiVersion 0.9.0
@apiParam {String} token The token.
@apiParam {Boolean} directed If the graph is directed
@apiParam {json} graph JSON description of the graph attributes.
@apiParam {Boolean} dynamic If the graph is a dynamic one.
@apiParamExample {json} graph example:
{
"directed": false,
"graph": {
"name": "graph_name"
},
"links": [
{
"source": 0,
"target": 1
},
{
"source": 0,
"target": 2
},
{
"source": 0,
"target": 3
},
{
"source": 0,
"target": 4
}
],
"multigraph": false,
"nodes": [
{
"id": 0
},
{
"id": 1
},
{
"id": 2
},
{
"id": 3
},
{
"id": 4
}
]
}
@apiName upload
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/UploadNetwork', data={'file': JSON, 'directed': False, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
try:
data = json.loads(request.form['file'])
except:
return {"Message": "Value Error: No JSON object could be decoded"}, bad_request
try:
g = None
dynamic = request.form['dynamic']
if 'directed' in request.form:
directed = request.form['directed']
if directed == 'True':
if dynamic == 'True':
g = dn.json_graph.node_link_graph(data, directed=True)
else:
g = json_graph.node_link_graph(data, directed=True)
else:
if dynamic == 'True':
g = dn.json_graph.node_link_graph(data, directed=False)
else:
g = json_graph.node_link_graph(data, directed=False)
if len(g.nodes()) < min_number_of_nodes or len(g.nodes()) > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
r = db_net
r['net'] = {'g': g, 'name': 'Uploaded Graph'}
db_net = r
db_net.close()
except:
return {'Message': 'Parameter error'}, bad_request
return {"Message": "Configuration applied"}, success
class Networks(Resource):
"""
@apiDefine Networks Networks
Endpoints belonging to this family provide access to network resources.</br>
In particular they provide lookup facilities for both real world datasets and network generators. </br>
Moreover, the <a href="#api-Networks-expgraphs">Get Network</a> endpoint allows for the download of
synthetic (i.e., generated) networks as well as all of those datasets for which are not specified access
restriction.
"""
def get(self):
"""
@api {get} /api/Networks Real Networks Endpoints
@ApiDescription Return the available network endpoints and their parameters
@apiVersion 0.4.0
@apiName getgraphs
@apiGroup Resources
@apiSuccess {Object} endpoints List of network endpoints.
@apiSuccessExample {json} Response example: Available networks
{'networks':
[
{
'name': 'Lastfm',
'size':
{
'nodes': 70000,
'edges': 389639
},
'description': 'Undirected social graph involving UK users of Last.fm'
}
]
}
@apiExample [python request] Example usage:
get('http://localhost:5000/api/Networks')
"""
res = json.load(open("resources/networks.json"))
return res, success
def put(self):
"""
@api {put} /api/Networks Load real graph
@ApiDescription Create an ER graph compliant to the specified parameters and bind it to the provided token
@apiVersion 0.4.0
@apiParam {String} token The token.
@apiParam {String} name The network name.
@apiName loadgraph
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Networks', data={'name': 'Last.fm','token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
directed = False
name = request.form['name']
nets = json.load(open("resources/networks.json"))['networks']
for net in nets:
if net["name"] == name:
directed = net["directed"]
break
g = None
if directed:
g = nx.DiGraph()
else:
g = nx.Graph()
try:
f = open("data/networks/%s.csv" % name)
for l in f:
l = list(map(int, l.rstrip().split(",")))
g.add_edge(int(l[0]), int(l[1]))
db_net = load_data("data/db/%s/net" % token)
r = db_net
r['net'] = {'g': g, 'name': name}
db_net = r
db_net.close()
return {'Message': 'Network correctly loaded'}, success
except:
return {'Message': "Wrong network name."}, bad_request
def delete(self):
"""
@api {delete} /api/Networks Network Destroy
@ApiDescription Delete the graph resource attached to the specified token
@apiVersion 0.4.0
@apiParam {String} token The token.
@apiName destroynetwork
@apiGroup Resources
@apiExample [python request] Example usage:
delete('http://localhost:5000/api/Networks', data={'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
db_net = load_data("data/db/%s/net" % token)
r = db_net
del r['net']
r['net'] = {}
db_net = r
db_net.close()
return {'Message': 'Resource deleted'}, success
class Generators(Resource):
def get(self):
"""
@api {get} /api/Generators Network Generator Endpoints
@ApiDescription Return the available network endpoints and their parameters
@apiVersion 0.1.0
@apiName getnetworks
@apiGroup Resources
@apiSuccess {Object} endpoints List of network endpoints.
@apiSuccessExample {json} Response example: Endpoint List
{'endpoints':
[
{
'name': 'Erdos Reny',
'uri': 'http://localhost:5000/api/Networks/ERGraph',
'params':
{
'token': 'access token',
'n': 'number of nodes',
'p': 'rewiring probability'
}
},
{
'name': 'Barabasi Albert',
'uri': 'http://localhost:5000/api/Networks/BarabasiAlbertGraph',
'params':
{
'token': 'access token',
'n': 'number of nodes',
'm': 'Number of edges to attach from a new node to existing nodes'
}
}
]
}
@apiExample [python request] Example usage:
get('http://localhost:5000/api/Generators')
"""
res = json.load(open("resources/generators.json"))
return res, success
class ERGraph(Resource):
def put(self):
"""
@api {put} /api/Generators/ERGraph Erdos-Renyi
@ApiDescription Create an ER graph compliant to the specified parameters and bind it to the provided token
@apiVersion 0.1.0
@apiParam {String} token The token.
@apiParam {Number{200..100000}} n The number of nodes.
@apiParam {Number{0-1}} p The rewiring probability.
@apiParam {Boolean} directed If the graph should be directed.
@apiParam {Number} t Number of temporal snapshots
If not specified an undirected graph will be generated.
@apiName ERGraph
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Generators/ERGraph', data={'n': n, 'p': p, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
n = int(request.form['n'])
if n < min_number_of_nodes or n > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
p = float(request.form['p'])
directed = False
if 'directed' in request.form:
directed = request.form['directed']
if directed == 'True':
directed = True
if 't' in request.form:
t = int(request.form['t'])
if directed:
g = dn.DynDiGraph()
else:
g = dn.DynGraph()
else:
t = 1
if t > 1:
for it in past.builtins.xrange(0, t):
fl = nx.erdos_renyi_graph(n, p, directed)
g.add_interactions_from(fl.edges(), it)
else:
g = nx.erdos_renyi_graph(n, p, directed)
r = db_net
r['net'] = {'g': g, 'name': 'ERGraph', 'params': {'n': n, 'p': p}}
db_net = r
except:
db_net.close()
return {'Message': 'Parameter error'}, bad_request
db_net.close()
return {'Message': 'Resource created'}, success
class PlantedPartition(Resource):
def put(self):
"""
@api {put} /api/Generators/PlantedPartition Planted l-partitions
@ApiDescription Create a Planted l-Parition graph compliant to the specified parameters and bind it to the provided token
@apiVersion 0.9.2
@apiParam {String} token The token.
@apiParam {Number} l The number of groups.
@apiParam {Number} k The number of nodes per group.
@apiParam {Number} pin The probability of connecting vertices within a group.
@apiParam {Number} pout The probability of connecting vertices between a group.
@apiParam {Boolean} directed If the graph should be directed.
If not specified an undirected graph will be generated.
@apiName PlantedPartition
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Generators/PlantedPartition', data={'l': l, 'k': k, 'pin': pin, 'pout': pout, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
k = int(request.form['k'])
l = int(request.form['l'])
if k*l < min_number_of_nodes or k*l > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
pin = float(request.form['pin'])
pout = float(request.form['pout'])
directed = False
if 'directed' in request.form:
directed = bool(request.form['directed'])
g = generators.planted_partition_graph(l, k, pin, pout, directed=directed)
r = db_net
r['net'] = {'g': g, 'name': 'PlantedPartition', 'params': {'l': l, 'k': k, 'pin': pin, 'pout': pout}}
db_net = r
except:
db_net.close()
return {'Message': 'Parameter error'}, bad_request
db_net.close()
return {'Message': 'Resource created'}, success
class BarabasiAlbertGraph(Resource):
def put(self):
"""
@api {put} /api/Generators/BarabasiAlbertGraph Barabasi-Albert
@ApiDescription Create a BA graph compliant to the specified parameters and bind it to the provided token
@apiVersion 0.2.0
@apiParam {String} token The token.
@apiParam {Number{200..100000}} n The number of nodes.
@apiParam {Number{1..}} m The number of edges attached to each new node.
@apiName BAGraph
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Generators/BarabasiAlbertGraph', data={'n': n, 'm': m, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
n = int(request.form['n'])
if n < min_number_of_nodes or n > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
m = int(request.form['m'])
g = nx.barabasi_albert_graph(n, m)
r = db_net
r['net'] = {'g': g, 'name': 'BAGraph', 'params': {'n': n, 'm': m}}
db_net = r
except:
db_net.close()
return {'Message': 'Parameter error'}, bad_request
db_net.close()
return {'Message': 'Resource created'}, success
class ClusteredBarabasiAlbertGraph(Resource):
def put(self):
"""
@api {put} /api/Generators/ClusteredBarabasiAlbertGraph Clustered-Barabasi-Albert
@ApiDescription Create a CBA graph compliant to the specified parameters and bind it to the provided token
@apiVersion 0.9.2
@apiParam {String} token The token.
@apiParam {Number{200..100000}} n The number of nodes.
@apiParam {Number{1..}} m The number of edges attached to each new node.
@apiParam {Number{0-1}} p Probability of adding a triangle after adding a random edge
@apiName CBAGraph
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Generators/ClusteredBarabasiAlbertGraph', data={'n': n, 'm': m, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
n = int(request.form['n'])
if n < min_number_of_nodes or n > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
m = int(request.form['m'])
p = float(request.form['p'])
g = nx.powerlaw_cluster_graph(n, m, p)
r = db_net
r['net'] = {'g': g, 'name': 'CBAGraph', 'params': {'n': n, 'm': m, 'p': p}}
db_net = r
except:
db_net.close()
return {'Message': 'Parameter error'}, bad_request
db_net.close()
return {'Message': 'Resource created'}, success
class WattsStrogatzGraph(Resource):
def put(self):
"""
@api {put} /api/Generators/WattsStrogatzGraph Watts-Strogatz
@ApiDescription Create a WS graph compliant to the specified parameters and bind it to the provided token
@apiVersion 0.3.0
@apiParam {String} token The token.
@apiParam {Number{200..100000}} n The number of nodes.
@apiParam {Number{1..}} k Each node is connected to k nearest neighbors in ring topology
@apiParam {Number{0-1}} p The probability of rewiring each edge
@apiName WSGraph
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Generators/WattsStrogatzGraph', data={'n': n, 'k': k, 'p': p, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
n = int(request.form['n'])
if n < min_number_of_nodes or n > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
k = int(request.form['k'])
p = float(request.form['p'])
g = nx.watts_strogatz_graph(n, k, p)
r = db_net
r['net'] = {'g': g, 'name': 'WSGraph', 'params': {'n': n, 'k': k, 'p': p}}
db_net = r
except:
db_net.close()
return {'Message': 'Parameter error'}, bad_request
db_net.close()
return {'Message': 'Resource created'}, success
class CompleteGraph(Resource):
def put(self):
"""
@api {put} /api/Generators/CompleteGraph Complete Graph
@ApiDescription Create a complete graph of size n and bind it to the provided token
@apiVersion 0.9.0
@apiParam {String} token The token.
@apiParam {Number} n The number of nodes.
@apiName CompleteGraph
@apiGroup Networks
@apiExample [python request] Example usage:
put('http://localhost:5000/api/Generators/CompleteGraph', data={'n': n, 'token': token})
"""
token = str(request.form['token'])
if not os.path.exists("data/db/%s" % token):
return {"Message": "Wrong Token"}, bad_request
n = int(request.form['n'])
if n < 100 or n > max_number_of_nodes:
return {"Message": "Node number out fo range."}, bad_request
db_net = load_data("data/db/%s/net" % token)
try:
n = int(request.form['n'])
g = nx.complete_graph(n)
r = db_net
r['net'] = {'g': g, 'name': 'CompleteGraph', 'params': {'n': n}}
db_net = r
except:
db_net.close()
return {'Message': 'Parameter error'}, bad_request
db_net.close()
return {'Message': 'Resource created'}, success
#######################################################################################
class Models(Resource):
"""
@apiDefine Models Models
Endpoints belonging to this family provide access to model resources.
"""
def get(self):
"""
@api {get} /api/Models Models Endpoints
@ApiDescription Return the available models endpoints and their parameter specification
@apiVersion 0.1.0
@apiName getmodellist
@apiGroup Resources
@apiSuccess {Object} endpoints List of model endpoints.
@apiSuccessExample {json} Response example: Endpoint List
{'endponts':
[
{
'name': 'Threshold',
'uri': 'http://localhost:5000/api/Models/Threshold',
'params':
{
'token': 'access token',
}
},
{
'name': 'SIR',
'uri': 'http://localhost:5000/api/Models/SIR',
'params':
{
'token': 'access token',
}
}
]
}
@apiExample [python request] Example usage:
get('http://localhost:5000/api/Models')
"""
res = json.load(open("resources/models.json"))
return res, success
def delete(self):
"""
@api {delete} /api/Models Models Destroy
@ApiDescription Delete model resources attached to the specified token.
If no models are specified all the ones bind to the experiment will be destroyed.
@apiVersion 0.1.0
@apiParam {String} token The token.
@apiParam {String} models String composed by comma separated model names.