-
Notifications
You must be signed in to change notification settings - Fork 36
/
models.py
1792 lines (1454 loc) · 62.1 KB
/
models.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
"""Define Dallinger's core models."""
from datetime import datetime
import inspect
from sqlalchemy import ForeignKey, or_, and_
from sqlalchemy import Column, String, Text, Enum, Integer, Boolean, DateTime, Float
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.sql.expression import false
from sqlalchemy.orm import relationship, validates
from .db import Base
DATETIME_FMT = "%Y-%m-%dT%H:%M:%S.%f"
def timenow():
"""A string representing the current date and time."""
return datetime.now()
class SharedMixin(object):
"""Create shared columns."""
#: a unique number for every entry. 1, 2, 3 and so on...
id = Column(Integer, primary_key=True, index=True)
#: the time at which the Network was created.
creation_time = Column(DateTime, nullable=False, default=timenow, index=True)
#: a generic column that can be used to store experiment-specific details in
#: String form.
property1 = Column(Text, nullable=True, default=None)
#: a generic column that can be used to store experiment-specific details in
#: String form.
property2 = Column(Text, nullable=True, default=None)
#: a generic column that can be used to store experiment-specific details in
#: String form.
property3 = Column(Text, nullable=True, default=None)
#: a generic column that can be used to store experiment-specific details in
#: String form.
property4 = Column(Text, nullable=True, default=None)
#: a generic column that can be used to store experiment-specific details in
#: String form.
property5 = Column(Text, nullable=True, default=None)
#: boolean indicating whether the Network has failed which
#: prompts Dallinger to ignore it unless specified otherwise. Objects are
#: usually failed to indicate something has gone wrong.
failed = Column(Boolean, nullable=False, default=False, index=True)
#: the time at which failing occurred
time_of_death = Column(DateTime, default=None)
#: a generic column for storing structured JSON data
details = Column(JSONB, nullable=False, server_default="{}", default=lambda: {})
def json_data(self):
return {}
def __json__(self):
"""Return json description of a participant."""
model_data = {
"id": self.id,
"creation_time": self.creation_time,
"failed": self.failed,
"time_of_death": self.time_of_death,
"property1": self.property1,
"property2": self.property2,
"property3": self.property3,
"property4": self.property4,
"property5": self.property5,
"details": self.details,
}
# Add any model specific data to the base data
model_data.update(self.json_data())
return model_data
class Participant(Base, SharedMixin):
"""An ex silico participant."""
__tablename__ = "participant"
#: a String giving the name of the class. Defaults to
#: "participant". This allows subclassing.
type = Column(String(50))
__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "participant"}
#: A String, the fingerprint hash of the participant.
fingerprint_hash = Column(String(50), nullable=True)
#: A String, the nickname of the recruiter used by this participant.
recruiter_id = Column(String(50), nullable=True)
#: A String, the worker id of the participant.
worker_id = Column(String(50), nullable=False)
#: A String, the assignment id of the participant.
assignment_id = Column(String(50), nullable=False, index=True)
#: A String, a concatenation of :attr:`~dallinger.models.Participant.worker_id`
#: and :attr:`~dallinger.models.Participant.assignment_id`
unique_id = Column(String(75), nullable=False, index=True)
#: A String, the id of the hit the participant is working on
hit_id = Column(String(50), nullable=False)
#: A String, the mode in which Dallinger is running: live,
#: sandbox or debug.
mode = Column(String(50), nullable=False)
#: The time at which the participant finished.
end_time = Column(DateTime)
#: The amount the participant was paid for finishing the
#: experiment.
base_pay = Column(Float)
#: the amount the participant was paid as a bonus.
bonus = Column(Float)
#: String representing the current status of the participant, can be:
#: - ``working`` - participant is working
#: - ``submitted`` - participant has submitted their work
#: - ``approved`` - their work has been approved and they have been paid
#: - ``rejected`` - their work has been rejected
#: - ``returned`` - they returned the hit before finishing
#: - ``abandoned`` - they ran out of time
#: - ``did_not_attend`` - the participant finished, but failed the
#: attention check
#: - ``bad_data`` - the participant finished, but their data was
#: malformed
#: - ``missing_notification`` - this indicates that Dallinger has
#: inferred that a Mechanical Turk notification corresponding to this
#: participant failed to arrive. This is an uncommon, but potentially
#: serious issue.
status = Column(
Enum(
"working",
"overrecruited",
"submitted",
"approved",
"rejected",
"returned",
"abandoned",
"did_not_attend",
"bad_data",
"missing_notification",
"replaced",
name="participant_status",
),
nullable=False,
default="working",
index=True,
)
def __init__(
self,
recruiter_id,
worker_id,
assignment_id,
hit_id,
mode,
fingerprint_hash=None,
):
"""Create a participant."""
self.recruiter_id = recruiter_id
self.worker_id = worker_id
self.assignment_id = assignment_id
self.hit_id = hit_id
self.unique_id = worker_id + ":" + assignment_id
self.mode = mode
self.fingerprint_hash = fingerprint_hash
def json_data(self):
"""Return json description of a participant."""
return {
"type": self.type,
"recruiter": self.recruiter_id,
"assignment_id": self.assignment_id,
"hit_id": self.hit_id,
"mode": self.mode,
"end_time": self.end_time,
"base_pay": self.base_pay,
"bonus": self.bonus,
"status": self.status,
}
def nodes(self, type=None, failed=False):
"""Get nodes associated with this participant.
Return a list of nodes associated with the participant. If specified,
``type`` filters by class. By default failed nodes are excluded, to
include only failed nodes use ``failed=True``, for all nodes use
``failed=all``.
"""
if type is None:
type = Node
if not issubclass(type, Node):
raise TypeError("{} is not a valid node type.".format(type))
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid node failed".format(failed))
if failed == "all":
return type.query.filter_by(participant_id=self.id).all()
else:
return type.query.filter_by(failed=failed, participant_id=self.id).all()
def questions(self, type=None):
"""Get questions associated with this participant.
Return a list of questions associated with the participant. If
specified, ``type`` filters by class.
"""
if type is None:
type = Question
if not issubclass(type, Question):
raise TypeError("{} is not a valid question type.".format(type))
return type.query.filter_by(participant_id=self.id).all()
def infos(self, type=None, failed=False):
"""Get all infos created by the participants nodes.
Return a list of infos produced by nodes associated with the
participant. If specified, ``type`` filters by class. By default, failed
infos are excluded, to include only failed nodes use ``failed=True``,
for all nodes use ``failed=all``. Note that failed filters the infos,
not the nodes - infos from all nodes (whether failed or not) can be
returned.
"""
nodes = self.nodes(failed="all")
infos = []
for n in nodes:
infos.extend(n.infos(type=type, failed=failed))
return infos
def fail(self):
"""Fail a participant.
Set :attr:`~dallinger.models.SharedMixin.failed` to ``True`` and
:attr:`~dallinger.models.SharedMixin.time_of_death` to now. Instruct all
not-failed nodes associated with the participant to fail.
"""
if self.failed is True:
raise AttributeError("Cannot fail {} - it has already failed.".format(self))
else:
self.failed = True
self.time_of_death = timenow()
for n in self.nodes():
n.fail()
for q in self.questions():
q.fail()
@property
def recruiter(self):
from dallinger import recruiters
recruiter_name = self.recruiter_id or "hotair"
if recruiter_name.startswith("bots:"):
recruiter_name = "bots"
return recruiters.by_name(recruiter_name)
class Question(Base, SharedMixin):
"""Responses of a participant to debriefing questions."""
__tablename__ = "question"
#: a String giving the name of the class. Defaults to
#: "question". This allows subclassing.
type = Column(String(50))
__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "question"}
#: the participant who made the response
participant_id = Column(Integer, ForeignKey("participant.id"))
#: the participant who answered the question
participant = relationship(Participant, backref="all_questions")
#: A number identifying the question. e.g., each participant might complete
#: three questions numbered 1, 2, and 3.
number = Column(Integer, nullable=False)
#: the text of the question
question = Column(String(250), nullable=False)
#: the participant's response. Stored as a string.
response = Column(String(1000), nullable=False)
def __init__(self, participant, question, response, number):
"""Create a question."""
# check the participant hasn't failed
if participant.failed:
raise ValueError(
"{} cannot create a question as it has failed".format(participant)
)
self.participant = participant
self.participant_id = participant.id
self.number = number
self.question = question
self.response = response
def fail(self):
"""Fail a question.
Set :attr:`~dallinger.models.SharedMixin.failed` to True and
:attr:`~dallinger.models.SharedMixin.time_of_death` to now.
"""
if self.failed is True:
raise AttributeError("Cannot fail {} - it has already failed.".format(self))
else:
self.failed = True
self.time_of_death = timenow()
def json_data(self):
"""Return json description of a question."""
return {
"number": self.number,
"type": self.type,
"participant_id": self.participant_id,
"question": self.question,
"response": self.response,
}
class Network(Base, SharedMixin):
"""Contains and manages a set of Nodes and Vectors etc."""
__tablename__ = "network"
#: A String giving the name of the class. Defaults to
#: "network". This allows subclassing.
type = Column(String(50))
__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "network"}
#: How big the network can get, this number is used by the full()
#: method to decide whether the network is full
max_size = Column(Integer, nullable=False, default=1e6)
#: Whether the network is currently full
full = Column(Boolean, nullable=False, default=False, index=True)
#: The role of the network. By default dallinger initializes all
#: networks as either "practice" or "experiment"
role = Column(String(26), nullable=False, default="default", index=True)
def __repr__(self):
"""The string representation of a network."""
return (
"<Network-{}-{} with {} nodes, {} vectors, {} infos, "
"{} transmissions and {} transformations>"
).format(
self.id,
self.type,
len(self.nodes()),
len(self.vectors()),
len(self.infos()),
len(self.transmissions()),
len(self.transformations()),
)
def json_data(self):
"""Return json description of a participant."""
return {
"type": self.type,
"max_size": self.max_size,
"full": self.full,
"role": self.role,
}
""" ###################################
Methods that get things about a Network
################################### """
def nodes(self, type=None, failed=False, participant_id=None):
"""Get nodes in the network.
type specifies the type of Node. Failed can be "all", False
(default) or True. If a participant_id is passed only
nodes with that participant_id will be returned.
"""
if type is None:
type = Node
if not issubclass(type, Node):
raise TypeError("{} is not a valid node type.".format(type))
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid node failed".format(failed))
if participant_id is not None:
if failed == "all":
return type.query.filter_by(
network_id=self.id, participant_id=participant_id
).all()
else:
return type.query.filter_by(
network_id=self.id, participant_id=participant_id, failed=failed
).all()
else:
if failed == "all":
return type.query.filter_by(network_id=self.id).all()
else:
return type.query.filter_by(failed=failed, network_id=self.id).all()
def size(self, type=None, failed=False):
"""How many nodes in a network.
type specifies the class of node, failed
can be True/False/all.
"""
return len(self.nodes(type=type, failed=failed))
def infos(self, type=None, failed=False):
"""
Get infos in the network.
type specifies the type of info (defaults to Info). failed { False,
True, "all" } specifies the failed state of the infos. To get infos
from a specific node, see the infos() method in class
:class:`~dallinger.models.Node`.
"""
if type is None:
type = Info
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid failed".format(failed))
if failed == "all":
return type.query.filter_by(network_id=self.id).all()
else:
return type.query.filter_by(network_id=self.id, failed=failed).all()
def transmissions(self, status="all", failed=False):
"""Get transmissions in the network.
status { "all", "received", "pending" }
failed { False, True, "all" }
To get transmissions from a specific vector, see the
transmissions() method in class Vector.
"""
if status not in ["all", "pending", "received"]:
raise ValueError(
"You cannot get transmission of status {}.".format(status)
+ "Status can only be pending, received or all"
)
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid failed".format(failed))
if status == "all":
if failed == "all":
return Transmission.query.filter_by(network_id=self.id).all()
else:
return Transmission.query.filter_by(
network_id=self.id, failed=failed
).all()
else:
if failed == "all":
return Transmission.query.filter_by(
network_id=self.id, status=status
).all()
else:
return Transmission.query.filter_by(
network_id=self.id, status=status, failed=failed
).all()
def transformations(self, type=None, failed=False):
"""Get transformations in the network.
type specifies the type of transformation (default = Transformation).
failed = { False, True, "all" }
To get transformations from a specific node,
see Node.transformations().
"""
if type is None:
type = Transformation
if failed not in ["all", True, False]:
raise ValueError("{} is not a valid failed".format(failed))
if failed == "all":
return type.query.filter_by(network_id=self.id).all()
else:
return type.query.filter_by(network_id=self.id, failed=failed).all()
def latest_transmission_recipient(self):
"""Get the node that most recently received a transmission."""
from operator import attrgetter
ts = Transmission.query.filter_by(
status="received", network_id=self.id, failed=False
).all()
if ts:
t = max(ts, key=attrgetter("receive_time"))
return t.destination
else:
return None
def vectors(self, failed=False):
"""
Get vectors in the network.
failed = { False, True, "all" }
To get the vectors to/from to a specific node, see Node.vectors().
"""
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid vector failed".format(failed))
if failed == "all":
return Vector.query.filter_by(network_id=self.id).all()
else:
return Vector.query.filter_by(network_id=self.id, failed=failed).all()
""" ###################################
Methods that make Networks do things
################################### """
def add_node(self, node):
"""Add the node to the network."""
raise NotImplementedError
def fail(self):
"""Fail an entire network."""
if self.failed is True:
raise AttributeError("Cannot fail {} - it has already failed.".format(self))
else:
self.failed = True
self.time_of_death = timenow()
for n in self.nodes():
n.fail()
def calculate_full(self):
"""Set whether the network is full."""
self.full = len(self.nodes()) >= (self.max_size or 0)
def print_verbose(self):
"""Print a verbose representation of a network."""
print("Nodes: ")
for a in self.nodes(failed="all"):
print(a)
print("\nVectors: ")
for v in self.vectors(failed="all"):
print(v)
print("\nInfos: ")
for i in self.infos(failed="all"):
print(i)
print("\nTransmissions: ")
for t in self.transmissions(failed="all"):
print(t)
print("\nTransformations: ")
for t in self.transformations(failed="all"):
print(t)
class Node(Base, SharedMixin):
"""A point in a network."""
__tablename__ = "node"
#: A String giving the name of the class. Defaults to
#: ``node``. This allows subclassing.
type = Column(String(50))
__mapper_args__ = {"polymorphic_on": type, "polymorphic_identity": "node"}
#: the id of the network that this node is a part of
network_id = Column(Integer, ForeignKey("network.id"), index=True)
#: the network the node is in
network = relationship(Network, backref="all_nodes")
#: the id of the participant whose node this is
participant_id = Column(Integer, ForeignKey("participant.id"), index=True)
#: the participant the node is associated with
participant = relationship(Participant, backref="all_nodes")
def __init__(self, network, participant=None):
"""Create a node."""
# check the network hasn't failed
if network.failed:
raise ValueError(
"Cannot create node in {} as it has failed".format(network)
)
# check the participant hasn't failed
if participant is not None and participant.failed:
raise ValueError(
"{} cannot create a node as it has failed".format(participant)
)
# check the participant is working
if participant is not None and participant.status != "working":
raise ValueError(
"{} cannot create a node as they are not working".format(participant)
)
self.network = network
self.network_id = network.id
network.calculate_full()
if participant is not None:
self.participant = participant
self.participant_id = participant.id
def __repr__(self):
"""The string representation of a node."""
return "Node-{}-{}".format(self.id, self.type)
def json_data(self):
"""The json of a node."""
return {
"type": self.type,
"network_id": self.network_id,
"participant_id": self.participant_id,
}
""" ###################################
Methods that get things about a node
################################### """
def vectors(self, direction="all", failed=False):
"""Get vectors that connect at this node.
Direction can be "incoming", "outgoing" or "all" (default).
Failed can be True, False or all
"""
# check direction
if direction not in ["all", "incoming", "outgoing"]:
raise ValueError(
"{} is not a valid vector direction. "
"Must be all, incoming or outgoing.".format(direction)
)
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid vector failed".format(failed))
# get the vectors
if failed == "all":
if direction == "all":
return Vector.query.filter(
or_(Vector.destination_id == self.id, Vector.origin_id == self.id)
).all()
if direction == "incoming":
return Vector.query.filter_by(destination_id=self.id).all()
if direction == "outgoing":
return Vector.query.filter_by(origin_id=self.id).all()
else:
if direction == "all":
return Vector.query.filter(
and_(
Vector.failed == failed,
or_(
Vector.destination_id == self.id,
Vector.origin_id == self.id,
),
)
).all()
if direction == "incoming":
return Vector.query.filter_by(
destination_id=self.id, failed=failed
).all()
if direction == "outgoing":
return Vector.query.filter_by(origin_id=self.id, failed=failed).all()
def neighbors(self, type=None, direction="to", failed=None):
"""Get a node's neighbors - nodes that are directly connected to it.
Type specifies the class of neighbour and must be a subclass of
Node (default is Node).
Connection is the direction of the connections and can be "to"
(default), "from", "either", or "both".
"""
# get type
if type is None:
type = Node
if not issubclass(type, Node):
raise ValueError(
"{} is not a valid neighbor type,"
"needs to be a subclass of Node.".format(type)
)
# get direction
if direction not in ["both", "either", "from", "to"]:
raise ValueError(
"{} not a valid neighbor connection."
"Should be both, either, to or from.".format(direction)
)
if failed is not None:
raise ValueError(
"You should not pass a failed argument to neighbors(). "
"Neighbors is "
"unusual in that a failed argument cannot be passed. This is "
"because there is inherent uncertainty in what it means for a "
"neighbor to be failed. The neighbors function will only ever "
"return not-failed nodes connected to you via not-failed "
"vectors. If you want to do more elaborate queries, for "
"example, getting not-failed nodes connected to you via failed"
" vectors, you should do so via sql queries."
)
neighbors = []
# get the neighbours
if direction == "to":
outgoing_vectors = (
Vector.query.with_entities(Vector.destination_id)
.filter_by(origin_id=self.id, failed=False)
.all()
)
neighbor_ids = [v.destination_id for v in outgoing_vectors]
if neighbor_ids:
neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all()
neighbors = [n for n in neighbors if isinstance(n, type)]
if direction == "from":
incoming_vectors = (
Vector.query.with_entities(Vector.origin_id)
.filter_by(destination_id=self.id, failed=False)
.all()
)
neighbor_ids = [v.origin_id for v in incoming_vectors]
if neighbor_ids:
neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all()
neighbors = [n for n in neighbors if isinstance(n, type)]
if direction == "either":
neighbors = list(
set(
self.neighbors(type=type, direction="to")
+ self.neighbors(type=type, direction="from")
)
)
if direction == "both":
neighbors = list(
set(self.neighbors(type=type, direction="to"))
& set(self.neighbors(type=type, direction="from"))
)
return neighbors
def is_connected(self, whom, direction="to", failed=None):
"""Check whether this node is connected [to/from] whom.
whom can be a list of nodes or a single node.
direction can be "to" (default), "from", "both" or "either".
If whom is a single node this method returns a boolean,
otherwise it returns a list of booleans
"""
if failed is not None:
raise ValueError(
"You should not pass a failed argument to is_connected."
"is_connected is "
"unusual in that a failed argument cannot be passed. This is "
"because there is inherent uncertainty in what it means for a "
"connection to be failed. The is_connected function will only "
"ever check along not-failed vectors. "
"If you want to check along failed vectors "
"you should do so via sql queries."
)
# make whom a list
if isinstance(whom, list):
is_list = True
else:
whom = [whom]
is_list = False
whom_ids = [n.id for n in whom]
# check whom contains only Nodes
for node in whom:
if not isinstance(node, Node):
raise TypeError(
"is_connected cannot parse objects of type {}.".format(type(node))
)
# check direction
if direction not in ["to", "from", "either", "both"]:
raise ValueError(
"{} is not a valid direction for is_connected".format(direction)
)
# get is_connected
connected = []
if direction == "to":
vectors = (
Vector.query.with_entities(Vector.destination_id)
.filter_by(origin_id=self.id, failed=False)
.all()
)
destinations = set([v.destination_id for v in vectors])
for w in whom_ids:
connected.append(w in destinations)
elif direction == "from":
vectors = (
Vector.query.with_entities(Vector.origin_id)
.filter_by(destination_id=self.id, failed=False)
.all()
)
origins = set([v.origin_id for v in vectors])
for w in whom_ids:
connected.append(w in origins)
elif direction in ["either", "both"]:
vectors = (
Vector.query.with_entities(Vector.origin_id, Vector.destination_id)
.filter(
and_(
Vector.failed == false(),
or_(
Vector.destination_id == self.id,
Vector.origin_id == self.id,
),
)
)
.all()
)
destinations = set([v.destination_id for v in vectors])
origins = set([v.origin_id for v in vectors])
if direction == "either":
origins_destinations = destinations.union(origins)
elif direction == "both":
origins_destinations = destinations.intersection(origins)
for w in whom_ids:
connected.append(w in origins_destinations)
if is_list:
return connected
else:
return connected[0]
def infos(self, type=None, failed=False):
"""Get infos that originate from this node.
Type must be a subclass of :class:`~dallinger.models.Info`, the default is
``Info``. Failed can be True, False or "all".
"""
if type is None:
type = Info
if not issubclass(type, Info):
raise TypeError(
"Cannot get infos of type {} " "as it is not a valid type.".format(type)
)
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid vector failed".format(failed))
if failed == "all":
return type.query.filter_by(origin_id=self.id).all()
else:
return type.query.filter_by(origin_id=self.id, failed=failed).all()
def received_infos(self, type=None, failed=None):
"""Get infos that have been sent to this node.
Type must be a subclass of info, the default is Info.
"""
if failed is not None:
raise ValueError(
"You should not pass a failed argument to received_infos. "
"received_infos is "
"unusual in that a failed argument cannot be passed. This is "
"because there is inherent uncertainty in what it means for a "
"received info to be failed. The received_infos function will "
"only ever check not-failed transmissions. "
"If you want to check failed transmissions "
"you should do so via sql queries."
)
if type is None:
type = Info
if not issubclass(type, Info):
raise TypeError(
"Cannot get infos of type {} " "as it is not a valid type.".format(type)
)
transmissions = (
Transmission.query.with_entities(Transmission.info_id)
.filter_by(destination_id=self.id, status="received", failed=False)
.all()
)
info_ids = [t.info_id for t in transmissions]
if info_ids:
return type.query.filter(type.id.in_(info_ids)).all()
else:
return []
def transmissions(self, direction="outgoing", status="all", failed=False):
"""Get transmissions sent to or from this node.
Direction can be "all", "incoming" or "outgoing" (default).
Status can be "all" (default), "pending", or "received".
failed can be True, False or "all"
"""
# check parameters
if direction not in ["incoming", "outgoing", "all"]:
raise ValueError(
"You cannot get transmissions of direction {}.".format(direction)
+ "Type can only be incoming, outgoing or all."
)
if status not in ["all", "pending", "received"]:
raise ValueError(
"You cannot get transmission of status {}.".format(status)
+ "Status can only be pending, received or all"
)
if failed not in ["all", False, True]:
raise ValueError("{} is not a valid transmission failed".format(failed))
# get transmissions
if direction == "all":
if status == "all":
return (
Transmission.query.filter(
and_(
Transmission.failed == false(),
or_(
Transmission.destination_id == self.id,
Transmission.origin_id == self.id,
),
)
)
.order_by("creation_time")
.all()
)
else:
return (
Transmission.query.filter(
and_(
Transmission.failed == false(),
Transmission.status == status,
or_(
Transmission.destination_id == self.id,
Transmission.origin_id == self.id,
),
)
)
.order_by("creation_time")
.all()
)
if direction == "incoming":
if status == "all":
return (
Transmission.query.filter_by(failed=False, destination_id=self.id)
.order_by("creation_time")
.all()
)
else:
return (
Transmission.query.filter(
and_(
Transmission.failed == false(),
Transmission.destination_id == self.id,
Transmission.status == status,
)
)
.order_by("creation_time")
.all()