def test_joins1(self): from aiida.orm import Node, Data, Calculation from aiida.orm.querybuilder import QueryBuilder # Creating n1, who will be a parent: parent=Node() parent.label = 'mother' good_child=Node() good_child.label='good_child' good_child._set_attr('is_good', True) bad_child=Node() bad_child.label='bad_child' bad_child._set_attr('is_good', False) unrelated = Node() unrelated.label = 'unrelated' for n in (good_child, bad_child, parent, unrelated): n.store() good_child.add_link_from(parent, label='parent') bad_child.add_link_from(parent, label='parent') # Using a standard inner join qb = QueryBuilder() qb.append(Node, tag='parent') qb.append(Node, tag='children', project='label', filters={'attributes.is_good':True}) self.assertEqual(qb.count(), 1) qb = QueryBuilder() qb.append(Node, tag='parent') qb.append(Node, tag='children', outerjoin=True, project='label', filters={'attributes.is_good':True}) self.assertEqual(qb.count(), 1)
def test_joins3_user_group(self): from aiida.orm.user import User from aiida.orm.querybuilder import QueryBuilder # Create another user new_email = "[email protected]" user = self.backend.users.create(email=new_email) user.store() # Create a group that belongs to that user from aiida.orm.group import Group group = Group(name="node_group") group.user = user group.store() # Search for the group of the user qb = QueryBuilder() qb.append(User, tag='user', filters={'id': {'==': user.id}}) qb.append(Group, belongs_to='user', filters={'id': {'==': group.id}}) self.assertEquals( qb.count(), 1, "The expected group that belongs to " "the selected user was not found.") # Search for the user that owns a group qb = QueryBuilder() qb.append(Group, tag='group', filters={'id': {'==': group.id}}) qb.append(User, owner_of='group', filters={'id': {'==': user.id}}) self.assertEquals( qb.count(), 1, "The expected user that owns the " "selected group was not found.")
def list_pseudo(sym, name, tags): """ List Gaussian Pseudopotentials """ from aiida.orm.querybuilder import QueryBuilder from aiida_gaussian_datatypes.pseudopotential.data import Pseudopotential query = QueryBuilder() query.append(Pseudopotential) if sym: query.add_filter(Pseudopotential, {'attributes.element': {'==': sym}}) if name: query.add_filter(Pseudopotential, {'attributes.aliases': { 'contains': [name] }}) if tags: query.add_filter(Pseudopotential, {'attributes.tags': { 'contains': tags }}) if not query.count(): echo.echo("No Gaussian Pseudopotentials found.") return echo.echo_report("{} Gaussian Pseudopotentials found:\n".format( query.count())) echo.echo(_formatted_table_list(pseudo for [pseudo] in query.iterall())) echo.echo("")
def get_code_helper(cls, label, machinename=None): """ :param label: the code label identifying the code to load :param machinename: the machine name where code is setup :raise aiida.common.NotExistent: if no code identified by the given string is found :raise aiida.common.MultipleObjectsError: if the string cannot identify uniquely a code """ from aiida.common.exceptions import NotExistent, MultipleObjectsError from aiida.orm.querybuilder import QueryBuilder from aiida.orm.computers import Computer qb = QueryBuilder() qb.append(cls, filters={'label': {'==': label}}, project=['*'], tag='code') if machinename: qb.append(Computer, filters={'name': {'==': machinename}}, with_node='code') if qb.count() == 0: raise NotExistent("'{}' is not a valid code name.".format(label)) elif qb.count() > 1: codes = qb.all(flat=True) retstr = ("There are multiple codes with label '{}', having IDs: ".format(label)) retstr += ', '.join(sorted([str(c.pk) for c in codes])) + '.\n' retstr += ('Relabel them (using their ID), or refer to them with their ID.') raise MultipleObjectsError(retstr) else: return qb.first()[0]
def list_basisset(sym, name, tags): """ List Gaussian Basis Sets """ from aiida.orm.querybuilder import QueryBuilder from aiida_gaussian_datatypes.basisset.data import BasisSet query = QueryBuilder() query.append(BasisSet) if sym: query.add_filter(BasisSet, {'attributes.element': {'==': sym}}) if name: query.add_filter(BasisSet, {'attributes.aliases': { 'contains': [name] }}) if tags: query.add_filter(BasisSet, {'attributes.tags': {'contains': tags}}) if not query.count(): echo.echo("No Gaussian Basis Sets found.") return echo.echo_report("{} Gaussian Basis Sets found:\n".format(query.count())) echo.echo(_formatted_table_list(bs for [bs] in query.iterall())) echo.echo("")
def test_uploadfamily_again(fresh_aiida_env, potcar_family, cmd_params): """ Re-upload a potcar family. Test: * Does not require description * Must succeed * Adds no nodes * Adds no groups """ from aiida.orm import Node, Group from aiida.orm.querybuilder import QueryBuilder node_qb = QueryBuilder(path=[Node]) node_count = node_qb.count() group_qb = QueryBuilder(path=[Group]) group_count = group_qb.count() result = run_cmd('uploadfamily', [cmd_params.PATH_OPTION, cmd_params.NAME_OPTION]) assert not result.exception node_qb = QueryBuilder(path=[Node]) assert node_count == node_qb.count() group_qb = QueryBuilder(path=[Group]) assert group_count == group_qb.count()
def listfamilies(element, with_description): """ Print on screen the list of installed PSF-pseudo families. """ from aiida import is_dbenv_loaded, load_dbenv if not is_dbenv_loaded(): load_dbenv() from aiida.orm import DataFactory from aiida_siesta.data.psf import PSFGROUP_TYPE PsfData = DataFactory('siesta.psf') from aiida.orm.querybuilder import QueryBuilder from aiida.orm.group import Group qb = QueryBuilder() qb.append(PsfData, tag='psfdata') if element: qb.add_filter(PsfData, {'attributes.element': {'in': element}}) qb.append( Group, group_of='psfdata', tag='group', project=["name", "description"], filters={ "type": { '==': PSFGROUP_TYPE } }) qb.distinct() if qb.count() > 0: for res in qb.dict(): group_name = res.get("group").get("name") group_desc = res.get("group").get("description") qb = QueryBuilder() qb.append( Group, tag='thisgroup', filters={ "name": { 'like': group_name } }) qb.append(PsfData, project=["id"], member_of='thisgroup') if with_description: description_string = ": {}".format(group_desc) else: description_string = "" click.echo("* {} [{} pseudos]{}".format(group_name, qb.count(), description_string)) else: click.echo("No valid PSF pseudopotential family found.", err=True)
def test_date(self): from aiida.orm.querybuilder import QueryBuilder from aiida.utils import timezone from datetime import timedelta from aiida.orm.node import Node n = Node() now = timezone.now() n._set_attr('now', now) n.store() qb = QueryBuilder().append(Node, filters={ 'attributes.now': { "and": [ { ">": now - timedelta(seconds=1) }, { "<": now + timedelta(seconds=1) }, ] } }) self.assertEqual(qb.count(), 1)
def print_node_info(node, print_groups=False): from aiida.cmdline.common import print_node_info ###TODO #Add a check here on the node type, otherwise it might try to access attributes such as code which are not necessarily there ##### print_node_info(node) if print_groups: from aiida.orm.querybuilder import QueryBuilder from aiida.orm.group import Group from aiida.orm.node import Node qb = QueryBuilder() qb.append(Node, tag='node', filters={'id': {'==': node.pk}}) qb.append(Group, tag='groups', group_of='node', project=['id', 'name']) click.echo("#### GROUPS:") if qb.count() == 0: click.echo("No groups found containing node {}".format(node.pk)) else: res = qb.iterdict() for gr in res: gr_specs = "{} {}".format(gr['groups']['name'], gr['groups']['id']) click.echo(gr_specs)
def get_subclass_from_pk(cls, pk): from aiida.orm.querybuilder import QueryBuilder from sqlalchemy.exc import DatabaseError # If it is not an int make a final attempt # to convert to an integer. If you fail, # raise an exception. try: pk = int(pk) except: raise ValueError("Incorrect type for int") try: qb = QueryBuilder() qb.append(cls, filters={'id': {'==': pk}}) if qb.count() == 0: raise NotExistent("No entry with pk= {} found".format(pk)) node = qb.first()[0] if not isinstance(node, cls): raise NotExistent("pk= {} is not an instance of {}".format( pk, cls.__name__)) return node except DatabaseError as de: raise ValueError(de.message)
def _rehash_cmd(all, class_name, pks): try_load_dbenv() from aiida.orm.querybuilder import QueryBuilder # Get the Node class to match try: node_class = load_class(class_name) except ClassNotFoundException: click.echo("Could not load class '{}'.\nAborted!".format(class_name)) sys.exit(1) # Add the filters for the class and PKs. qb = QueryBuilder() qb.append(node_class, tag='node') if pks: qb.add_filter('node', {'id': {'in': pks}}) else: if not all: click.echo( "Nothing specified, nothing re-hashed.\nExplicitly specify the PK of the nodes, or use '--all'." ) return if not qb.count(): click.echo('No matching nodes found.') return for i, (node, ) in enumerate(qb.iterall()): if i % 100 == 0: click.echo('.', nl=False) node.rehash() click.echo('\nAll done! {} node(s) re-hashed.'.format(i + 1))
def _check_pk_validity(self, pk): """ Checks whether a pk corresponds to an object of the expected type, whenever type is a valid column of the database (ex. for nodes, but not for users)_ :param pk: (integer) ok to check :return: True or False """ # The logic could be to load the node or to use querybuilder. Let's # do with qb for consistency, although it would be easier to do it # with load_node query_help_base = { 'path': [ { 'type': self._qb_type, 'label': self.__label__, }, ], 'filters': { self.__label__: { 'id': {'==': pk} } } } qb_base = QueryBuilder(**query_help_base) return qb_base.count() == 1
def node_show(nodes, print_groups): """Show generic information on one or more nodes.""" from aiida.cmdline.utils.common import get_node_info for node in nodes: # pylint: disable=fixme # TODO: Add a check here on the node type, otherwise it might try to access # attributes such as code which are not necessarily there echo.echo(get_node_info(node)) if print_groups: from aiida.orm.querybuilder import QueryBuilder from aiida.orm.groups import Group from aiida.orm import Node # pylint: disable=redefined-outer-name # pylint: disable=invalid-name qb = QueryBuilder() qb.append(Node, tag='node', filters={'id': {'==': node.pk}}) qb.append(Group, tag='groups', with_node='node', project=['id', 'label', 'type_string']) echo.echo('#### GROUPS:') if qb.count() == 0: echo.echo('Node {} does not belong to any group'.format(node.pk)) else: echo.echo('Node {} belongs to the following groups:'.format(node.pk)) res = qb.iterdict() table = [(gr['groups']['id'], gr['groups']['label'], gr['groups']['type_string']) for gr in res] table.sort() echo.echo(tabulate.tabulate(table, headers=['PK', 'Label', 'Group type']))
def get_data_aiida(cif_uuid, plot_info): """Query the AiiDA database""" from aiida import load_dbenv, is_dbenv_loaded from aiida.backends import settings if not is_dbenv_loaded(): load_dbenv(profile=settings.AIIDADB_PROFILE) from aiida.orm.querybuilder import QueryBuilder from aiida.orm.data.parameter import ParameterData from aiida.orm.data.cif import CifData qb = QueryBuilder() qb.append(CifData, filters={'uuid': { '==': cif_uuid }}, tag='cifs', project='*') qb.append( ParameterData, descendant_of='cifs', project='*', ) nresults = qb.count() if nresults == 0: plot_info.text = "No matching COF found." return None return qb.one()
def show(nodes, print_groups): """Show generic information on node(s).""" from aiida.cmdline.utils.common import get_node_info for node in nodes: # pylint: disable=fixme #TODO: Add a check here on the node type, otherwise it might try to access # attributes such as code which are not necessarily there echo.echo(get_node_info(node)) if print_groups: from aiida.orm.querybuilder import QueryBuilder from aiida.orm.group import Group from aiida.orm.node import Node # pylint: disable=redefined-outer-name # pylint: disable=invalid-name qb = QueryBuilder() qb.append(Node, tag='node', filters={'id': {'==': node.pk}}) qb.append(Group, tag='groups', group_of='node', project=['id', 'name']) echo.echo("#### GROUPS:") if qb.count() == 0: echo.echo("No groups found containing node {}".format(node.pk)) else: res = qb.iterdict() for gr in res: gr_specs = "{} {}".format(gr['groups']['name'], gr['groups']['id']) echo.echo(gr_specs)
def get_data_aiida(projections, sliders_dict, quantities, plot_info): """Query the AiiDA database""" from aiida import load_dbenv, is_dbenv_loaded from aiida.backends import settings if not is_dbenv_loaded(): load_dbenv(profile=settings.AIIDADB_PROFILE) from aiida.orm.querybuilder import QueryBuilder from aiida.orm.data.parameter import ParameterData filters = {} def add_range_filter(bounds, label): # a bit of cheating until this is resolved # https://github.com/aiidateam/aiida_core/issues/1389 # filters['attributes.'+label] = {'>=':bounds[0]} filters["attributes." + label] = { "and": [{ ">=": bounds[0] }, { "<": bounds[1] }] } for k, v in sliders_dict.items(): # Note: filtering is costly, avoid if possible if not v.value == quantities[k]["range"]: add_range_filter(v.value, k) qb = QueryBuilder() qb.append( ParameterData, filters=filters, project=["attributes." + p for p in projections] + ["uuid", "extras.cif_uuid"], ) nresults = qb.count() if nresults == 0: plot_info.text = "No matching frameworks found." return data_empty plot_info.text = "{} frameworks found. Plotting...".format(nresults) # x,y position x, y, clrs, uuids, names, cif_uuids = zip(*qb.all()) plot_info.text = "{} frameworks queried".format(nresults) x = map(float, x) y = map(float, y) cif_uuids = map(str, cif_uuids) uuids = map(str, uuids) if projections[2] == "group": # clrs = map(lambda clr: bondtypes.index(clr), clrs) clrs = map(str, clrs) else: clrs = map(float, clrs) return dict(x=x, y=y, uuid=cif_uuids, color=clrs, name=names)
def get_calc_by_label(workcalc, label): qb = QueryBuilder() qb.append(WorkChainNode, filters={'uuid':workcalc.uuid}) qb.append(CalcJob, with_incoming=WorkChainNode, filters={'label':label}) assert qb.count() == 1 calc = qb.first()[0] assert(calc.is_finished_ok) return calc
def listfamilies(elements, with_description): """ Print on screen the list of upf families installed """ from aiida.orm import DataFactory from aiida.orm.data.upf import UPFGROUP_TYPE # pylint: disable=invalid-name UpfData = DataFactory('upf') from aiida.orm.querybuilder import QueryBuilder from aiida.orm.group import Group qb = QueryBuilder() qb.append(UpfData, tag='upfdata') if elements is not None: qb.add_filter(UpfData, {'attributes.element': {'in': elements}}) qb.append(Group, group_of='upfdata', tag='group', project=["name", "description"], filters={"type": { '==': UPFGROUP_TYPE }}) qb.distinct() if qb.count() > 0: for res in qb.dict(): group_name = res.get("group").get("name") group_desc = res.get("group").get("description") qb = QueryBuilder() qb.append(Group, tag='thisgroup', filters={"name": { 'like': group_name }}) qb.append(UpfData, project=["id"], member_of='thisgroup') if with_description: description_string = ": {}".format(group_desc) else: description_string = "" echo.echo_success("* {} [{} pseudos]{}".format( group_name, qb.count(), description_string)) else: echo.echo_warning("No valid UPF pseudopotential family found.")
def get_calc_by_label(workcalc, label): qb = QueryBuilder() qb.append(WorkCalculation, filters={'uuid': workcalc.uuid}) qb.append(JobCalculation, output_of=WorkCalculation, filters={'label': label}) assert qb.count() == 1 calc = qb.first()[0] assert (calc.get_state() == 'FINISHED') return calc
def dump_pseudo(sym, name, tags, output_format, data): """ Print specified Pseudopotentials """ from aiida.orm.querybuilder import QueryBuilder from aiida_gaussian_datatypes.pseudopotential.data import Pseudopotential writers = { "cp2k": Pseudopotential.to_cp2k, } if data: # if explicit nodes where given the only thing left is to make sure no filters are present if sym or name or tags: raise click.UsageError( "can not specify node IDs and filters at the same time") else: query = QueryBuilder() query.append(Pseudopotential, project=["*"]) if sym: query.add_filter(Pseudopotential, {"attributes.element": { "==": sym }}) if name: query.add_filter(Pseudopotential, {"attributes.aliases": { "contains": [name] }}) if tags: query.add_filter(Pseudopotential, {"attributes.tags": { "contains": tags }}) if not query.count(): echo.echo_warning("No Gaussian Pseudopotential found.", err=echo.is_stdout_redirected()) return data = [pseudo for pseudo, in query.iterall() ] # query always returns a tuple, unpack it here for pseudo in data: if echo.is_stdout_redirected(): echo.echo_report("Dumping {}/{} ({})...".format( pseudo.name, pseudo.element, pseudo.uuid), err=True) writers[output_format](pseudo, sys.stdout)
def addNodes(nodeId, maxDepth, nodes, addedNodes, addedEdges, edgeType): qb = QueryBuilder() qb.append(Node, tag="main", filters={"id": {"==": nodeId}}) if edgeType == "ancestors": qb.append(Node, tag=edgeType, project=['id', 'type'], edge_project=['path', 'depth'], ancestor_of_beta='main', edge_filters={'depth': { '<=': maxDepth }}) elif edgeType == "desc": qb.append(Node, tag=edgeType, project=['id', 'type'], edge_project=['path', 'depth'], descendant_of_beta='main', edge_filters={'depth': { '<=': maxDepth }}) if (qb.count() > 0): qbResults = qb.get_results_dict() for resultDict in qbResults: if resultDict[edgeType]["id"] not in addedNodes: nodes.append({ "id": len(addedNodes), "nodeid": resultDict[edgeType]["id"], "nodetype": resultDict[edgeType]["type"], "group": edgeType + "-" + str(resultDict["main--" + edgeType]["depth"]) }) addedNodes.append(resultDict[edgeType]["id"]) path = resultDict["main--" + edgeType]["path"] if edgeType == "ancestors": startEdge = path[0] endEdge = path[1] elif edgeType == "desc": startEdge = path[-2] endEdge = path[-1] if startEdge not in addedEdges.keys(): addedEdges[startEdge] = [endEdge] elif endEdge not in addedEdges[startEdge]: addedEdges[startEdge].append(endEdge) return nodes, addedNodes, addedEdges
def get_computer_names(): """ Retrieve the list of computers in the DB. """ from aiida.orm.querybuilder import QueryBuilder builder = QueryBuilder() builder.append(entity_type='computer', project=['name']) if builder.count() > 0: return next(zip(*builder.all())) # return the first entry return []
def test_uploadfamily_dryrun(fresh_aiida_env, cmd_params): """Make sure --dry-run does not affect the db""" from aiida.orm import Node, Group from aiida.orm.querybuilder import QueryBuilder node_qb = QueryBuilder(path=[Node]) node_count = node_qb.count() group_qb = QueryBuilder(path=[Group]) group_count = group_qb.count() result = run_cmd('uploadfamily', [ cmd_params.PATH_OPTION, cmd_params.NAME_OPTION, cmd_params.DESC_OPTION, '--dry-run' ]) assert not result.exception node_qb = QueryBuilder(path=[Node]) assert node_count == node_qb.count() group_qb = QueryBuilder(path=[Group]) assert group_count == group_qb.count()
def get_computer_names(self): """ Retrieve the list of computers in the DB. ToDo: use an API or cache the results, sometime it is quite slow! """ from aiida.orm.querybuilder import QueryBuilder qb = QueryBuilder() qb.append(type='computer', project=['name']) if qb.count() > 0: return zip(*qb.all())[0] else: return None
def test_subclassing(self): from aiida.orm.data.structure import StructureData from aiida.orm.data.parameter import ParameterData from aiida.orm import Node, Data from aiida.orm.querybuilder import QueryBuilder s = StructureData() s._set_attr('cat', 'miau') s.store() d = Data() d._set_attr('cat', 'miau') d.store() p = ParameterData(dict=dict(cat='miau')) p.store() n = Node() n._set_attr('cat', 'miau') n.store() # Now when asking for a node with attr.cat==miau, I want 4 esults: qb = QueryBuilder().append(Node, filters={'attributes.cat': 'miau'}) self.assertEqual(qb.count(), 4) qb = QueryBuilder().append(Data, filters={'attributes.cat': 'miau'}) self.assertEqual(qb.count(), 3) # If I'm asking for the specific lowest subclass, I want one result for cls in (StructureData, ParameterData): qb = QueryBuilder().append(cls, filters={'attributes.cat': 'miau'}) self.assertEqual(qb.count(), 1) # Now I am not allow the subclassing, which should give 1 result for each for cls in (StructureData, ParameterData, Node, Data): qb = QueryBuilder().append(cls, filters={'attributes.cat': 'miau'}, subclassing=False) self.assertEqual(qb.count(), 1)
def dump_basisset(sym, name, tags, output_format, data): """ Print specified Basis Sets """ from aiida.orm.querybuilder import QueryBuilder from aiida_gaussian_datatypes.basisset.data import BasisSet writers = { "cp2k": BasisSet.to_cp2k, } if data: # if explicit nodes where given the only thing left is to make sure no filters are present if sym or name or tags: raise click.UsageError( "can not specify node IDs and filters at the same time") else: query = QueryBuilder() query.append(BasisSet, project=['*']) if sym: query.add_filter(BasisSet, {'attributes.element': {'==': sym}}) if name: query.add_filter(BasisSet, {'attributes.aliases': { 'contains': [name] }}) if tags: query.add_filter(BasisSet, {'attributes.tags': {'contains': tags}}) if not query.count(): echo.echo_warning("No Gaussian Basis Sets found.", err=echo.is_stdout_redirected()) return data = [bset for bset, in query.iterall() ] # query always returns a tuple, unpack it here for bset in data: if echo.is_stdout_redirected(): echo.echo_report("Dumping {}/{} ({})...".format( bset.name, bset.element, bset.uuid), err=True) writers[output_format](bset, sys.stdout)
def search(sliders_vals, inputs_vals): """Query AiiDA database""" filters = {} #pk_list = inp_pks.value.strip().split() #if pk_list: # filters['id'] = {'in': pk_list} def add_range_filter(bounds, label): filters['attributes.'+label] = {'and':[{'>=':bounds[0]}, {'<':bounds[1]}]} for k,v in sliders_vals.iteritems(): add_range_filter(v, k) inp_x = inputs_vals['inp_x'] inp_y = inputs_vals['inp_y'] inp_clr = inputs_vals['inp_clr'] qb = QueryBuilder() qb.append(ParameterData, filters=filters, project = ['attributes.'+inp_x, 'attributes.'+inp_y, 'attributes.'+inp_clr, 'uuid'] ) nresults = qb.count() print("Results: {}".format(nresults)) if nresults == 0: print("No results found.") #query_message.value = "No results found." return #query_message.value = "{} results found. Plotting...".format(nresults) # x,y position x, y, clrs, uuids = zip(*qb.all()) x = map(float, x) y = map(float, y) title = "{} vs {}".format(quantities[inp_y]['label'], quantities[inp_x]['label']) xlabel = '{} [{}]'.format(quantities[inp_x]['label'],quantities[inp_x]['unit']) ylabel = '{} [{}]'.format(quantities[inp_y]['label'],quantities[inp_y]['unit']) clrs = map(float, clrs) clr_label = "{} [{}]".format(quantities[inp_clr]['label'], quantities[inp_clr]['unit']) uuids = map(str, uuids) return plot_plotly(x, y, uuids, clrs, title=title, xlabel=xlabel, ylabel=ylabel, clr_label=clr_label)
def test_queryhelp(self): """ Here I test the queryhelp by seeing whether results are the same as using the append method. I also check passing of tuples. """ from aiida.orm.data.structure import StructureData from aiida.orm.data.parameter import ParameterData from aiida.orm.data import Data from aiida.orm.querybuilder import QueryBuilder from aiida.orm.group import Group from aiida.orm.computer import Computer g = Group(name='helloworld').store() for cls in (StructureData, ParameterData, Data): obj = cls() obj._set_attr('foo-qh2', 'bar') obj.store() g.add_nodes(obj) for cls, expected_count, subclassing in ( (StructureData, 1, True), (ParameterData, 1, True), (Data, 3, True), (Data, 1, False), ((ParameterData, StructureData), 2, True), ((ParameterData, StructureData), 2, False), ((ParameterData, Data), 2, False), ((ParameterData, Data), 3, True), ((ParameterData, Data, StructureData), 3, False), ): qb = QueryBuilder() qb.append(cls, filters={'attributes.foo-qh2': 'bar'}, subclassing=subclassing, project='uuid') self.assertEqual(qb.count(), expected_count) qh = qb.get_json_compatible_queryhelp() qb_new = QueryBuilder(**qh) self.assertEqual(qb_new.count(), expected_count) self.assertEqual(sorted([uuid for uuid, in qb.all()]), sorted([uuid for uuid, in qb_new.all()])) qb = QueryBuilder().append(Group, filters={'name': 'helloworld'}) self.assertEqual(qb.count(), 1) qb = QueryBuilder().append((Group, ), filters={'name': 'helloworld'}) self.assertEqual(qb.count(), 1) qb = QueryBuilder().append(Computer, ) self.assertEqual(qb.count(), 1) qb = QueryBuilder().append(cls=(Computer, )) self.assertEqual(qb.count(), 1)
def rehash(nodes, entry_point, force): """Recompute the hash for nodes in the database. The set of nodes that will be rehashed can be filtered by their identifier and/or based on their class. """ from aiida.orm import Data, ProcessNode, QueryBuilder if not force: echo.echo_warning( 'This command will recompute and overwrite the hashes of all nodes.' ) echo.echo_warning( 'Note that this can take a lot of time for big databases.') echo.echo_warning('') echo.echo_warning('', nl=False) confirm_message = 'Do you want to continue?' try: click.confirm(text=confirm_message, abort=True) except click.Abort: echo.echo('\n') echo.echo_critical( 'Migration aborted, the data has not been affected.') # If no explicit entry point is defined, rehash all nodes, which are either Data nodes or ProcessNodes if entry_point is None: entry_point = (Data, ProcessNode) if nodes: to_hash = [(node, ) for node in nodes if isinstance(node, entry_point)] num_nodes = len(to_hash) else: builder = QueryBuilder() builder.append(entry_point, tag='node') to_hash = builder.all() num_nodes = builder.count() if not to_hash: echo.echo_critical('no matching nodes found') with click.progressbar(to_hash, label='Rehashing Nodes:') as iter_hash: for node, in iter_hash: node.rehash() echo.echo_success('{} nodes re-hashed.'.format(num_nodes))
def get_subclass_from_uuid(cls, uuid): from aiida.orm.querybuilder import QueryBuilder from sqlalchemy.exc import DatabaseError try: qb = QueryBuilder() qb.append(cls, filters={'uuid': {'==': str(uuid)}}) if qb.count() == 0: raise NotExistent("No entry with UUID={} found".format(uuid)) node = qb.first()[0] if not isinstance(node, cls): raise NotExistent("UUID={} is not an instance of {}".format( uuid, cls.__name__)) return node except DatabaseError as de: raise ValueError(de.message)
#for queries examplefrom tutorial from aiida.orm.querybuilder import QueryBuilder qb=QueryBuilder() qb.all() qb.append(Node) qb.all() qb.count() #enumerate the <pk> for each query key for node, in qb.iterall(): print node #may need this line StructureData = DataFactory("structure") qb=QueryBuilder() qb.append(StructureData) #met le pk pour chaque structure si on met qb.all() qb.all()
path="/home/aiida/Documents/seb352-travail/essais-tuto/res/" StructureData = DataFactory("structure") ParameterData = DataFactory("parameter") #PwCalculation= DataFactory("calculation") qb=QueryBuilder() qb.append(ParameterData, project=["attributes.step0", "attributes.steps"], filters={"id":{"==":5615}} ) ok=0 a=qb.count() file=open(path+"results-parabola-dict", 'w') for i in qb.iterall(): file.write("{}\n\n{}\n\n{}\n\n{}".format(i[0],i[1][0],i[1][1],i[1][2])) ok+=1 print i[0]['dE'] print len(i[0]) file.close() new_dict={'0': i[0], '1': i[1][0], '2': i[1][1],'3' :i[1][2]} #print new_dict