Пример #1
0
 def test_pretty_print(self):
     """Test printing cuds objects in a human readable way."""
     c, p1, p2, p3, n1, n2, s1 = get_test_city()
     px = city.Person()
     c.add(px, rel=city.encloses)
     f = io.StringIO()
     pretty_print(c, file=f)
     self.maxDiff = 5000
     self.assertEqual(
         f.getvalue(), "\n".join([
             "- Cuds object named <Freiburg>:",
             "  uuid: %s" % c.uid, "  type: city.City",
             "  superclasses: city.City, city.GeographicalPlace, " +
             "city.PopulatedPlace, cuba.Entity",
             "  values: coordinates: [1 2]", "  description: ",
             "    To Be Determined", "", "   |_Relationship city.encloses:",
             "   | -  city.Person cuds object named <John Smith>:",
             "   |    uuid: %s" % px.uid, "   |    age: 25",
             "   |_Relationship city.hasInhabitant:",
             "   | -  city.Citizen cuds object named <Carlos>:",
             "   | .  uuid: %s" % p2.uid, "   | .  age: 25",
             "   | .   |_Relationship city.hasChild:",
             "   | .     -  city.Citizen cuds object named <Maria>:",
             "   | .        uuid: %s" % p3.uid, "   | .        age: 25",
             "   | -  city.Citizen cuds object named <Maria>:",
             "   | .  uuid: %s" % p3.uid, "   | .  (already printed)",
             "   | -  city.Citizen cuds object named <Rainer>:",
             "   |    uuid: %s" % p1.uid, "   |    age: 25",
             "   |     |_Relationship city.hasChild:",
             "   |       -  city.Citizen cuds object named <Maria>:",
             "   |          uuid: %s" % p3.uid,
             "   |          (already printed)",
             "   |_Relationship city.hasPart:",
             "     -  city.Neighborhood cuds object named <St. Georgen>:",
             "     .  uuid: %s" % n2.uid, "     .  coordinates: [3 4]",
             "     .   |_Relationship city.hasPart:",
             "     .     -  city.Street cuds object named <Lange Straße>:",
             "     .        uuid: %s" % s1.uid,
             "     .        coordinates: [4 5]",
             "     .         |_Relationship city.hasInhabitant:",
             "     .           -  city.Citizen cuds object named <Carlos>:",
             "     .           .  uuid: %s" % p2.uid,
             "     .           .  (already printed)",
             "     .           -  city.Citizen cuds object named <Maria>:",
             "     .              uuid: %s" % p3.uid,
             "     .              (already printed)",
             "     -  city.Neighborhood cuds object named <Zähringen>:",
             "        uuid: %s" % n1.uid, "        coordinates: [2 3]",
             "         |_Relationship city.hasPart:",
             "           -  city.Street cuds object named <Lange Straße>:",
             "              uuid: %s" % s1.uid,
             "              (already printed)", ""
         ]))
Пример #2
0
    def parseResults(self, jsonResults, root_cuds_object, synEntityToCUDSmap):
        """Given the results of a remote simulation in JSON form, this
        function parses them in to CUDS objects.

        Arguments:
            jsonResults        -- Remote simulation results
            root_cuds_object   -- Root CUDS object representing input data
            synEntityToCUDSmap -- Dictionary which stores a mapping between syntacitc (key) output
                                  representation that engine understands and the concrete CUDS
                                  instance that the it is associated with
        """

        # TODO - Should we expect the originally input CUDS objects to contain
        # placeholders for the output data, or do we need to generate and append
        # new CUDS objects for them?
        if jsonResults is None:
            print("No valid simulation results detected, session has failed.")
            self.successful = False
        else:
            # Use the CUDSAdaptor to fill CUDS objects with results
            CUDSAdaptor.toCUDS(jsonResults, synEntityToCUDSmap)
            print(
                "CUDS objects have now been populated with simulation results."
            )
            self.successful = True

        results = [
            res_dict[CUDS_BIND]
            for res_dict in list(synEntityToCUDSmap.values())
        ]

        if results is not None:
            if len(results) == 0:
                print("Could not find OUTPUT_RESULTS instance in CUDS")
            else:
                outputs_file = open("output_results.txt", "w")
                for result_item in results:
                    pretty_print(result_item, outputs_file)
                outputs_file.close()
                print(
                    "CUDS representation of results written to: ./output_results.txt"
                )

        else:
            print("Could not find CUDS results instances")

        # Mark as complete
        self.executed = True
