Exemplo n.º 1
0
    def test_rule_sub(self):

        rules_text = """

            descendant(X, Y) :- offspring(X, Y).
            descendant(X, Z) :- offspring(X, Y), descendant(Y, Z).
            
            offspring(abraham, ishmael).
            offspring(abraham, isaac).
            offspring(isaac, esau).
            offspring(isaac, jacob).

        """

        query_text = """

            descendant(abraham, X).

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue(len(solutions.get("X")) == 4)

        self.assertTrue("ishmael" in str(solution)
                        for solution in solutions.get("X"))
        self.assertTrue("isaac" in str(solution)
                        for solution in solutions.get("X"))
        self.assertTrue("esau" in str(solution)
                        for solution in solutions.get("X"))
        self.assertTrue("jacob" in str(solution)
                        for solution in solutions.get("X"))
Exemplo n.º 2
0
    def test_multi_variable_solutions(self):

        rules_text = """

            is_tall(jack, yes).
            is_tall(eric, no).
            is_tall(johnny, yes).
            is_tall(mark, no).

        """

        query_text = """

            is_tall(Y, yes)

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue(len(solutions.get("Y")) == 2)

        self.assertTrue("jack" in str(solution)
                        for solution in solutions.get("Y"))
        self.assertTrue("johnny" in str(solution)
                        for solution in solutions.get("Y"))
Exemplo n.º 3
0
    def test_find_bad_dog(self):

        rules_text = """
            
            bad_dog(Dog) :-
               bites(Dog, Person),
               is_person(Person),
               is_dog(Dog).
            
            bites(fido, postman).
            is_person(postman).
            is_dog(fido).

        """

        query_text = """

            bad_dog( X )

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue(len(solutions.get("X")) == 1)

        self.assertTrue("fido" in str(solution)
                        for solution in solutions.get("X"))
Exemplo n.º 4
0
    def test_multiple_var_query(self):

        rules_text = """

            father(jack, susan).                            
            father(jack, ray).                             
            father(david, liza).                       
            father(david, john).                           
            father(john, peter).                
            father(john, mary).                     
            mother(karen, susan).                        
            mother(karen, ray).                              
            mother(amy, liza).                        
            mother(amy, john).                        
            mother(susan, peter).                            
            mother(susan, mary).                             
            
            parent(X, Y) :- father(X, Y).                    
            parent(X, Y) :- mother(X, Y).                    
            grandfather(X, Y) :- father(X, Z), parent(Z, Y).
            grandmother(X, Y) :- mother(X, Z), parent(Z, Y). 
            grandparent(X, Y) :- parent(X, Z), parent(Z, Y). 

        """

        query_text = """

            grandparent(X, Y)

        """

        solver = Solver(rules_text)
        solution_map = solver.find_solutions(query_text)
        solutions = list(zip(solution_map.get("X"), solution_map.get("Y")))

        self.assertTrue(len(solutions) == 8)

        self.assertTrue('(jack, peter)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(jack, mary)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(david, peter)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(david, mary)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(karen, peter)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(karen, mary)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(amy, peter)' in str(solution)
                        for solution in solutions)
        self.assertTrue('(amy, peter)' in str(solution)
                        for solution in solutions)
Exemplo n.º 5
0
def _test(n):
    input_path = pathlib.Path(current_dir / input_paths[n])
    expected_path = pathlib.Path(current_dir / expected_paths[n])

    solution = Solver(Parser(input_path)).solve()
    expected = Solver.to_string(
        [line for line in open(str(expected_path), 'r').read().splitlines()])

    assert solution == expected, 'Failed test_' + str(
        n) + ' -> ' + 'Expected:' + expected + ' != ' + 'Actual:' + solution
    print('Passed test_' + str(n) + ' -> ' + 'Expected:' + expected + ' == ' +
          'Actual:' + solution)
Exemplo n.º 6
0
    def run_query(self):

        # Delete all of the text in our solutions display text box
        self.solutions_display.delete('1.0', END)

        self.set_busy()

        # Fetch the raw rule / query text entered by the user
        rules_text = self.rule_editor.get(1.0, "end-1c")
        query_text = self.query_editor.get(1.0, "end-1c")

        # Create a new solver so we can try to query for solutions.
        try:
            solver = Solver(rules_text)
        except Exception as exception:
            self.handle_exception("Error processing prolog rules.", exception)
            return

        # Attempt to find the solutions and handle any exceptions gracefully
        try:
            solutions = solver.find_solutions(query_text)
        except Exception as exception:
            self.handle_exception("Error processing prolog query.", exception)
            return

        # If our query returns a boolean, we simply display a 'Yes' or a 'No' depending on its value
        if isinstance(solutions, bool):
            self.solutions_display.insert(END, 'Yes.' if solutions else 'No.')

        # Our solver returned a map, so we display the variable name to value mappings
        elif isinstance(solutions, dict):
            self.solutions_display.insert( END, "\n".join("{} = {}"
                                                        # If our solution is a list contining one item, we show that
                                                        # item, otherwise we display the entire list
                                                         .format(variable, value[0] if len(value) == 1 else value)
                                                         for variable, value
                                                         in solutions.items())
                                          )
        else:

            # We know we have no matching solutions in this instance so we provide relevant feedback
            self.solutions_display.insert(END, "No solutions found.")

        self.set_not_busy()
Exemplo n.º 7
0
    def test_simple_goal_query2(self):
        rules_text = """

            brother_sister(joe, monica).
            brother_sister(eric, erica).
            brother_sister(jim, rebecca).

        """

        goal_text = """

            brother_sister(joe, rebecca).

        """

        solver = Solver(rules_text)
        solution = solver.find_solutions(goal_text)

        self.assertFalse(solution)
Exemplo n.º 8
0
def paintshop_ide():
    import pathlib

    input_paths = [
        'input_0.txt', 'input_1.txt', 'input_2.txt', 'input_3.txt',
        'input_messy_formatting.txt'
    ]

    for input_path in input_paths:
        path = pathlib.Path(
            pathlib.Path(__file__).parent / 'test' / input_path)
        solution = Solver(Parser(path)).solve()
        print(solution)
Exemplo n.º 9
0
    def test_simple_variable_query(self):

        rules_text = """

            father_child(mike, john).
            father_child(eric, sarah).
            father_child(bob, jim).

        """

        query_text = """

            father_child(X, sarah).

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue(len(solutions.get("X")) == 1)

        self.assertEqual(str(solutions.get("X").pop()), "eric")
