/
node.py
2111 lines (1742 loc) · 72 KB
/
node.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 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida_core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import logging
import importlib
import collections
import numbers
import math
import six
from aiida.backends.utils import validate_attribute_key
from aiida.common.caching import get_use_cache
from aiida.common.exceptions import InternalError, ModificationNotAllowed, UniquenessError, ValidationError
from aiida.common.folders import SandboxFolder
from aiida.common.lang import override
from aiida.common.links import LinkType
from aiida.common.utils import abstractclassmethod
from aiida.common.utils import combomethod, classproperty
from aiida.plugins.loader import get_query_type_from_type_string, get_type_string_from_class
_NO_DEFAULT = tuple()
_HASH_EXTRA_KEY = '_aiida_hash'
def clean_value(value):
"""
Get value from input and (recursively) replace, if needed, all occurrences
of BaseType AiiDA data nodes with their value, and List with a standard list.
It also makes a deep copy of everything.
Note however that there is no logic to avoid infinite loops when the
user passes some perverse recursive dictionary or list.
In any case, however, this would not be storable by AiiDA...
:param value: A value to be set as an attribute or an extra
:return: a "cleaned" value, potentially identical to value, but with
values replaced where needed.
"""
# Must be imported in here to avoid recursive imports
from aiida.orm.data import BaseType
def clean_builtin(val):
if isinstance(val, numbers.Real) and (math.isnan(val) or math.isinf(val)):
# see https://www.postgresql.org/docs/current/static/datatype-json.html#JSON-TYPE-MAPPING-TABLE
raise ValidationError("nan and inf/-inf can not be serialized to the database")
return val
if isinstance(value, BaseType):
return clean_builtin(value.value)
if isinstance(value, dict):
# Check dictionary before iterables
return {k: clean_value(v) for k, v in value.items()}
if (isinstance(value, collections.Iterable) and not isinstance(value, six.string_types)):
# list, tuple, ... but not a string
# This should also properly take care of dealing with the
# basedatatypes.List object
return [clean_value(v) for v in value]
# If I don't know what to do I just return the value
# itself - it's not super robust, but relies on duck typing
# (e.g. if there is something that behaves like an integer
# but is not an integer, I still accept it)
return clean_builtin(value)
class _AbstractNodeMeta(ABCMeta):
"""
Some python black magic to set correctly the logger also in subclasses.
"""
def __new__(cls, name, bases, attrs):
newcls = ABCMeta.__new__(cls, name, bases, attrs)
# Configure the logger by inheriting from the aiida logger
if not attrs['__module__'].startswith('aiida.'):
newcls._logger = logging.getLogger('aiida.{:s}.{:s}'.format(attrs['__module__'], name))
else:
newcls._logger = logging.getLogger('{:s}.{:s}'.format(attrs['__module__'], name))
# Set the plugin type string and query type string
plugin_type_string = get_type_string_from_class(attrs['__module__'], name)
query_type_string = get_query_type_from_type_string(plugin_type_string)
newcls._plugin_type_string = plugin_type_string
newcls._query_type_string = query_type_string
return newcls
@six.add_metaclass(_AbstractNodeMeta)
class AbstractNode(object):
"""
Base class to map a node in the DB + its permanent repository counterpart.
Stores attributes starting with an underscore.
Caches files and attributes before the first save, and saves everything
only on store(). After the call to store(), attributes cannot be changed.
Only after storing (or upon loading from uuid) extras can be modified
and in this case they are directly set on the db.
In the plugin, also set the _plugin_type_string, to be set in the DB in
the 'type' field.
"""
# This will be set by the metaclass call
_logger = None
# Name to be used for the Repository section
_section_name = 'node'
# The name of the subfolder in which to put the files/directories
# added with add_path
_path_subfolder_name = 'path'
# A list of tuples, saying which attributes cannot be set at the same time
# See documentation in the set() method.
_set_incompatibilities = []
# A tuple of attribute names that can be updated even after node is stored
# Requires Sealable mixin, but needs empty tuple for base class
_updatable_attributes = tuple()
# A tuple of attribute names that will be ignored when creating the hash.
_hash_ignored_attributes = tuple()
# Flag that determines whether the class can be cached.
_cacheable = True
def get_desc(self):
"""
Returns a string with infos retrieved from a node's properties.
This method is actually overwritten by the inheriting classes
:return: a description string
"""
return ""
@classproperty
def plugin_type_string(cls):
"""Returns the plugin type string of the node class."""
return cls._plugin_type_string
@staticmethod
def get_schema():
"""
Every node property contains:
- display_name: display name of the property
- help text: short help text of the property
- is_foreign_key: is the property foreign key to other type of the node
- type: type of the property. e.g. str, dict, int
:return: get schema of the node
"""
return {
"attributes": {
"display_name": "Attributes",
"help_text": "Attributes of the node",
"is_foreign_key": False,
"type": "dict"
},
"attributes.state": {
"display_name": "State",
"help_text": "AiiDA state of the calculation",
"is_foreign_key": False,
"type": ""
},
"ctime": {
"display_name": "Creation time",
"help_text": "Creation time of the node",
"is_foreign_key": False,
"type": "datetime.datetime"
},
"extras": {
"display_name": "Extras",
"help_text": "Extras of the node",
"is_foreign_key": False,
"type": "dict"
},
"id": {
"display_name": "Id",
"help_text": "Id of the object",
"is_foreign_key": False,
"type": "int"
},
"label": {
"display_name": "Label",
"help_text": "User-assigned label",
"is_foreign_key": False,
"type": "str"
},
"mtime": {
"display_name": "Last Modification time",
"help_text": "Last modification time",
"is_foreign_key": False,
"type": "datetime.datetime"
},
"type": {
"display_name": "Type",
"help_text": "Code type",
"is_foreign_key": False,
"type": "str"
},
"user_id": {
"display_name": "Id of creator",
"help_text": "Id of the user that created the node",
"is_foreign_key": True,
"related_column": "id",
"related_resource": "_dbusers",
"type": "int"
},
"uuid": {
"display_name": "Unique ID",
"help_text": "Universally Unique Identifier",
"is_foreign_key": False,
"type": "unicode"
},
"nodeversion": {
"display_name": "Node version",
"help_text": "Version of the node",
"is_foreign_key": False,
"type": "int"
},
"process_type": {
"display_name": "Process type",
"help_text": "Process type",
"is_foreign_key": False,
"type": "str"
}
}
@property
def logger(self):
"""
Get the logger of the Node object.
:return: Logger object
"""
return self._logger
@abstractclassmethod
def get_subclass_from_uuid(cls, uuid):
"""
Get a node object from the uuid, with the proper subclass of Node.
(if Node(uuid=...) is called, only the Node class is loaded).
:param uuid: a string with the uuid of the object to be loaded.
:return: the object of the proper subclass.
:raise: NotExistent: if there is no entry of the desired
object kind with the given uuid.
"""
pass
@abstractclassmethod
def get_subclass_from_pk(cls, pk):
"""
Get a node object from the pk, with the proper subclass of Node.
(integer primary key used in this database),
but loading the proper subclass where appropriate.
:param pk: a string with the pk of the object to be loaded.
:return: the object of the proper subclass.
:raise: NotExistent: if there is no entry of the desired
object kind with the given pk.
"""
pass
def __int__(self):
if self._to_be_stored:
return None
return self.id
@abstractmethod
def __init__(self, **kwargs):
"""
Initialize the object Node.
:param uuid: if present, the Node with given uuid is
loaded from the database.
(It is not possible to assign a uuid to a new Node.)
"""
from aiida.orm.backend import construct_backend
self._to_be_stored = True
# Empty cache of input links in any case
self._attrs_cache = {}
self._inputlinks_cache = {}
self._temp_folder = None
self._repo_folder = None
self._backend = construct_backend()
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, str(self))
def __str__(self):
if not self.is_stored:
return "uuid: {} (unstored)".format(self.uuid)
return "uuid: {} (pk: {})".format(self.uuid, self.pk)
def __copy__(self):
"""Copying a Node is not supported in general, but only for the Data sub class."""
raise NotImplementedError('copying a base Node is not supported')
def __deepcopy__(self, memo):
"""Deep copying a Node is not supported in general, but only for the Data sub class."""
raise NotImplementedError('deep copying a base Node is not supported')
@property
def backend(self):
return self._backend
@property
def is_stored(self):
"""
Return True if the node is stored, False otherwise.
"""
return not self._to_be_stored
@abstractproperty
def ctime(self):
"""
Return the creation time of the node.
"""
pass
@abstractproperty
def mtime(self):
"""
Return the modification time of the node.
"""
pass
def _init_internal_params(self):
"""
Set the default values for this class; this method is automatically called by the init.
:note: if you inherit this function, ALWAYS remember to
call super()._init_internal_params() as the first thing
in your inherited function.
"""
pass
@property
def _set_defaults(self):
"""
Default values to set in the __init__, if no value is explicitly provided
for the given key.
It is a dictionary, with k=v; if the key k is not provided to the __init__,
and a value is present here, this is set.
"""
return {}
@abstractclassmethod
def query(cls, *args, **kwargs):
"""
Map to the aiidaobjects manager of the DbNode, that returns
Node objects (or their subclasses) instead of DbNode entities.
# TODO: VERY IMPORTANT: the recognition of a subclass from the type
# does not work if the modules defining the subclasses are not
# put in subfolders.
# In the future, fix it either to make a cache and to store the
# full dependency tree, or save also the path.
"""
pass
def _set_with_defaults(self, **kwargs):
"""
Calls the set() method, but also adds the class-defined default
values (defined in the self._set_defaults attribute),
if they are not provided by the user.
:note: for the default values, also allow to define 'hidden' methods,
meaning that if a default value has a key "_state", it will not call
the function "set__state" but rather "_set_state".
This is not allowed, instead, for the standard set() method.
"""
self._set_internal(arguments=self._set_defaults, allow_hidden=True)
# Pass everything to 'set'
self.set(**kwargs)
def set(self, **kwargs):
"""
For each k=v pair passed as kwargs, call the corresponding
set_k(v) method (e.g., calling self.set(property=5, mass=2) will
call self.set_property(5) and self.set_mass(2).
Useful especially in the __init__.
:note: it uses the _set_incompatibilities list of the class to check
that we are not setting methods that cannot be set at the same time.
_set_incompatibilities must be a list of tuples, and each tuple
specifies the elements that cannot be set at the same time.
For instance, if _set_incompatibilities = [('property', 'mass')],
then the call self.set(property=5, mass=2) will raise a ValueError.
If a tuple has more than two values, it raises ValueError if *all*
keys are provided at the same time, but it does not give any error
if at least one of the keys is not present.
:note: If one element of _set_incompatibilities is a tuple with only
one element, this element will not be settable using this function
(and in particular,
:raise ValueError: if the corresponding set_k method does not exist
in self, or if the methods cannot be set at the same time.
"""
self._set_internal(arguments=kwargs, allow_hidden=False)
def _set_internal(self, arguments, allow_hidden=False):
"""
Works as self.set(), but takes a dictionary as the 'arguments' variable,
instead of reading it from the ``kwargs``; moreover, it allows to specify
allow_hidden to True. In this case, if a a key starts with and
underscore, as for instance ``_state``, it will not call
the function ``set__state`` but rather ``_set_state``.
"""
for incomp in self._set_incompatibilities:
if all(k in arguments.keys() for k in incomp):
if len(incomp) == 1:
raise ValueError("Cannot set {} directly when creating "
"the node or using the .set() method; "
"use the specific method instead.".format(
incomp[0]))
else:
raise ValueError("Cannot set {} at the same time".format(
" and ".join(incomp)))
for k, v in arguments.items():
try:
if allow_hidden and k.startswith("_"):
method = getattr(self, '_set_{}'.format(k[1:]))
else:
method = getattr(self, 'set_{}'.format(k))
except AttributeError:
raise ValueError("Unable to set '{0}', no set_{0} method "
"found".format(k))
if not isinstance(method, collections.Callable):
raise ValueError("Unable to set '{0}', set_{0} is not "
"callable!".format(k))
method(v)
@abstractproperty
def type(self):
"""
Get the type of the node.
:return: a string.
"""
pass
@abstractproperty
def nodeversion(self):
"""
Return the version of the node
:return: A version integer
"""
pass
@property
def label(self):
"""
Get the label of the node.
:return: a string.
"""
return self._get_db_label_field()
@label.setter
def label(self, label):
"""
Set the label of the node.
:param label: a string
"""
self._update_db_label_field(label)
@abstractmethod
def _get_db_label_field(self):
"""
Get the label field acting directly on the DB
:return: a string.
"""
pass
@abstractmethod
def _update_db_label_field(self, field_value):
"""
Set the label field acting directly on the DB
"""
pass
@property
def description(self):
"""
Get the description of the node.
:return: a string
:rtype: str
"""
return self._get_db_description_field()
@description.setter
def description(self, desc):
"""
Set the description of the node
:param desc: a string
"""
self._update_db_description_field(desc)
@abstractmethod
def _get_db_description_field(self):
"""
Get the description of this node, acting directly at the DB level
"""
pass
@abstractmethod
def _update_db_description_field(self, field_value):
"""
Update the description of this node, acting directly at the DB level
"""
pass
def _validate(self):
"""
Check if the attributes and files retrieved from the DB are valid.
Raise a ValidationError if something is wrong.
Must be able to work even before storing: therefore, use the get_attr
and similar methods that automatically read either from the DB or
from the internal attribute cache.
For the base class, this is always valid. Subclasses will
reimplement this.
In the subclass, always call the super()._validate() method first!
"""
return True
@abstractmethod
def get_user(self):
"""
Get the user.
:return: a User model object
"""
pass
@abstractmethod
def set_user(self, user):
"""
Set the user
:param user: The new user
"""
pass
def _has_cached_links(self):
"""
Return True if there is at least one cached (input) link, that is a
link that is not stored yet in the database. False otherwise.
"""
return len(self._inputlinks_cache) != 0
# pylint: disable=protected-access
def add_link_from(self, src, label=None, link_type=LinkType.UNSPECIFIED):
"""
Add a link to the current node from the 'src' node.
Both nodes must be a Node instance (or a subclass of Node)
:note: In subclasses, change only this. Moreover, remember to call
the super() method in order to properly use the caching logic!
:param src: the source object
:param str label: the name of the label to set the link from src.
Default = None.
:param link_type: The type of link, must be one of the enum values
from :class:`~aiida.common.links.LinkType`
"""
assert src is not None, "You must provide a valid Node to link"
# Check that the label does not already exist
# This can happen also if both nodes are stored, e.g. if one first
# stores the output node and then the input node. Therefore I check
# it here.
if label in self._inputlinks_cache:
raise UniquenessError("Input link with name '{}' already present "
"in the internal cache".format(label))
# Check if the source allows output links from this node
# (will raise ValueError if this is not the case)
src._linking_as_output(self, link_type)
# If both are stored, write directly on the DB
if self.is_stored and src.is_stored:
self._add_dblink_from(src, label, link_type)
else: # at least one is not stored: add to the internal cache
self._add_cachelink_from(src, label, link_type)
def _add_cachelink_from(self, src, label, link_type):
"""
Add a link in the cache.
"""
if label is None:
raise ModificationNotAllowed(
"Cannot store a link in the cache if "
"no explicit label is provided. You can avoid "
"to provide an input link name only if "
"both nodes are already stored: in this case, "
"the link will be directly stored in the DB "
"and a default name will be provided")
if label in self._inputlinks_cache:
raise UniquenessError("Input link with name '{}' already present "
"in the internal cache".format(label))
self._inputlinks_cache[label] = (src, link_type)
def _replace_link_from(self, src, label, link_type=LinkType.UNSPECIFIED):
"""
Replace an input link with the given label, or simply creates it
if it does not exist.
:note: In subclasses, change only this. Moreover, remember to call
the super() method in order to properly use the caching logic!
:param src: the source object
:param str label: the name of the label to set the link from src.
"""
# If both are stored, write directly on the DB
if self.is_stored and src.is_stored:
self._replace_dblink_from(src, label, link_type)
# If the link was in the local cache, remove it
# (this could happen if I first store the output node, then
# the input node.
try:
del self._inputlinks_cache[label]
except KeyError:
pass
else: # at least one is not stored: set in the internal cache
# I insert the link directly in the cache rather than calling
# _add_cachelink_from because this latter performs an undesired check
self._inputlinks_cache[label] = (src, link_type)
def _remove_link_from(self, label):
"""
Remove from the DB the input link with the given label.
:note: In subclasses, change only this. Moreover, remember to call
the super() method in order to properly use the caching logic!
:note: No error is raised if the link does not exist.
:param str label: the name of the label to set the link from src.
:param link_type: The type of link, must be one of the enum values form
:class:`~aiida.common.links.LinkType`
"""
# Try to remove from the local cache, no problem if none is present
try:
del self._inputlinks_cache[label]
except KeyError:
pass
# If both are stored, remove also from the DB
if self.is_stored:
self._remove_dblink_from(label)
@abstractmethod
def _replace_dblink_from(self, src, label, link_type):
"""
Replace an input link with the given label and type, or simply creates
it if it does not exist.
:note: this function should not be called directly; it acts directly on
the database.
:param str src: the source object.
:param str label: the label of the link from src to the current Node
:param link_type: The type of link, must be one of the enum values form
:class:`~aiida.common.links.LinkType`
"""
pass
@abstractmethod
def _remove_dblink_from(self, label):
"""
Remove from the DB the input link with the given label.
:note: this function should not be called directly; it acts directly on
the database.
:note: No checks are done to verify that the link actually exists.
:param str label: the label of the link from src to the current Node
:param link_type: The type of link, must be one of the enum values form
:class:`~aiida.common.links.LinkType`
"""
pass
@abstractmethod
def _add_dblink_from(self, src, label=None, link_type=LinkType.UNSPECIFIED):
"""
Add a link to the current node from the 'src' node.
Both nodes must be a Node instance (or a subclass of Node)
:note: this function should not be called directly; it acts directly on
the database.
:param src: the source object
:param str label: the name of the label to set the link from src.
Default = None.
"""
pass
def _linking_as_output(self, dest, link_type):
"""
Raise a ValueError if a link from self to dest is not allowed.
Implement in subclasses.
:param dest: the destination output Node
:return: a boolean (True)
"""
return True
def get_inputs_dict(self, only_in_db=False, link_type=None):
"""
Return a dictionary where the key is the label of the input link, and
the value is the input node.
:param only_in_db: If true only get stored links, not cached
:param link_type: Only get inputs of this link type, if None then
returns all inputs of all link types.
:return: a dictionary {label:object}
"""
return dict(
self.get_inputs(
also_labels=True, only_in_db=only_in_db, link_type=link_type))
def get_outputs_dict(self, link_type=None):
"""
Return a dictionary where the key is the label of the output link, and
the value is the input node.
As some Nodes (Datas in particular) can have more than one output with
the same label, all keys have the name of the link with appended the pk
of the node in output.
The key without pk appended corresponds to the oldest node.
:return: a dictionary {linkname:object}
"""
if link_type is not None and not isinstance(link_type, LinkType):
raise TypeError("link_type should be a LinkType object")
all_outputs = self.get_outputs(also_labels=True, link_type=link_type)
all_linknames = [i[0] for i in all_outputs]
linknames_set = list(set(all_linknames))
# prepare a new output list
new_outputs = {}
# first add the defaults
for irreducible_linkname in linknames_set:
this_elements = [
i[1] for i in all_outputs if i[0] == irreducible_linkname
]
# select the oldest element
last_element = sorted(this_elements, key=lambda x: x.ctime)[0]
# for this one add the default value
new_outputs[irreducible_linkname] = last_element
# now for everyone append the string with the pk
for i in this_elements:
new_outputs[irreducible_linkname + "_{}".format(i.pk)] = i
return new_outputs
def get_inputs(self, node_type=None, also_labels=False, only_in_db=False, link_type=None):
"""
Return a list of nodes that enter (directly) in this node
:param node_type: If specified, should be a class, and it filters only
elements of that specific type (or a subclass of 'type')
:param also_labels: If False (default) only return a list of input nodes.
If True, return a list of tuples, where each tuple has the
following format: ('label', Node), with 'label' the link label,
and Node a Node instance or subclass
:param only_in_db: Return only the inputs that are in the database,
ignoring those that are in the local cache. Otherwise, return
all links.
:param link_type: Only get inputs of this link type, if None then
returns all inputs of all link types.
"""
if link_type is not None and not isinstance(link_type, LinkType):
raise TypeError('link_type should be a LinkType object')
inputs_list = self._get_db_input_links(link_type=link_type)
if not only_in_db:
# Needed for the check
input_list_keys = [i[0] for i in inputs_list]
for label, v in self._inputlinks_cache.items():
src = v[0]
input_link_type = v[1]
if label in input_list_keys:
raise InternalError("There exist a link with the same name '{}' both in the DB "
"and in the internal cache for node pk= {}!".format(label, self.pk))
if link_type is None or input_link_type is link_type:
inputs_list.append((label, src))
if node_type is None:
filtered_list = inputs_list
else:
filtered_list = [i for i in inputs_list if isinstance(i[1], node_type)]
if also_labels:
return list(filtered_list)
return [i[1] for i in filtered_list]
@abstractclassmethod
def _get_db_input_links(self, link_type):
"""
Return a list of tuples (label, aiida_class) for each input link,
possibly filtering only by those of a given type.
:param link_type: if not None, a link type to filter results
:return: a list of tuples (label, aiida_class)
"""
pass
@override
def get_outputs(self, node_type=None, also_labels=False, link_type=None):
"""
Return a list of nodes that exit (directly) from this node
:param node_type: if specified, should be a class, and it filters only
elements of that specific node_type (or a subclass of 'node_type')
:param also_labels: if False (default) only return a list of input nodes.
If True, return a list of tuples, where each tuple has the
following format: ('label', Node), with 'label' the link label,
and Node a Node instance or subclass
:param link_type: Only return outputs connected by links of this type.
"""
if link_type is not None and not isinstance(link_type, LinkType):
raise TypeError('link_type should be a LinkType object')
outputs_list = self._get_db_output_links(link_type=link_type)
if node_type is None:
filtered_list = outputs_list
else:
filtered_list = (i for i in outputs_list if isinstance(i[1], node_type))
if also_labels:
return list(filtered_list)
return [i[1] for i in filtered_list]
@abstractmethod
def _get_db_output_links(self, link_type):
"""
Return a list of tuples (label, aiida_class) for each output link,
possibly filtering only by those of a given type.
:param link_type: if not None, a link type to filter results
:return: a list of tuples (label, aiida_class)
"""
pass
@abstractmethod
def get_computer(self):
"""
Get the computer associated to the node.
:return: the Computer object or None.
"""
pass
def set_computer(self, computer):
"""
Set the computer to be used by the node.
Note that the computer makes sense only for some nodes: Calculation,
RemoteData, ...
:param computer: the computer object
"""
if self._to_be_stored:
if not computer.is_stored:
raise ValueError("The computer instance has not yet been stored")
self._set_db_computer(computer)
else:
raise ModificationNotAllowed(
"Node with uuid={} was already stored".format(self.uuid))
@abstractmethod
def _set_db_computer(self, computer):
"""
Set the computer directly inside the dbnode member, in the DB.
DO NOT USE DIRECTLY.
:param computer: the computer object
"""
pass
def _set_attr(self, key, value, clean=True, stored_check=True):
"""
Set a new attribute to the Node (in the DbAttribute table).
:param key: key name
:param value: its value
:param clean: whether to clean values.
WARNING: when set to False, storing will throw errors
for any data types not recognized by the db backend
:param stored_check: when set to False will disable the mutability check
:raise ModificationNotAllowed: if node is already stored
:raise ValidationError: if the key is not valid, e.g. it contains the separator symbol
"""
if stored_check and self.is_stored:
raise ModificationNotAllowed('Cannot change the attributes of a stored node')
validate_attribute_key(key)
if self._to_be_stored:
if clean:
self._attrs_cache[key] = clean_value(value)
else:
self._attrs_cache[key] = value
else:
self._set_db_attr(key, clean_value(value))
def _append_to_attr(self, key, value, clean=True):
"""
Append value to an attribute of the Node (in the DbAttribute table).
:param key: key name of "list-type" attribute
If attribute doesn't exist, it is created.
:param value: the value to append to the list
:param clean: whether to clean the value
WARNING: when set to False, storing will throw errors
for any data types not recognized by the db backend
:raise ValidationError: if the key is not valid, e.g. it contains the separator symbol
"""
validate_attribute_key(key)
try:
values = self.get_attr(key)
except AttributeError:
values = []
try:
if clean:
values.append(clean_value(value))
else:
values.append(value)
except AttributeError:
raise AttributeError(
"Use _set_attr only on attributes containing lists")
self._set_attr(key, values, clean=False)
@abstractmethod
def _set_db_attr(self, key, value):
"""
Set the value directly in the DB, without checking if it is stored, or
using the cache.
DO NOT USE DIRECTLY.
:param key: key name
:param value: its value
"""
pass