Пример #3
0
    def _run(self, root_cuds_object):
        """Runs the AgentBridge class to execute a remote Kinetics simulation.

        Note that once CUDS data is passed into this method, it should be
        considered READ-ONLY by any calling code outside this wrapper.

        Arguments:
            root_cuds_object -- Root CUDS object representing input data
        """
        print("")
        print("===== Start: KineticsSession =====")

        # Save a copy of the CUDS inputs
        inputs_file = open("input_results.txt", "w")
        pretty_print(root_cuds_object, inputs_file)
        inputs_file.close()
        print("CUDS representation of inputs written to: ./input_results.txt")

        # Determine template from root CUDS object
        simulation_template = self._engine.determineTemplate(
            root_cuds_object, self.modelFlag)

        # Use the engine to generate JSON inputs
        jsonInputs, synEntityToCUDSmap = self._engine.generateJSON(
            root_cuds_object, simulation_template)

        # Run remote simulation (via AgentBridge)
        agentBridge = AgentBridge()
        jsonResult = agentBridge.runJob(json.dumps(jsonInputs))

        # Pass results (in JSON form) back to the engine for parsing
        self._engine.parseResults(jsonResult, root_cuds_object,
                                  synEntityToCUDSmap)

        print("===== End: KineticsSession =====")
        print("")
fd.add(QE.Volume(value = 33, unit = "au^3"))
sim2.add(QE.TotalEnergy(value = -432, unit = "Ry"))
 
with qeSession(root) as session:
    # Adds session to wrapper
    quantum_espresso_wrapper = QE.QEWrapper(session = session)
    # Adds simulation to wrapper
    sim = quantum_espresso_wrapper.add(sim)
    # pretty_print(sim)
    # Creates a qeUtil object and creates an input file based off of the simulation
    print("Running calculation...")
    # Runs the simulation 
    # pretty_print(quantum_espresso_wrapper)
    # pretty_print(quantum_espresso_wrapper)
    quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "scf", root = root)
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "bands")
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "bands.x", calculation_type = "")
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "relax", IONS = {'ion_dynamics': "'bfgs'"})
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pw.x", calculation_type = "scf", SYSTEM = {'occupations': "'tetrahedra'"})
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "dos.x", calculation_type = "")
    quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "pp.x", calculation_type = 9, PLOT = {"output_format": 6})
    # quantum_espresso_wrapper.session._run(simulation = [sim, sim2], prefix = 'si', command_type = "ev.x", calculation_type = '1')
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "ph.x", calculation_type = "")
    # quantum_espresso_wrapper.session._run(simulation = sim, prefix = "si", command_type = "plotband.x", calculation_type = "", params = {'Input file': 'si.bands.dat', 'Emin, Emax': "-6 17", "gnuplot": "gnuplot", "ps": "si.bands.ps", "Efermi": "0", "deltaE": "5 0"})
    pretty_print(sim)
    # pretty_print(sim2)
    # print("Results: ")
    # Pretty prints the simulation

Пример #5
0
    # THIS ALLOWS US TO SHOW THAT OSP-CORE CAN IMPORT ANY RDF DATA,
    # AND NOT ONLY DATA THAT WAS PREVIOUSLY EXPORTED BY OSP CORE!
    # THIS IS NOTHING THAT YOU AS A USER WOULD EVER HAVE TO DO.

    print("Replace UUID in turtle file")
    with open("test.rdf") as f1:
        with open("test2.rdf", "w", encoding="utf-8") as f2:
            for line in f1:
                match = uuid_re.match(line)
                if match:
                    uid = uuid.UUID(match[2])
                    line = line.replace(
                        match[1],
                        "http://city.com/" + session._registry.get(uid).name,
                    )
                print("\t", line, end="")
                print(line, end="", file=f2)