Exemplo n.º 10
0
    def test_rule_sub2(self):

        rules_text = """

            father_child(massimo, ridge).
            father_child(eric, thorne).
            father_child(thorne, alexandria).

            mother_child(stephanie, chloe).
            mother_child(stephanie, kristen).
            mother_child(stephanie, felicia).

            parent_child(X, Y) :- father_child(X, Y).
            parent_child(X, Y) :- mother_child(X, Y).

            sibling(X, Y) :- parent_child(Z, X), parent_child(Z, Y).

        """

        query_text = """

            sibling(X, felicia)

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue(len(solutions.get("X")) == 3)

        self.assertTrue("chloe" in str(solution)
                        for solution in solutions.get("X"))
        self.assertTrue("kristen" in str(solution)
                        for solution in solutions.get("X"))
        self.assertTrue("alexandria" in str(solution)
                        for solution in solutions.get("X"))
Exemplo n.º 11
0
def main():
    # ----- Setup ----- #
    # Simulation parameters
    Nx = 30
    duration = 3.0
    height = 1.0
    width = 1.0

    # Other parameters
    rho0 = 1000.0
    XSPH = False
    plot = True

    # Create some particles
    r0, pA = create_particles(Nx, rho0, width, height)

    # Create the solver
    kernel = CubicSpline()
    method = WCSPH(height=height, rho0=rho0, r0=r0, useXSPH=XSPH, Pb=0)
    integrator = PEC(useXSPH=XSPH, strict=False)
    solver = Solver(method,
                    integrator,
                    kernel,
                    duration,
                    quick=False,
                    incrementalWriteout=False,
                    exportProperties=['x', 'y', 'p', 'vx', 'vy'])

    # Add the particles
    solver.addParticles(pA)

    # Setup
    solver.setup()

    # ----- Run ----- #
    solver.run()

    # ----- Post ----- #
    # Output timing
    solver.timing()

    # Output
    exportPath = f'{sys.path[0]}/containment.hdf5'
    solver.save(exportPath)

    if plot == True:
        plt = Plot(exportPath,
                   title=f'Containment (2D); {len(pA)} particles',
                   xmin=-0.2,
                   xmax=1.2,
                   ymin=-0.2,
                   ymax=1.2)
        plt.save(f'{sys.path[0]}/containment.mp4')
Exemplo n.º 12
0
def main():
    # ----- Setup ----- #
    # Simulation parameters
    duration = 5.0  # Duration of the simulation [s]
    height = 10.0  # Height of the fluid box [m]
    width = 60.0  # Width of the fluid box [m]
    compress = 1.0  # (vertical) compression factor [-]

    # Computed parameters
    ice_max = width / 2.0

    # Coupling object
    P = {'g': 9.81, 'L_interface': [], 'F_a': [], 'Pressure': [], 'F_r': []}

    # Other parameters
    rho0 = 1025.0
    XSPH = True
    print('Three different models are implemented.')
    print(
        '0. A cantilever beam, with a static force on the end, above the water.'
    )
    print(
        '1. An short sheet of ice (cantilever beam) floating on water without any force.'
    )
    print(
        '2. An long sheet of ice (cantilever beam) floating on water without any force.'
    )
    print('3. --')
    print('4. The ice-sheet above the water.')
    print('5. The scaled ice-sheet model (Valanto, 1992).')
    print('6. Full scale model (Keijdener, 2018).')
    P['model'] = int(input('Select model: '))
    plot = input('Create animation after solving? (y/n) ').lower() == 'y'

    if P['model'] > 6 or P['model'] < 0:
        raise 'Invalid model selected'

    if P['model'] == 5:
        height = 1.0
        width = 2.0
        ice_max = 1.0

    Nx = int(input('Number of particles in x-direction (100 > N > 10): '))
    # if Nx > 500 or Nx < 10:
    # raise 'Invalid number of particles.'

    # Create some particles
    y00, r0, pA = create_particles(Nx, rho0, width, height, ice_max, P,
                                   compress)
    P['y0'] = y00

    # -- Create matrix -- #
    # Beam/Ice properties
    L = ice_max + r0  # Total Length [m]; one third overlap with water, two thirds to the left.
    b = 1  # Width of the beam [m]
    h = 1  # Height of the beam [m]
    v = 0.3  # Poisson ratio [-]
    P['alpha'] = 15 / 180 * np.pi  # Angle of the hull [rad]
    P['ice_v'] = 0.2  # Velocity of the ice-sheet [m/s]
    P['ice_fy_comp'] = 11e3  # Compressive strength of the ice [Pa]
    P['m2_stiffness'] = 15e5  # Rigid spring stiffness [N/m]
    P['b'] = b

    # General properties
    if P['model'] in [0]:
        E = 200e9
        rho = 7800
        h = 1 / 33.33
    elif P['model'] in [1, 2]:
        E = 140e6
        rho = 916.0
        duration = 1.0
        if P['model'] == 1:
            L = 2 * ice_max
        elif P['model'] == 2:
            L = 5 * ice_max
    elif P['model'] in [5]:
        duration = 1.5
        L = 5 * ice_max
        h = 1 / 33.33
        b = 0.34
        P['b'] = b
        E = 140e6  # Young's Modulus [Pa]
        rho = 916.0
    elif P['model'] in [6]:
        L = 1.9 * ice_max
        P['ice_v'] = float(input('Ice velocity: '))
        duration = float(input('Duration: '))
        E = 5e9 / (1 - v**2)
        P['ice_fy_comp'] = 6E5
        P['m2_stiffness'] = 50 * P['ice_fy_comp']
        P['alpha'] = 45 / 180 * np.pi
        rho = 925.0

    # Ice-penetration
    P['mode'] = 1  # Start in crushing mode.
    P['penetration'] = [0]  # Start with zero penetration.
    P['t_trans'] = 0  # Transition time [s]
    P['hh'] = h / 2

    # Compute one-time dynamic h.
    P['h'] = 1.6 * r0

    # Compute properties
    n = len(pA[pA['label'] == ParticleType.Coupled])  # Number of Nodes [-]
    A = b * h  # Area [m^3]
    I = 1 / 12 * b * h**3  # Area moment of Inertia [kg/m^3]
    P['L_n'] = L / n  # Node length [m]
    P['m'] = rho * A  # Nodal mass [kg/m]

    # Assign some props
    P['E'] = E
    P['pois'] = v

    # Compute stiffness and mass matrices
    K, M = createMatrix(n, E, I, A, rho, P['L_n'])

    # Set mass
    pA[pA['label'] == ParticleType.Coupled]['m'] = P['m']

    # Compute damping matrix
    xi = 2e1  # Damping factor [-]
    c_crit = np.sqrt(rho * A * rho0 * P['g'])  # Critical damping factor [-]
    C = np.eye(n) * 2 * xi * c_crit  # Damping matrix [N/s]

    # Create the solver
    newmark = NewmarkBeta(beta=1 / 4, gamma=1 / 2, M=M, K=K, C=C)
    kernel = Wendland()
    method = WCSPH(height=height,
                   rho0=rho0,
                   r0=r0,
                   useXSPH=XSPH,
                   Pb=0,
                   useSummationDensity=False)
    integrator = PEC(useXSPH=XSPH, strict=False)
    solver = Solver(method,
                    integrator,
                    kernel,
                    duration,
                    quick=False,
                    damping=0.0,
                    incrementalWriteout=False,
                    maxSettle=1800,
                    customSettle=custom_settling,
                    exportProperties=['x', 'y', 'p', 'rho'],
                    coupling=coupling,
                    couplingIntegrator=newmark,
                    couplingProperties=P,
                    timeStep=None)

    # Add the particles
    solver.addParticles(pA)

    # Setup
    solver.setup()

    # ----- Run ----- #
    solver.run()

    # ----- Post ----- #
    # Output timing
    solver.timing()

    # Output
    exportPath = '{0}/IceBreak-{1}.hdf5'.format(sys.path[0], P['model'])
    solver.save(exportPath, True, solver.couplingProperties)

    # Create an animation.
    if plot == True:
        title = 'IceBreak (2D); {0} particles'.format(len(pA))
        plt = Plot(exportPath,
                   title=title,
                   xmin=-1,
                   xmax=width + 2 * r0,
                   ymin=-2 * r0,
                   ymax=height * 1.3 + 2 * r0)
        plt.save('{0}/IceBreak-{1}.mp4'.format(sys.path[0], P['model']))

    # Load the file and determine breaking length
    post(exportPath)
Exemplo n.º 13
0
def paintshop_console(args):
    for path in args:
        solution = Solver(Parser(path)).solve()
        print(solution)
Exemplo n.º 14
0
from src.Solver import Solver
import pandas as pd

if __name__ == "__main__":
    with open('examples/logical_rules', 'r') as content_file:
        content = content_file.read()
    solver = Solver(content)
    print(solver.database)
    while True:
        inp = input("запрос> ")
        solution = solver.find_solutions(inp)
        if isinstance(solution, dict):
            print(pd.DataFrame.from_dict(solution))
        else:
            print(solution)
Exemplo n.º 15
0
    parser.add_argument("--lr", type=float, help="learning rate", default=1e-3)
    parser.add_argument("--weight_decay",
                        type=float,
                        help="weight decay",
                        default=1e-4)
    parser.add_argument('--num_points',
                        type=int,
                        default=4096,
                        help='Point Number [default: 4096]')
    parser.add_argument('--no_augment',
                        action='store_true',
                        help='Do NOT use height signal in input.')
    parser.add_argument('--use_color',
                        action='store_true',
                        help='Use RGB color in input.')
    args = parser.parse_args()

    solver = Solver(args)

    train_dataloader = DataLoader(solver.train_dataset,
                                  batch_size=4,
                                  shuffle=True)
    tnrange = tqdm(enumerate(train_dataloader),
                   total=len(train_dataloader),
                   desc='Train')
    phrase = 'train'

    for i, sample in tnrange:
        solver._run_iter(sample, phrase)
        break
Exemplo n.º 16
0
def main(args):

    solver = Solver(args)
    ### Training
    solver.train()
Exemplo n.º 17
0
    def test_einstein_puzzle(self):

        rules_text = """ 

            exists(A, list(A, _, _, _, _)).
            exists(A, list(_, A, _, _, _)).
            exists(A, list(_, _, A, _, _)).
            exists(A, list(_, _, _, A, _)).
            exists(A, list(_, _, _, _, A)).
            
            rightOf(R, L, list(L, R, _, _, _)).
            rightOf(R, L, list(_, L, R, _, _)).
            rightOf(R, L, list(_, _, L, R, _)).
            rightOf(R, L, list(_, _, _, L, R)).
            
            middle(A, list(_, _, A, _, _)).
            
            first(A, list(A, _, _, _, _)).
            
            nextTo(A, B, list(B, A, _, _, _)).
            nextTo(A, B, list(_, B, A, _, _)).
            nextTo(A, B, list(_, _, B, A, _)).
            nextTo(A, B, list(_, _, _, B, A)).
            nextTo(A, B, list(A, B, _, _, _)).
            nextTo(A, B, list(_, A, B, _, _)).
            nextTo(A, B, list(_, _, A, B, _)).
            nextTo(A, B, list(_, _, _, A, B)).

            puzzle(Houses) :-
                  exists(house(red, english, _, _, _), Houses),
                  exists(house(_, spaniard, _, _, dog), Houses),
                  exists(house(green, _, coffee, _, _), Houses),
                  exists(house(_, ukrainian, tea, _, _), Houses),
                  rightOf(house(green, _, _, _, _), 
                  house(ivory, _, _, _, _), Houses),
                  exists(house(_, _, _, oldgold, snails), Houses),
                  exists(house(yellow, _, _, kools, _), Houses),
                  middle(house(_, _, milk, _, _), Houses),
                  first(house(_, norwegian, _, _, _), Houses),
                  nextTo(house(_, _, _, chesterfield, _), house(_, _, _, _, fox), Houses),
                  nextTo(house(_, _, _, kools, _),house(_, _, _, _, horse), Houses),
                  exists(house(_, _, orangejuice, luckystike, _), Houses),
                  exists(house(_, japanese, _, parliament, _), Houses),
                  nextTo(house(_, norwegian, _, _, _), house(blue, _, _, _, _), Houses),
                  exists(house(_, _, water, _, _), Houses),
                  exists(house(_, _, _, _, zebra), Houses).

            solution(WaterDrinker, ZebraOwner) :-
                  puzzle(Houses),
                  exists(house(_, WaterDrinker, water, _, _), Houses),
                  exists(house(_, ZebraOwner, _, _, zebra), Houses).

        """

        query_text = """

            solution(WaterDrinker, ZebraOwner)

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue("norwegian" in str(solution)
                        for solution in solutions.get("WaterDrinker"))
        self.assertTrue("japanese" in str(solution)
                        for solution in solutions.get("ZebraOwner"))
