/
Networks.R
1301 lines (1217 loc) · 54.4 KB
/
Networks.R
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
# ==============================================================================
# Functions for NETWORK management and retrieving information on networks, nodes
# and edges. Includes all functions that result in the creation of a new network
# in Cytoscape, in addition to funcitons that extract network models into
# other useful objects.
#
# I. General network functions
# II. General node functions
# III. General edge functions
# IV. Network creation
# V. Network extraction
# VI. Internal functions
#
# Note: Go to NetworkSelection.R for all selection-related functions
#
# ==============================================================================
# I. General network functions
# ------------------------------------------------------------------------------
#' @title Set current network
#'
#' @description Selects the given network as "current"
#' @param network (optional) Name or suid of the network that you want set as current
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return server response
#' @export
#' @examples
#' \donttest{
#' setCurrentNetwork('MyNetwork')
#' }
setCurrentNetwork <- function(network = NULL, base.url = .defaultBaseUrl) {
suid = getNetworkSuid(network,base.url)
cmd <- paste0('network set current network=SUID:"', suid, '"')
commandsPOST(cmd, base.url = base.url)
}
# ------------------------------------------------------------------------------
#' @title Rename a network
#'
#' @description Sets a new name for this network
#' @details Duplicate network names are not allowed
#' @param title New name for the network
#' @param network (optional) Name or suid of the network that you want to rename; default is "current" network
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return None
#' @author Alexander Pico, Julia Gustavsen
#' @examples \donttest{
#' renameNetwork("renamed network")
#' }
#' @export
renameNetwork <- function(title,
network = NULL,
base.url = .defaultBaseUrl) {
old.suid = getNetworkSuid(network,base.url)
cmd <-
paste0('network rename name="',
title,
'" sourceNetwork=SUID:"',
old.suid,
'"')
res <- commandsPOST(cmd, base.url = base.url)
invisible(res)
}
# ------------------------------------------------------------------------------
#' @title Get the number of Cytoscape networks
#'
#' @description Returns the number of Cytoscape networks in the current Cytoscape session
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{numeric}
#' @author Alexander Pico, Tanja Muetze, Georgi Kolishovski, Paul Shannon
#' @examples \donttest{
#' getNetworkCount()
#' # 3
#' }
#' @export
getNetworkCount <- function(base.url = .defaultBaseUrl) {
res <- cyrestGET('networks/count', base.url = base.url)
return(as.integer(unname(res)))
}
# ------------------------------------------------------------------------------
#' @title Get the name of a network
#'
#' @description Retrieve the title of a network
#' @param suid (optional) SUID of the network; default is current network. If a
#' name is provided, then it is validated and returned.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return network name
#' @export
#' @examples
#' \donttest{
#' getNetworkName()
#' getNetworkName(1111)
#' }
#
# Dev Notes: together with getNetworkSuid, this function attempts to handle all
# of the multiple ways we support network referencing (e.g., title, SUID,
# 'current', and NULL). These functions are then used by all other functions
# that take a "network" argument.
#
getNetworkName <- function(suid = NULL, base.url = .defaultBaseUrl) {
if (is.character(suid)) {
#title provided
if (suid == 'current') {
network.suid = getNetworkSuid(base.url = base.url)
} else {
net.names <- getNetworkList(base.url = base.url)
if (suid %in% net.names) {
return(suid)
} else {
stop(paste0("Network does not exist: ", suid))
}
}
} else if (is.numeric(suid)) {
#suid provided
network.suid = suid
} else {
#use current network
network.suid = getNetworkSuid(base.url = base.url)
}
res <-
cyrestGET('networks.names',
list(
column = "suid",
query = network.suid),
base.url = base.url
)
network.name <- unname(res)[[1]]$name
return(network.name)
}
# ------------------------------------------------------------------------------
#' @title Get the SUID of a network
#'
#' @description Retrieve the SUID of a network
#' @param title (optional) Name of the network; default is "current" network. If
#' an SUID is provided, then it is validated and returned.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return (\code{numeric}) Network suid
#' @author Alexander Pico
#' @examples
#' \donttest{
#' getNetworkSuid()
#' getNetworkSuid("myNetwork")
#' # 80
#' }
#' @export
#
# Dev Notes: together with getNetworkName, this function attempts to handle all
# of the multiple ways we support network referencing (e.g., title, SUID,
# 'current', and NULL). These functions are then used by all other functions
# that take a "network" argument.
#
getNetworkSuid <- function(title = NULL, base.url = .defaultBaseUrl) {
if (is.character(title)) {
#title provided
if (title == 'current') {
network.title = title
} else {
net.names <- getNetworkList(base.url = base.url)
if (title %in% net.names) {
network.title = title
} else {
stop(paste0("Network does not exist: ", title))
}
}
} else if (is.numeric(title)) {
#suid provided
net.suids <- cyrestGET('networks', base.url = base.url)
if (title %in% net.suids) {
return(title)
} else {
stop(paste0("Network does not exist: ", title))
}
} else {
#use current network
network.title = 'current'
}
cmd <-
paste0(
'network get attribute network="',
network.title,
'" namespace="default" columnList="SUID"'
)
suid <- commandsPOST(cmd, base.url = base.url)
#suid <- gsub("\\{SUID:|\\}", "", res)
return(as.numeric(suid[[1]]))
}
# ------------------------------------------------------------------------------
#' @title Get the list of Cytoscape networks
#'
#' @description Returns the list of Cytoscape network names in the current Cytoscape session
#' @param getSUIDs (optional) Whether to return SUIDs instead of titles; default is FALSE.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{list}
#' @author Alexander Pico, Tanja Muetze, Georgi Kolishovski, Paul Shannon
#' @examples \donttest{
#' getNetworkList()
#' # 3
#' }
#' @export
getNetworkList <- function(getSUIDs = FALSE, base.url = .defaultBaseUrl) {
if (getNetworkCount(base.url) == 0) {
return(c())
}
if (getSUIDs) {
return(commandsPOST('network list', base.url = base.url)$networks)
} else {
return(commandsGET('network list', base.url = base.url))
}
}
# ------------------------------------------------------------------------------
#' @title Export Network
#'
#' @description Export a network to one of mulitple file formats
#' @param filename Full path or path relative to current working directory,
#' in addition to the name of the file. Extension is automatically added based
#' on the \code{type} argument. If blank, then the current network name is used.
#' @param type File type. SIF (default), CX, cyjs, graphML, NNF, xGMML.
#' @param network (optional) Name or SUID of a network or view. Default is the
#' "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @param overwriteFile (optional) FALSE allows Cytoscape show a message box before overwriting the file if the file already
#' exists; TRUE. allows Cytoscape to overwrite it without asking. Default value is TRUE.
#' @return None.
#' @examples \donttest{
#' exportNetwork('/path/filename','SIF')
#' }
#' @export
exportNetwork <- function (filename=NULL, type="SIF",
network=NULL, base.url = .defaultBaseUrl, overwriteFile = TRUE) {
cmd.string <- 'network export' # a good start
# filename must be suppled
if(is.null(filename))
filename <- getNetworkName(network, base.url)
# optional args
if(!is.null(network))
cmd.string <- paste0(cmd.string,' network="SUID:',getNetworkSuid(network,base.url),'"')
type = toupper(type)
if (type == 'CYS') {
message('Saving session as a CYS file...')
return(saveSession(filename = filename, base.url = base.url))
}
else {
#e.g., CX, CYJS, GraphML, NNF, SIF, XGMML
if (type == "GRAPHML")
type = 'GraphML'
cmd.string <- paste0(cmd.string,' options="',type,'"')
}
ext <- paste0(".",tolower(type),"$")
if (!grepl(ext,filename))
filename <- paste0(filename,".",tolower(type))
fileInfo <- sandboxGetFileInfo(filename, base.url=base.url)
if (length(fileInfo[['modifiedTime']] == 1) && fileInfo[['isFile']]){
if (overwriteFile){
sandboxRemoveFile(filename, base.url=base.url)
}
else {
warning("This file already exists. A Cytoscape popup will be
generated to confirm overwrite.",
call. = FALSE,
immediate. = TRUE)
}
}
commandsPOST(paste0(cmd.string,' OutputFile="',
getAbsSandboxPath(filename),'"'),
base.url = base.url)
}
# ------------------------------------------------------------------------------
#' @title Delete Network
#'
#' @description Delete a network from the current Cytoscape session.
#' @param network (optional) Name or SUID of the network. Default is the
#' "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return None
#' @examples \donttest{
#' deleteNetwork()
#' }
#' @export
deleteNetwork <- function (network = NULL, base.url = .defaultBaseUrl) {
suid = getNetworkSuid(network,base.url)
res = cyrestDELETE(paste("networks", suid, sep = "/"), base.url = base.url)
invisible(res)
}
# ------------------------------------------------------------------------------
#' @title Delete All Networks
#'
#' @description Delete all networks from the current Cytoscape session.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return None
#' @examples \donttest{
#' deleteAllNetworks()
#' }
#' @export
deleteAllNetworks <- function (base.url = .defaultBaseUrl) {
res = cyrestDELETE("networks", base.url = base.url)
invisible(res)
}
# ==============================================================================
# II. General node functions
# ------------------------------------------------------------------------------
#' Get list of nodes neighboring provided list
#'
#' @description Returns a non-redundant list of first
#' neighbors of the supplied list of nodes or current node selection.
#' @param node.names A \code{list} of SUIDs or names from the \code{name} column
#' of the \code{node table}. Default is currently selected nodes.
#' @param as.nested.list \code{logical} Whether to return lists of neighbors per query node
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return A list of unique node names, optionally nested per query node name.
#' @author Alexander Pico, Tanja Muetze, Georgi Kolishovski, Paul Shannon
#' @seealso
#' selectNodes
#' selectFirstNeighbors
#' @examples \donttest{
#' getFirstNeighbors()
#' }
#' @export
getFirstNeighbors <-
function (node.names = NULL,
as.nested.list = FALSE,
network = NULL,
base.url = .defaultBaseUrl) {
if (is.null(node.names))
node.names <- getSelectedNodes(network=network,base.url=base.url)
if (length (node.names) == 0)
return()
net.SUID = getNetworkSuid(network,base.url)
neighbor.names <- c()
for (node.name in node.names) {
# get first neighbors for each node
node.SUID = .nodeNameToNodeSUID(node.name, net.SUID, base.url, uniqueList=TRUE)
first.neighbors.SUIDs <- cyrestGET(
paste(
"networks",
net.SUID,
"nodes",
as.character(node.SUID),
"neighbors",
sep = "/"
),
base.url = base.url
)
first.neighbors.names <-
.nodeSUIDToNodeName(first.neighbors.SUIDs, net.SUID, base.url)
if (as.nested.list) {
neighbor.names <-
append(neighbor.names, list(c(
node.name, list(first.neighbors.names)
)))
} else {
neighbor.names <- c(neighbor.names, first.neighbors.names)
neighbor.names <-
unique(unlist(neighbor.names, use.names = FALSE))
}
}
return (neighbor.names)
}
# ------------------------------------------------------------------------------
#' @title Add CyNodes
#'
#' @description Add one or more nodes to a Cytoscape network.
#' @param node.names A \code{list} of node names
#' @param skip.duplicate.names Skip adding a node if a node with the same name is already in
#' the network. If \code{FALSE} then a duplicate node (with a unique SUID) will be added. Default
#' is \code{TRUE}.
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return A \code{list} of \code{named lists} of name and SUID for each node added.
#' @examples \donttest{
#' addCyNodes(c('Node A','Node B','Node C'))
#' }
#' @importFrom BiocGenerics setdiff
#' @importFrom RJSONIO fromJSON
#' @export
addCyNodes <- function(node.names,
skip.duplicate.names = TRUE,
network = NULL,
base.url = .defaultBaseUrl) {
net.suid <- getNetworkSuid(network,base.url)
if (skip.duplicate.names)
node.names <-
setdiff(node.names, getAllNodes(net.suid, base.url))
res <- cyrestPOST(
paste("networks", net.suid, "nodes", sep = "/"),
body = node.names,
base.url = base.url
)
if(!findRemoteCytoscape(base.url)){
return(res)
} else {
return(fromJSON(res$text))
}
}
# ------------------------------------------------------------------------------
#' @title Get Node Count
#'
#' @description Reports the number of nodes in the network.
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{numeric}
#' @author Alexander Pico, Tanja Muetze, Georgi Kolishovski, Paul Shannon
#' @examples \donttest{
#' getNodeCount()
#' }
#' @export
getNodeCount <- function(network = NULL, base.url = .defaultBaseUrl) {
net.SUID <- getNetworkSuid(network,base.url)
res <-
cyrestGET(paste("networks", net.SUID, "nodes/count", sep = "/"),
base.url = base.url)
return(as.integer(unname(res)))
}
# ------------------------------------------------------------------------------
#' @title Get All Nodes
#'
#' @description Retrieve the names of all the nodes in the network.
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{list} of node names
#' @examples \donttest{
#' getAllNodes()
#' }
#' @export
getAllNodes <- function(network = NULL, base.url = .defaultBaseUrl) {
net.SUID <- getNetworkSuid(network,base.url)
n.count <- getNodeCount(net.SUID, base.url)
if (n.count == 0) {
return()
}
res <- cyrestGET(
paste(
"networks",
net.SUID,
"tables/defaultnode/columns/name",
sep = "/"
),
base.url = base.url
)
return(res$values)
}
# ==============================================================================
# III. General edge functions
# ------------------------------------------------------------------------------
#' @title Add CyEdges
#'
#' @description Add one or more edges to a Cytoscape network by listing source and
#' target node pairs.
#' @param source.target.list A \code{list} (or \code{list of lists}) of source
#' and target node name or SUID pairs
#' @param edgeType The type of interaction. Default is 'interacts with'.
#' @param directed \code{boolean} for whether interactions are directed. Default is \code{FALSE}.
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return A \code{list} of \code{named lists} of SUID, source and target for each edge added.
#' @examples \donttest{
#' addCyEdges(c('sourceNode','targetNode'))
#' addCyEdges(list(c('s1','t1'),c('s2','t2')))
#' }
#' @importFrom stats setNames
#' @importFrom RJSONIO fromJSON
#' @export
addCyEdges <-
function (source.target.list,
edgeType = 'interacts with',
directed = FALSE,
network = NULL,
base.url = .defaultBaseUrl) {
net.suid <- getNetworkSuid(network,base.url)
# swap with node suids
if (length(unlist(source.target.list)) > 2) {
# list of lists
edge.suid.list <- lapply(source.target.list, function(x)
lapply(x, function(y)
.nodeNameToNodeSUID(y, net.suid, base.url)))
} else {
# just single edge pair
edge.suid.list <- list(lapply(source.target.list,
function(y)
.nodeNameToNodeSUID(y, net.suid, base.url)))
}
# check for unique node name<->suid mappings
max.mapping <- lapply(edge.suid.list, function(x)
lapply(x, function(y)
max(length(y))))
if (as.integer(max(unlist(max.mapping))) > 1) {
message('RCy3::addCyEdges, more than one node found for a given
source or target node name. No edges added.')
return()
}
# add other fields
edge.data <- lapply(edge.suid.list,
function(y)
c(
setNames(as.list(unlist(y)), c("source", "target")),
directed = directed,
interaction = edgeType
))
res <- cyrestPOST(
paste("networks", net.suid, "edges", sep = "/"),
body = edge.data,
base.url = base.url
)
if(!findRemoteCytoscape(base.url)){
return(res)
} else {
return(fromJSON(res$text))
}
}
# ------------------------------------------------------------------------------
#' @title Get Edge Count
#'
#' @description Reports the number of the edges in the network.
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{numeric}
#' @author Alexander Pico, Tanja Muetze, Georgi Kolishovski, Paul Shannon
#' @examples \donttest{
#' getEdgeCount()
#' }
#' @export
getEdgeCount <- function(network = NULL, base.url = .defaultBaseUrl) {
net.SUID <- getNetworkSuid(network,base.url)
res <-
cyrestGET(paste("networks", net.SUID, "edges/count", sep = "/"),
base.url = base.url)
return(as.integer(unname(res)))
}
# ------------------------------------------------------------------------------
#' @title Get Edge Information
#'
#' @description Returns source, target and edge table row values.
#' @param edges List of SUIDs or names of edges, i.e., values in the "name"
#' column. Can also input a single edge.
#' @param network (optional) Name or SUID of the network. Default is the
#' "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{named list of lists}
#' @details This function is kinda slow. It takes approximately 70ms per edge
#' to return a result, e.g., 850 edges will take a one minute.
#' @author Alexander Pico
#' @examples \donttest{
#' getEdgeInfo()
#' }
#' @export
getEdgeInfo <- function(edges, network = NULL, base.url = .defaultBaseUrl) {
net.SUID <- getNetworkSuid(network,base.url)
ret <- lapply (edges, function(x){
edge.SUID <- .edgeNameToEdgeSUID(x, network, base.url)
res <- cyrestGET(paste("networks", net.SUID,
"edges", edge.SUID, sep = "/"),
base.url = base.url)
res[["data"]]
})
names(ret) <- edges
return(ret)
}
# ------------------------------------------------------------------------------
#' @title Get All Edges
#'
#' @description Retrieve the names of all the edges in the network.
#' @param network (optional) Name or SUID of the network. Default is the "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return \code{list} of node edges
#' @examples \donttest{
#' getAllEdges()
#' }
#' @export
getAllEdges <- function(network = NULL, base.url = .defaultBaseUrl) {
net.SUID <- getNetworkSuid(network,base.url)
e.count <- getEdgeCount(net.SUID, base.url)
if (e.count == 0) {
return()
}
res <- cyrestGET(
paste(
"networks",
net.SUID,
"tables/defaultedge/columns/name",
sep = "/"
),
base.url = base.url
)
return(res$values)
}
# ==============================================================================
# IV. Network creation
# ------------------------------------------------------------------------------
#' @title Clone a Cytoscape Network
#'
#' @description Makes a copy of a Cytoscape Network with all of its edges and nodes.
#' @param network (optional) Name or SUID of the network you want to clone;
#' default is "current" network
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return The \code{suid} of the new network
#' @examples \donttest{
#' cloneNetwork("cloned network")
#' }
#' @author Alexander Pico, Julia Gustavsen
#' @export
cloneNetwork <- function(network = NULL, base.url = .defaultBaseUrl) {
suid = getNetworkSuid(network,base.url)
cmd <- paste0('network clone network=SUID:"', suid, '"')
res <- commandsPOST(cmd, base.url = base.url)
return(res['network'])
}
# ------------------------------------------------------------------------------
#' @title Create subnetwork from existing network
#'
#' @description Copies a subset of nodes and edges into a newly created
#' subnetwork.
#' @details If you specify both nodes and edges, the resulting subset will be
#' the union of those sets. Typical usage only requires specifying either nodes
#' or edges. Note that selected nodes will bring along their connecting edges
#' by default (see exclude.edges arg) and selected edges will always
#' bring along their source and target nodes.
#' @param nodes list of nodes by SUID, by specified nodes.by.col value
#' (e.g., name) or by keyword: selected, unselected or all.
#' Default is currently selected nodes.
#' @param nodes.by.col name of node table column corresponding to provided
#' nodes list; default is 'SUID'
#' @param edges list of edges by SUID, by specified nodes.by.col value
#' (e.g., name) or by keyword: selected, unselected or all.
#' Default is currently selected edges.
#' @param edges.by.col name of edge table column corresponding to provided
#' edges list; default is 'SUID'
#' @param exclude.edges (boolean) whether to exclude connecting edges; default
#' is FALSE
#' @param subnetwork.name name of new subnetwork to be created;
#' default is to add a numbered suffix to source network name
#' @param network (optional) Name or SUID of the network. Default is the
#' "current" network active in Cytoscape.
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return SUID of new subnetwork
#' @export
#' @examples
#' \donttest{
#' createSubnetwork()
#' createSubnetwork("all")
#' createSubnetwork(subnetwork.name="mySubnetwork")
#' createSubnetwork(c("node 1","node 2","node 3"),"name")
#' createSubnetwork(c("AKT1","TP53","PIK3CA"),"display name")
#' createSubnetwork(edges="all") #subnetwork of all connected nodes
#' }
createSubnetwork <- function(nodes=NULL,
nodes.by.col = 'SUID',
edges=NULL,
edges.by.col = 'SUID',
exclude.edges = FALSE,
subnetwork.name=NULL,
network = NULL,
base.url = .defaultBaseUrl) {
title = getNetworkSuid(network, base.url)
if (exclude.edges)
exclude.edges = "true"
else
exclude.edges = "false"
if (length(nodes)==1 && nodes[1] %in% c('all','selected','unselected'))
nodes.by.col = NULL
if (length(edges)==1 && edges[1] %in% c('all','selected','unselected'))
edges.by.col = NULL
json_sub = NULL
json_sub$source = paste0("SUID:", title)
json_sub$excludeEdges = exclude.edges
json_sub$nodeList = .prepPostQueryLists(nodes,nodes.by.col)
json_sub$edgeList = .prepPostQueryLists(edges,edges.by.col)
if (!is.null(subnetwork.name)) {
json_sub$networkName = subnetwork.name
}
res <- cyrestPOST(
'commands/network/create',
body = as.list(json_sub),
base.url = base.url)
if(!findRemoteCytoscape(base.url)){
return(res$data['network'])
} else {
return(fromJSON(res$text)$data['network'])
}
}
# ------------------------------------------------------------------------------
#' @title Create a Cytoscape network from an igraph network
#'
#' @description Takes an igraph network and generates data frames for nodes and edges to
#' send to the createNetwork function.
#' Returns the network.suid and applies the perferred layout set in Cytoscape preferences.
#' @details Vertices and edges from the igraph network will be translated into nodes and edges
#' in Cytoscape. Associated attributes will also be passed to Cytoscape as node and edge
#' table columns. Note: undirected networks will be implicitly modeled as directed
#' in Cytoscape. Conversion back via \code{createIgraphFromNetwork} will result in
#' a directed network. Also note: igraph attributes of type "other" denoted by "x"
#' are converted to "String" in Cytoscape.
#' @param igraph (igraph) igraph network object
#' @param title (char) network name
#' @param collection (char) network collection name
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @param ... params for nodeSet2JSON() and edgeSet2JSON(); see createNetwork
#' @return (int) network SUID
#' @examples
#' \donttest{
#' library(igraph)
#' ig <- makeSimpleIgraph()
#' createNetworkFromIgraph(ig)
#' }
#' @seealso createNetworkFromDataFrames, createIgraphFromNetwork
#' @importFrom BiocGenerics colnames
#' @importFrom RJSONIO fromJSON
#' @export
createNetworkFromIgraph <- function(igraph,
title = "From igraph",
collection = "My Igraph Network Collection",
base.url = .defaultBaseUrl,
...) {
if (!requireNamespace("igraph", quietly = TRUE)) {
stop("Package \"igraph\" needed for this function to work. Please install it.",
call. = FALSE)
}
#extract dataframes
igedges = igraph::as_data_frame(igraph, what = "edges")
ignodes = igraph::as_data_frame(igraph, what = "vertices")
#setup columns for Cytoscape import
ignodes$id <- row.names(ignodes)
colnames(igedges)[colnames(igedges) == "from"] <- "source"
colnames(igedges)[colnames(igedges) == "to"] <- "target"
#protect against non-character and list types for special columns
ignodes$id <- unlist(lapply(ignodes$id, as.character))
igedges$source <- unlist(lapply(igedges$source, as.character))
igedges$target <- unlist(lapply(igedges$target, as.character))
if('interaction' %in% names(igedges))
igedges$interaction <- unlist(lapply(igedges$interaction, as.character))
#flatten all list types (until supported by createNetworkFromDataFrame)
ige.list.cols <- vapply(igedges, is.list, logical(1))
for(i in seq_along(ige.list.cols)){
if(ige.list.cols[i]){
suppressWarnings(igedges[i]<-lapply(igedges[[i]], paste, collapse=','))
}
}
ign.list.cols <- vapply(ignodes, is.list, logical(1))
for(i in seq_along(ign.list.cols)){
if(ign.list.cols[i]){
suppressWarnings(ignodes[i]<-lapply(ignodes[[i]], paste, collapse=','))
}
}
igedges = data.frame(lapply(igedges, unlist),stringsAsFactors = FALSE)
ignodes = data.frame(lapply(ignodes, unlist),stringsAsFactors = FALSE)
#check for empty data.frames
if (nrow(igedges) == 0)
igedges = NULL
if (nrow(ignodes) == 0)
ignodes = NULL
#ship
createNetworkFromDataFrames(ignodes, igedges, title, collection, base.url)
}
# ------------------------------------------------------------------------------
#' @title Create Network From Graph
#'
#' @description Creates a Cytoscape network from a Bioconductor graph.
#' @param graph A GraphNEL object
#' @param title (char) network name
#' @param collection (char) network collection name
#' @param base.url (optional) Ignore unless you need to specify a custom domain,
#' port or version to connect to the CyREST API. Default is http://localhost:1234
#' and the latest version of the CyREST API supported by this version of RCy3.
#' @return Network SUID
#' @author Alexander Pico, Tanja Muetze, Georgi Kolishovski, Paul Shannon
#' @examples \donttest{
#' library(graph)
#' g <- makeSimpleGraph()
#' createNetworkFromGraph(g)
#' }
#' @export
createNetworkFromGraph <- function (graph,
title = "From graph",
collection = "My GraphNEL Network Collection",
base.url = .defaultBaseUrl) {
if (!requireNamespace("igraph", quietly = TRUE)) {
stop("Package \"igraph\" needed for this function to work. Please install it.",
call. = FALSE)
}
createNetworkFromIgraph(igraph::igraph.from.graphNEL(graph),
title = title,
collection = collection,
base.url = base.url)
}
# ------------------------------------------------------------------------------
#' @title Create a network from data frames
#'
#' @description Takes data frames for nodes and edges, as well as naming
#' parameters to generate the JSON data format required by the "networks" POST
#' operation via CyREST. Returns the network.suid and applies the perferred
#' layout set in Cytoscape preferences.
#' @details NODES should contain a column of character strings named: id. This
#' name can be overridden by the arg: node.id.list. Additional columns are
#' loaded as node attributes. EDGES should contain columns of character strings
#' named: source, target and interaction. These names can be overridden by
#' args: source.id.list, target.id.list, interaction.type.list. Additional
#' columns are loaded as edge attributes. The 'interaction' list can contain a
#' single value to apply to all rows; and if excluded altogether, the
#' interaction type wiil be set to "interacts with". NOTE: attribute values of
#' types (num) will be imported as (Double); (int) as (Integer); (chr) as
#' (String); and (logical) as (Boolean). (Lists) will be imported as (Lists)
#' in CyREST v3.9+.
#' @param nodes (data.frame) see details and examples below; default NULL to
#' derive nodes from edge sources and targets
#' @param edges (data.frame) see details and examples below; default NULL for
#' disconnected set of nodes
#' @param title (char) network name
#' @param collection (char) network collection name
#' @param base.url (optional) Ignore unless you need to specify a custom
#' domain, port or version to connect to the CyREST API. Default is
#' http://localhost:1234 and the latest version of the CyREST API supported by
#' this version of RCy3.
#' @param ... params for nodeSet2JSON() and edgeSet2JSON()
#' @return (int) network SUID
#' @examples
#' \donttest{
#' nodes <- data.frame(id=c("node 0","node 1","node 2","node 3"),
#' group=c("A","A","B","B"), # categorical strings
#' score=as.integer(c(20,10,15,5))) # integers
#' edges <- data.frame(source=c("node 0","node 0","node 0","node 2"),
#' target=c("node 1","node 2","node 3","node 3"),
#' interaction=c("inhibits","interacts",
#' "activates","interacts"), # optional
#' weight=c(5.1,3.0,5.2,9.9)) # numeric
#'
#' createNetworkFromDataFrames(nodes,edges)
#' }
#' @export
createNetworkFromDataFrames <-
function(nodes = NULL,
edges = NULL,
title = "From dataframe",
collection = "My Dataframe Network Collection",
base.url = .defaultBaseUrl,
...) {
#defining variable names to be used globally later on (to avoid devtools::check() NOTES)
RCy3.CreateNetworkFromDataFrames.temp.global.counter <- NULL
RCy3.CreateNetworkFromDataFrames.temp.global.size <- NULL
RCy3.CreateNetworkFromDataFrames.temp.global.json_set <- NULL
if (is.null(nodes)) {
if (!is.null(edges)) {
nodes = data.frame(
id = c(edges$source, edges$target),
stringsAsFactors = FALSE
)
} else
stop("Create Network Failed: Must provide either nodes or edges")
} else {
nodes <- data.frame(nodes, stringsAsFactors = FALSE) #clear factors
}
# Assign ellipsis as variables
ellipsisArgs <- list(...)
for(i in seq_along(ellipsisArgs)){
assign(names(ellipsisArgs[i]), unlist(unname(ellipsisArgs[i])))
}
if(exists('node.id.list'))
nodes['id'] <- nodes[node.id.list]
node.id.list = 'id'
# Subset dataframe for initial network creation
json_nodes <- .nodeSet2JSON(nodes[node.id.list])
# cleanup global environment variables (which can be quite large)
remove(RCy3.CreateNetworkFromDataFrames.temp.global.counter,
envir = globalenv())
remove(RCy3.CreateNetworkFromDataFrames.temp.global.size,
envir = globalenv())
remove(RCy3.CreateNetworkFromDataFrames.temp.global.json_set,
envir = globalenv())
json_edges <- c()
if (!is.null(edges)) {
edges <- data.frame(edges, stringsAsFactors = FALSE) #clear factors
# Subset dataframe for initial network creation
if(exists('source.id.list'))
edges['source'] <- edges[source.id.list]
source.id.list = 'source'
if(exists('target.id.list'))
edges['target'] <- edges[target.id.list]
target.id.list = 'target'
if(exists('interaction.type.list'))
edges['interaction'] <- edges[interaction.type.list]
interaction.type.list = 'interaction'
if (!(interaction.type.list %in% names(edges)))
edges[, interaction.type.list] = rep('interacts with')
edges.sub <- edges[c(source.id.list,target.id.list,interaction.type.list)]
json_edges <- .edgeSet2JSON(edges.sub)
# cleanup global environment variables (which can be quite large)
remove(RCy3.CreateNetworkFromDataFrames.temp.global.counter,
envir = globalenv())
remove(RCy3.CreateNetworkFromDataFrames.temp.global.size,
envir = globalenv())
remove(RCy3.CreateNetworkFromDataFrames.temp.global.json_set,
envir = globalenv())
} else {
json_edges <- "[]" #fake empty array
}
json_network <- list(data = list(name = title),
elements = c(
nodes = list(json_nodes),
edges = list(json_edges)
))
network.suid <- cyrestPOST('networks',