# Create new session and import file
with SqliteSession(path="test2.db") as session:
    w = city.CityWrapper(session=session)  # wrapper will be skipped for export
    import_cuds("test2.rdf", format="ttl", session=session)
    w.add(session.load_from_iri(URIRef("http://city.com/Freiburg")).one())
    print("Imported data:")
    pretty_print(w)

os.remove("test.db")
os.remove("test2.db")
os.remove("test.rdf")
os.remove("test2.rdf")
    print("Connect to DB via transport session")
    with TransportSessionClient(
        SqliteSession, "ws://localhost:8688", path="test.db"
    ) as session:
        wrapper = city.CityWrapper(session=session)
        wrapper.add(c)
        wrapper.session.commit()

    print("Reconnect and check if data is still there")
    with TransportSessionClient(
        SqliteSession, "ws://localhost:8688", path="test.db"
    ) as session:
        wrapper = city.CityWrapper(session=session)
        c = wrapper.get(oclass=city.City)[0]
        pretty_print(c)

    print("Reconnect and make some changes")
    with TransportSessionClient(
        SqliteSession, "ws://localhost:8688", path="test.db"
    ) as session:
        wrapper = city.CityWrapper(session=session)
        c = wrapper.get(oclass=city.City)[0]
        c.name = "Paris"
        wrapper.session.commit()

    print("Reconnect and check if changes were successful")
    with TransportSessionClient(
        SqliteSession, "ws://localhost:8688", path="test.db"
    ) as session:
        wrapper = city.CityWrapper(session=session)
Пример #7
0
"""This code runs on the wrapper under `../osp/wrappers/simple_simulation`"""

import numpy as np

from osp.core.namespaces import simple_ontology
from osp.core.utils import pretty_print
from osp.wrappers.simple_simulation import SimpleSimulationSession

m = simple_ontology.Material()
for i in range(3):
    a = m.add(simple_ontology.Atom())
    a.add(simple_ontology.Position(value=[i, i, i], unit="m"),
          simple_ontology.Velocity(value=np.random.random(3), unit="m/s"))

# Run a simulation
with SimpleSimulationSession() as session:
    w = simple_ontology.Wrapper(session=session)
    m = w.add(m)
    w.session.run()

    pretty_print(m)

    for atom in m.get(rel=simple_ontology.hasPart):
        atom.get(oclass=simple_ontology.Velocity)[0].value = [0, 0, 0]
    w.session.run()

    pretty_print(m)
Пример #8
0
    # create rectangle
    rec = Rectangle(temp_dir,
                    values={
                        'x': 20,
                        'y': 10,
                        'z': 150,
                        'filling_fraction': 0.5,
                        'resolution': 1
                    },
                    units={
                        'lengths': "mm",
                        'resolution': "mm"
                    },
                    session=session)

    wrapper.add(rec.get_model(), rel=emmo.hasPart)

    print("Run the GMSH computation:")
    session.run()

    # get the entity with the computed output
    computation = wrapper.get(oclass=emmo.MeshGeneration)

    # pretty print the output
    print("Generated meta data:")
    pretty_print(computation[0])

    # print information of generated .stl-file
    print(f"You can now review the files under {temp_dir}")
# We can go through inverse relationships
print(onto.get(rel=city.isPartOf)[0].name + ' is my city!')

# Working with a DB-wrapper: Store in the DB.
with SqlAlchemyWrapperSession(postgres_url) as session:
    wrapper = city.CityWrapper(session=session)
    wrapper.add(emmo_town)
    session.commit()

# Load from the DB.
with SqlAlchemyWrapperSession(postgres_url) as db_session:
    db_wrapper = city.CityWrapper(session=db_session)
    db_emmo_town = db_wrapper.get(emmo_town.uid)
    print("The database contains the following information about the city:")
    pretty_print(db_emmo_town)

    # Working with a Simulation wrapper
    with SimDummySession() as sim_session:
        sim_wrapper = city.CitySimWrapper(numSteps=1,
                                          session=sim_session)
        new_inhabitant = city.Person(age=31, name="Peter")
        sim_emmo_town, _ = sim_wrapper.add(db_emmo_town, new_inhabitant)
        sim_session.run()
        print("The city has a new inhabitant:")
        pretty_print(sim_emmo_town.get(new_inhabitant.uid))

    # update database
    db_wrapper.update(sim_emmo_town)
    db_session.commit()