Exemplo n.º 18
0
    def test_alternate_einstein_puzzle(self):

        rules_text = """ 

            exists(A, list(A, _, _, _, _)).
            exists(A, list(_, A, _, _, _)).
            exists(A, list(_, _, A, _, _)).
            exists(A, list(_, _, _, A, _)).
            exists(A, list(_, _, _, _, A)).

            rightOf(R, L, list(L, R, _, _, _)).
            rightOf(R, L, list(_, L, R, _, _)).
            rightOf(R, L, list(_, _, L, R, _)).
            rightOf(R, L, list(_, _, _, L, R)).

            middle(A, list(_, _, A, _, _)).

            first(A, list(A, _, _, _, _)).

            nextTo(A, B, list(B, A, _, _, _)).
            nextTo(A, B, list(_, B, A, _, _)).
            nextTo(A, B, list(_, _, B, A, _)).
            nextTo(A, B, list(_, _, _, B, A)).
            nextTo(A, B, list(A, B, _, _, _)).
            nextTo(A, B, list(_, A, B, _, _)).
            nextTo(A, B, list(_, _, A, B, _)).
            nextTo(A, B, list(_, _, _, A, B)).

            puzzle(Houses) :-
                  exists(house(red, british, _, _, _), Houses),
                  exists(house(_, swedish, _, _, dog), Houses),
                  exists(house(green, _, coffee, _, _), Houses),
                  exists(house(_, danish, tea, _, _), Houses),
                  rightOf(house(white, _, _, _, _), house(green, _, _, _, _), Houses),
                  exists(house(_, _, _, pall_mall, bird), Houses),
                  exists(house(yellow, _, _, dunhill, _), Houses),
                  middle(house(_, _, milk, _, _), Houses),
                  first(house(_, norwegian, _, _, _), Houses),
                  nextTo(house(_, _, _, blend, _), house(_, _, _, _, cat), Houses),
                  nextTo(house(_, _, _, dunhill, _),house(_, _, _, _, horse), Houses),
                  exists(house(_, _, beer, bluemaster, _), Houses),
                  exists(house(_, german, _, prince, _), Houses),
                  nextTo(house(_, norwegian, _, _, _), house(blue, _, _, _, _), Houses),
                  nextTo(house(_, _, _, blend, _), house(_, _, water_, _, _), Houses).

            solution(FishOwner) :-
              puzzle(Houses),
              exists(house(_, FishOwner, _, _, fish), Houses).

        """

        query_text = """

            solution(FishOwner)

        """

        solver = Solver(rules_text)
        solutions = solver.find_solutions(query_text)

        self.assertTrue(len(solutions.get("FishOwner")) == 1)

        self.assertTrue("german" in str(solution)
                        for solution in solutions.get("FishOwner"))