Пример #10
0
"""An example explaining the use of the pretty_print function."""

# Please install the city ontology: $pico install city

from osp.core.namespaces import city
from osp.core.utils import pretty_print

# Let's build an EMMO compatible city!
emmo_town = city.City(name="EMMO town", coordinates=[42, 42])

emmo_town.add(city.Citizen(name="Emanuele Ghedini"), rel=city.hasInhabitant)
emmo_town.add(city.Citizen(name="Adham Hashibon"), rel=city.hasInhabitant)
emmo_town.add(
    city.Citizen(name="Jesper Friis"),
    city.Citizen(name="Gerhard Goldbeck"),
    city.Citizen(name="Georg Schmitz"),
    city.Citizen(name="Anne de Baas"),
    rel=city.hasInhabitant,
)

emmo_town.add(city.Neighborhood(name="Ontology"))
emmo_town.add(city.Neighborhood(name="User cases"))

ontology_uid = None
for neighborhood in emmo_town.get(oclass=city.Neighborhood):
    if neighborhood.name == "Ontology":
        ontology_uid = neighborhood.uid
        neighborhood.add(city.Street(name="Relationships"), rel=city.hasPart)
        neighborhood.add(city.Street(name="Entities"), rel=city.hasPart)
pretty_print(emmo_town)
Пример #11
0
                ["H", [1.14720, -0.93530, 0.00160]]]

# define the material by specifying atom symbols and cartesian coordinates, atom-by-atom
for atom_symbol, atom_coords in atoms_to_add:
    atom = material.add(cobramm.atom())
    atom.add(cobramm.position(vector_value=atom_coords, unit="Ang"))
    atom.add(cobramm.element_id(atom_symbol=atom_symbol))

# add other physical properties: temperature, pressure, solvent (with commercial name)
material.add(cobramm.temperature(scalar_value=300., unit="K"))
material.add(cobramm.pressure(scalar_value=1., unit="bar"))
material.add(cobramm.solvent(commercial_name="water"))

# pretty-print the material so far
print("\n")
pretty_print(material)
print("\n")

# now open a new CobrammSession to execute the simulation
with CobrammSession() as session:
    wrapper = cobramm.wrapper(session=session)
    material_wrapper = wrapper.add(material, rel=cobramm.has_part)

    # run the simulation
    material_wrapper.session.run()

    # extract the spectrum
    spectrum = material_wrapper.get(oclass=cobramm.spectrum)[0]

    # pretty-print the final spectrum
    print("\n")
Пример #12
0
                                         name='Temporal temperature gradient')
    temp_start = onto.Temperature(value=2000,
                                  unit='K',
                                  name='Start temperature')

    # Declaring and adding plasma composition
    comp = onto.Composition()
    arf = onto.MolarFraction(value=1, name='Ar', unit='~')
    h2f = onto.MolarFraction(value=0, name='H2', unit='~')
    n2f = onto.MolarFraction(value=0, name='N2', unit='~')
    comp.add(arf, h2f, n2f, rel=onto.hasPart)

    # Define the results CUDS
    Particles_Properties = onto.SizeDistribution(name='Particles')
    Primaries_Properties = onto.SizeDistribution(name='Primaries')

    # Define the user case in the wrapper (the high level wrapper)
    wrapper.add(pressure, accuracy_level, prec, comp, flow_rate,
                Particles_Properties, Primaries_Properties, temp_grad,
                temp_start)

    # Run the session for the defined case
    ##########################################################
    session.run()

    # Get the results
    Particles_Properties = wrapper.get(Particles_Properties.uid)
    pretty_print(Particles_Properties)
    Primaries_Properties = wrapper.get(Primaries_Properties.uid)
    pretty_print(Primaries_Properties)