コード例 #1
0
def test_derived_level_validation():
    DerivedLevel(42, WithinTrial(op.eq, [color, text]))
    DerivedLevel("name", WithinTrial(lambda x: x, [color]))

    # Invalid Window
    with pytest.raises(ValueError):
        DerivedLevel("name", 42)
コード例 #2
0
def __get_response_transition() -> Factor:
    color = Factor("color", ["red", "blue", "green"])
    motion = Factor("motion", ["up", "down"])
    task = Factor("task", ["color", "motion"])

    # Response Definition
    def response_left(task, color, motion):
        return (task == "color"  and color  == "red") or \
            (task == "motion" and motion == "up")

    def response_right(task, color, motion):
        return not response_left(task, color, motion)

    response = Factor("response", [
        DerivedLevel("left", WithinTrial(response_left,
                                         [task, color, motion])),
        DerivedLevel("right", WithinTrial(response_right,
                                          [task, color, motion]))
    ])

    return Factor("response transition", [
        DerivedLevel(
            "repeat",
            Transition(lambda responses: responses[0] == responses[1],
                       [response])),
        DerivedLevel(
            "switch",
            Transition(lambda responses: responses[0] != responses[1],
                       [response]))
    ])
コード例 #3
0
def test_fully_cross_block_crossing_size_with_overlapping_exclude():
    # How about with two overlapping exclude constraints? Initial crossing size
    # should be 3 x 3 = 9.
    # Excluding congruent pairs will reduce that to 9 - 3 = 6
    # Then excluding red and green on top of that should make it 5.
    color = Factor("color", ["red", "blue", "green"])
    text = Factor("text", ["red", "blue", "green"])

    congruent_factor = Factor("congruent?", [
        DerivedLevel("congruent", WithinTrial(op.eq, [color, text])),
        DerivedLevel("incongruent", WithinTrial(op.ne, [color, text])),
    ])

    def illegal(color, text):
        return (color == "red" and text == "green") or color == text

    def legal(color, text):
        return not illegal(color, text)

    legal_factor = Factor("legal", [
        DerivedLevel("yes", WithinTrial(legal, [color, text])),
        DerivedLevel("no", WithinTrial(illegal, [color, text]))
    ])

    assert FullyCrossBlock(
        [color, text, congruent_factor, legal_factor],
        [[color, text]],
        [
            Exclude(congruent_factor,
                    get_level_from_name(congruent_factor,
                                        "congruent")),  # Excludes 3
            Exclude(legal_factor, get_level_from_name(legal_factor, "no"))
        ],  # Exludes 4, but 3 were already excluded
        require_complete_crossing=False).crossing_size() == 5
コード例 #4
0
def test_consistency_with_transition_first_and_uneven_level_lengths():
    color3 = Factor("color3", ["red", "blue", "green"])

    yes_fn = lambda colors: colors[0] == colors[1] == colors[2]
    no_fn = lambda colors: not yes_fn(colors)
    color3_repeats_factor = Factor("color3 repeats?", [
        DerivedLevel("yes", Window(yes_fn, [color3], 3, 1)),
        DerivedLevel("no", Window(no_fn, [color3], 3, 1))
    ])

    block = fully_cross_block([color3_repeats_factor, color3, text],
                              [color3, text], [])

    backend_request = BackendRequest(0)
    Consistency.apply(block, backend_request)

    assert backend_request.ll_requests == [
        LowLevelRequest("EQ", 1, [1, 2, 3]),
        LowLevelRequest("EQ", 1, [4, 5]),
        LowLevelRequest("EQ", 1, [6, 7, 8]),
        LowLevelRequest("EQ", 1, [9, 10]),
        LowLevelRequest("EQ", 1, [11, 12, 13]),
        LowLevelRequest("EQ", 1, [14, 15]),
        LowLevelRequest("EQ", 1, [16, 17, 18]),
        LowLevelRequest("EQ", 1, [19, 20]),
        LowLevelRequest("EQ", 1, [21, 22, 23]),
        LowLevelRequest("EQ", 1, [24, 25]),
        LowLevelRequest("EQ", 1, [26, 27, 28]),
        LowLevelRequest("EQ", 1, [29, 30]),
        LowLevelRequest("EQ", 1, [31, 32]),
        LowLevelRequest("EQ", 1, [33, 34]),
        LowLevelRequest("EQ", 1, [35, 36]),
        LowLevelRequest("EQ", 1, [37, 38])
    ]
コード例 #5
0
def test_generate_encoding_diagram_with_window_with_stride():
    congruent_bookend = Factor("congruent bookend?", [
        DerivedLevel("yes", Window(lambda colors, texts: colors[0] == texts[0], [color, text], 1, 3)),
        DerivedLevel("no",  Window(lambda colors, texts: colors[0] != texts[0], [color, text], 1, 3))
    ])

    block = fully_cross_block([color, text, congruent_bookend], [color, text], [])

    assert __generate_encoding_diagram(block) == "\
------------------------------------------------------\n\
|   Trial |  color   |   text   | congruent bookend? |\n\
|       # | red blue | red blue |    yes       no    |\n\
------------------------------------------------------\n\
|       1 |  1   2   |  3   4   |    17        18    |\n\
|       2 |  5   6   |  7   8   |                    |\n\
|       3 |  9   10  | 11   12  |                    |\n\
|       4 | 13   14  | 15   16  |    19        20    |\n\
------------------------------------------------------\n"

    congruent_bookend = Factor("congruent bookend?", [
        DerivedLevel("yes", Window(lambda colors, texts: colors[0] == texts[0], [color, text], 2, 2)),
        DerivedLevel("no",  Window(lambda colors, texts: colors[0] != texts[0], [color, text], 2, 2))
    ])

    block = fully_cross_block([color, text, congruent_bookend], [color, text], [])

    assert __generate_encoding_diagram(block) == "\
コード例 #6
0
def test_generate_derivations_within_trial():
    assert DerivationProcessor.generate_derivations(blk) == [
        Derivation(4, [[0, 2], [1, 3]], con_factor),
        Derivation(5, [[0, 3], [1, 2]], con_factor)
    ]

    integer = Factor("integer", ["1", "2"])
    numeral = Factor("numeral", ["I", "II"])
    text = Factor("text", ["one", "two"])

    twoConLevel = DerivedLevel("twoCon",
                               WithinTrial(two_con, [integer, numeral, text]))
    twoNotConLevel = DerivedLevel(
        "twoNotCon", WithinTrial(two_not_con, [integer, numeral, text]))
    two_con_factor = Factor("twoCon?", [twoConLevel, twoNotConLevel])

    one_two_design = [integer, numeral, text, two_con_factor]
    one_two_crossing = [integer, numeral, text]

    assert DerivationProcessor.generate_derivations(
        fully_cross_block(one_two_design, one_two_crossing, [])) == [
            Derivation(6,
                       [[0, 2, 5], [0, 3, 4], [0, 3, 5], [1, 2, 4], [1, 2, 5],
                        [1, 3, 4]], two_con_factor),
            Derivation(7, [[0, 2, 4], [1, 3, 5]], two_con_factor)
        ]
コード例 #7
0
def test_generate_derivations_should_raise_error_if_some_factor_matches_multiple_levels(
):
    local_con_factor = Factor("congruent?", [
        DerivedLevel("con", WithinTrial(op.eq, [color, text])),
        DerivedLevel("inc", WithinTrial(op.eq, [color, text]))
    ])

    with pytest.raises(ValueError):
        fully_cross_block([color, text, local_con_factor], [color, text], [])
コード例 #8
0
def test_generate_derivations_should_produce_warning_if_some_level_is_unreachable(capsys):
    local_con_factor = Factor("congruent?", [
        DerivedLevel("con", WithinTrial(op.eq, [color, text])),
        DerivedLevel("inc", WithinTrial(op.ne, [color, text])),
        DerivedLevel("dum", WithinTrial(lambda c, t: c=='green', [color, text]))
    ])
    fully_cross_block([color, text, local_con_factor],
                      [color, text],
                      [])
    assert capsys.readouterr().out == "WARNING: There is no assignment that matches factor congruent? with level dum.\n"
コード例 #9
0
def test_derived_level_validation():
    # Non-str name
    with pytest.raises(ValueError):
        DerivedLevel(42, WithinTrial(op.eq, [color, text]))

    # Invalid Window
    with pytest.raises(ValueError):
        DerivedLevel("name", 42)

    # Repeated factors in argument list.
    with pytest.raises(ValueError):
        DerivedLevel("name", WithinTrial(lambda x: x, [color, color]))
コード例 #10
0
def __build_stroop_block(color_count):
    color = Factor("color", color_list[:color_count])
    text = Factor("text", color_list[:color_count])

    congruent = Factor("congruent?", [
        DerivedLevel("yes", WithinTrial(op.eq, [color, text])),
        DerivedLevel("no",  WithinTrial(op.ne, [color, text]))
    ])

    constraints = [AtMostKInARow(1, ("congruent?", "yes"))]

    return fully_cross_block([color, text, congruent], [color, text], constraints)
コード例 #11
0
def test_generate_derivations_should_raise_error_if_fn_doesnt_return_a_boolean():
    def local_eq(color, text):
            color == text # Notice the missing return stmt

    local_con_factor = Factor("congruent?", [
        DerivedLevel("con", WithinTrial(local_eq, [color, text])),
        DerivedLevel("inc", WithinTrial(lambda c, t: not local_eq(c, t), [color, text]))
    ])

    with pytest.raises(ValueError):
        fully_cross_block([color, text, local_con_factor],
                          [color, text],
                          [])
コード例 #12
0
def test_generate_encoding_diagram_with_windows():
    color3 = Factor("color3", ["red", "blue", "green"])

    yes_fn = lambda colors: colors[0] == colors[1] == colors[2]
    no_fn = lambda colors: not yes_fn(colors)
    color3_repeats_factor = Factor("color3 repeats?", [
        DerivedLevel("yes", Window(yes_fn, [color3], 3, 1)),
        DerivedLevel("no",  Window(no_fn, [color3], 3, 1))
    ])

    block = fully_cross_block([color3_repeats_factor, color3, text], [color3, text], [])

    assert __generate_encoding_diagram(block) == "\
コード例 #13
0
def test_generate_sample_basic_stroop_uneven_colors(sequence_number, expected_solution):
    text = Factor("text", ["red", "blue", "green"])
    congruency = Factor("congruency", [
        DerivedLevel("congruent",   WithinTrial(op.eq, [color, text])),
        DerivedLevel("incongruent", WithinTrial(op.ne, [color, text]))
    ])

    block = fully_cross_block([color, text, congruency],
                              [color, congruency],
                              [])
    enumerator = UCSolutionEnumerator(block)
    print(enumerator.generate_sample(sequence_number))
    assert enumerator.generate_sample(sequence_number) == expected_solution
コード例 #14
0
def test_factor_validation():
    Factor("factor name", ["level 1", "level 2"])

    # Non-string name
    with pytest.raises(ValueError):
        Factor(56, ["level "])

    # Non-list levels
    with pytest.raises(ValueError):
        Factor("name", 42)

    # Empty list
    with pytest.raises(ValueError):
        Factor("name", [])

    # Invalid level type
    with pytest.raises(ValueError):
        Factor("name", [1, 2])

    # Valid level types, but not uniform.
    with pytest.raises(ValueError):
        Factor("name", ["level1", con_level])

    # Derived levels with non-uniform window types
    with pytest.raises(ValueError):
        Factor("name", [
            con_level,
            DerivedLevel(
                "other",
                Transition(lambda colors: colors[0] == colors[1], [color]))
        ])
コード例 #15
0
 def extract_simplelevel(self, block: Block, level: DerivedLevel) -> List[Dict[Factor, SimpleLevel]]:
     """Recursively deciphers the excluded level to a list of combinations
     basic levels."""
     excluded_levels = []
     excluded: List[Tuple[Level, ...]] = [cross for cross in level.get_dependent_cross_product()
                                          if level.window.predicate(*[level.name for level in cross])]
     for excluded_level_tuple in excluded:
         combos: List[Dict[Factor, SimpleLevel]] = [{}]
         for excluded_level in excluded_level_tuple:
             if isinstance(excluded_level, DerivedLevel):
                 result = self.extract_simplelevel(block, excluded_level)
                 newcombos = []
                 valid = True
                 for r in result:
                     for c in combos:
                         for f in c:
                             if f in r:
                                 if c[f] != r[f]:
                                     valid = False
                     if valid:
                         newcombos.append({**r, **c})
                 combos = newcombos
             else:
                 if not isinstance(excluded_level, SimpleLevel):
                     raise ValueError(f"Unexpected level type in exclusion: level {level.name} of type "
                                      f"{type(level).__name__}.")
                 for c in combos:
                     if block.factor_in_crossing(excluded_level.factor) and block.require_complete_crossing:
                         block.errors.add("WARNING: Some combinations have been excluded, this crossing may not be complete!")
                     c[excluded_level.factor] = excluded_level
         excluded_levels.extend(combos)
     return excluded_levels
コード例 #16
0
def test_base_window_validation():
    # Nonfactor argument
    with pytest.raises(ValueError):
        WithinTrial(op.eq, [42])

    # Duplicated factors
    with pytest.raises(ValueError):
        DerivedLevel("name", WithinTrial(lambda x, y: x, [color, color]))
コード例 #17
0
def test_factor_validation():
    Factor("factor name", ["level 1", "level 2"])
    Factor("name", [1, 2])

    # Duplicated name
    with pytest.raises(ValueError):
        Factor("name", ["a", "b", "a"])
    with pytest.raises(ValueError):
        Factor("name", [
            DerivedLevel("a", WithinTrial(op.eq, [color, text])),
            ElseLevel("a")
        ])

    # Non-string name
    with pytest.raises(ValueError):
        Factor(56, ["level "])

    # Non-list levels
    with pytest.raises(TypeError):
        Factor("name", 42)

    # Empty list
    with pytest.raises(ValueError):
        Factor("name", [])

    # Valid level types, but not uniform.
    with pytest.raises(ValueError):
        Factor("name", ["level1", con_level])

    # Derived levels with non-uniform window types
    with pytest.raises(ValueError):
        Factor("name", [
            con_level,
            DerivedLevel("other", WithinTrial(lambda color: color, [color]))
        ])

    # Derived levels with different window arguments
    with pytest.raises(ValueError):
        Factor("name", [
            con_level,
            DerivedLevel(
                "other",
                Transition(lambda colors: colors[0] == colors[1], [color]))
        ])
コード例 #18
0
def test_generate_argument_list_with_transition():
    color_repeats_level = DerivedLevel(
        "yes", Transition(lambda colors: colors[0] == colors[1], [color]))
    x_product = color_repeats_level.get_dependent_cross_product()

    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[0]) == [['red', 'red']]
    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[1]) == [['red', 'blue']]
    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[2]) == [['blue', 'red']]
    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[3]) == [['blue', 'blue']]

    double_repeat_level = DerivedLevel(
        "name", Transition(lambda colors, texts: True, [color, text]))
    x_product = double_repeat_level.get_dependent_cross_product()

    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[0]) == [['red', 'red'], ['red', 'red']]
    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[1]) == [['red', 'red'], ['red', 'blue']]
    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[2]) == [['red', 'red'], ['blue', 'red']]
    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[3]) == [['red', 'red'],
                                               ['blue', 'blue']]

    assert DerivationProcessor.generate_argument_list(
        color_repeats_level, x_product[15]) == [['blue', 'blue'],
                                                ['blue', 'blue']]
コード例 #19
0
def test_exclude_with_reduced_crossing():
    color = Factor("color", ["red", "blue", "green"])
    text = Factor("text", ["red", "blue"])

    def illegal_stimulus(color, text):
        return color == "green" and text == "blue"

    def legal_stimulus(color, text):
        return not illegal_stimulus(color, text)

    stimulus_configuration = Factor("stimulus configuration", [
        DerivedLevel("legal", WithinTrial(legal_stimulus, [color, text])),
        DerivedLevel("illegal", WithinTrial(illegal_stimulus, [color, text]))
    ])

    c = Exclude(stimulus_configuration,
                get_level_from_name(stimulus_configuration, "illegal"))
    block = fully_cross_block([color, text, stimulus_configuration],
                              [color, text], [c],
                              require_complete_crossing=False)

    backend_request = BackendRequest(0)
    c.apply(block, backend_request)
    assert backend_request.cnfs == [And([-7, -14, -21, -28, -35])]
コード例 #20
0
def test_derivation_with_three_level_transition():
    f = Factor("f", ["a", "b", "c"])
    f_transition = Factor("transition", [
        DerivedLevel("aa",
                     Transition(lambda c: c[0] == "a" and c[1] == "a", [f])),
        DerivedLevel("ab",
                     Transition(lambda c: c[0] == "a" and c[1] == "b", [f])),
        DerivedLevel("ac",
                     Transition(lambda c: c[0] == "a" and c[1] == "c", [f])),
        DerivedLevel("ba",
                     Transition(lambda c: c[0] == "b" and c[1] == "a", [f])),
        DerivedLevel("bb",
                     Transition(lambda c: c[0] == "b" and c[1] == "b", [f])),
        DerivedLevel("bc",
                     Transition(lambda c: c[0] == "b" and c[1] == "c", [f])),
        DerivedLevel("ca",
                     Transition(lambda c: c[0] == "c" and c[1] == "a", [f])),
        DerivedLevel("cb",
                     Transition(lambda c: c[0] == "c" and c[1] == "b", [f])),
        DerivedLevel("cc",
                     Transition(lambda c: c[0] == "c" and c[1] == "c", [f])),
    ])

    block = fully_cross_block([f, f_transition], [f], [])

    # a-a derivation
    d = Derivation(9, [[0, 3]], f_transition)
    backend_request = BackendRequest(28)
    d.apply(block, backend_request)

    (expected_cnf, expected_fresh) = to_cnf_tseitin(
        And([Iff(10, Or([And([1, 4])])),
             Iff(19, Or([And([4, 7])]))]), 28)

    assert backend_request.fresh == expected_fresh
    assert backend_request.cnfs == [expected_cnf]
コード例 #21
0
def test_factor_applies_to_trial():
    assert color.applies_to_trial(1) == True
    assert color.applies_to_trial(2) == True
    assert color.applies_to_trial(3) == True
    assert color.applies_to_trial(4) == True

    with pytest.raises(ValueError):
        color.applies_to_trial(0)

    assert color_repeats_factor.applies_to_trial(1) == False
    assert color_repeats_factor.applies_to_trial(2) == True
    assert color_repeats_factor.applies_to_trial(3) == True
    assert color_repeats_factor.applies_to_trial(4) == True

    f = Factor('f', [DerivedLevel('l', Window(op.eq, [color], 2, 2))])
    assert f.applies_to_trial(1) == False
    assert f.applies_to_trial(2) == True
    assert f.applies_to_trial(3) == False
    assert f.applies_to_trial(4) == True

    assert color3.applies_to_trial(1) == True
コード例 #22
0
def test_derived_level_get_dependent_cross_product():
    assert [((tup[0][0].factor_name, tup[0][1].external_name),
             (tup[1][0].factor_name, tup[1][1].external_name))
            for tup in con_level.get_dependent_cross_product()
            ] == [(('color', 'red'), ('text', 'red')),
                  (('color', 'red'), ('text', 'blue')),
                  (('color', 'blue'), ('text', 'red')),
                  (('color', 'blue'), ('text', 'blue'))]

    integer = Factor("integer", ["1", "2"])
    numeral = Factor("numeral", ["I", "II"])
    text = Factor("text", ["one", "two"])
    two_con_level = DerivedLevel(
        "twoCon", WithinTrial(lambda x: x, [integer, numeral, text]))
    assert [((tup[0][0].factor_name, tup[0][1].external_name),
             (tup[1][0].factor_name, tup[1][1].external_name),
             (tup[2][0].factor_name, tup[2][1].external_name))
            for tup in two_con_level.get_dependent_cross_product()
            ] == [(('integer', '1'), ('numeral', 'I'), ('text', 'one')),
                  (('integer', '1'), ('numeral', 'I'), ('text', 'two')),
                  (('integer', '1'), ('numeral', 'II'), ('text', 'one')),
                  (('integer', '1'), ('numeral', 'II'), ('text', 'two')),
                  (('integer', '2'), ('numeral', 'I'), ('text', 'one')),
                  (('integer', '2'), ('numeral', 'I'), ('text', 'two')),
                  (('integer', '2'), ('numeral', 'II'), ('text', 'one')),
                  (('integer', '2'), ('numeral', 'II'), ('text', 'two'))]

    mixed_level = DerivedLevel(
        "mixed",
        WithinTrial(lambda x: x, [
            Factor("color", ["red", "blue", "green"]),
            Factor("boolean", ["true", "false"])
        ]))
    assert [((tup[0][0].factor_name, tup[0][1].external_name),
             (tup[1][0].factor_name, tup[1][1].external_name))
            for tup in mixed_level.get_dependent_cross_product()
            ] == [(('color', 'red'), ('boolean', 'true')),
                  (('color', 'red'), ('boolean', 'false')),
                  (('color', 'blue'), ('boolean', 'true')),
                  (('color', 'blue'), ('boolean', 'false')),
                  (('color', 'green'), ('boolean', 'true')),
                  (('color', 'green'), ('boolean', 'false'))]
コード例 #23
0
color = Factor("color", ["red", "blue"])
motion = Factor("motion", ["up", "down"])
task = Factor("task", ["color", "motion"])


def color_motion_congruent(color, motion):
    return ((color == "red") and (motion == "up")) or \
           ((color == "blue") and (motion == "down"))


def color_motion_incongruent(color, motion):
    return not color_motion_congruent(color, motion)


congruency = Factor("congruency", [
    DerivedLevel("con", WithinTrial(color_motion_congruent, [color, motion])),
    DerivedLevel("inc", WithinTrial(color_motion_incongruent, [color, motion]))
])


def response_left(task, color, motion):
    return (task == "color"  and color  == "red") or \
        (task == "motion" and motion == "up")


def response_right(task, color, motion):
    return not response_left(task, color, motion)


response = Factor("response", [
    DerivedLevel("left", WithinTrial(response_left, [task, color, motion])),
コード例 #24
0
from sweetpea import fully_cross_block, synthesize_trials_non_uniform, print_experiments
from sweetpea.constraints import at_most_k_in_a_row, exclude
from sweetpea.encoding_diagram import print_encoding_diagram
from sweetpea.primitives import Factor, DerivedLevel, Window
from sweetpea.tests.test_utils import get_level_from_name
from sweetpea.server import build_cnf
from acceptance import path_to_cnf_files

# Basic setup
color_list = ["red", "blue"]
color = Factor("color", color_list)
text = Factor("text", color_list)

# congruent 'bookend' Factor. (color and text in first and last trial are congruent)
congruent_bookend = Factor("congruent bookend?", [
    DerivedLevel(
        "yes", Window(lambda color, text: color == text, [color, text], 1, 3)),
    DerivedLevel(
        "no", Window(lambda color, text: color != text, [color, text], 1, 3))
])


@pytest.mark.parametrize('design',
                         permutations([color, text, congruent_bookend]))
def test_correct_solution_count_when_unconstrained(design):
    crossing = [color, text]
    constraints = []

    block = fully_cross_block(design, crossing, constraints)
    experiments = synthesize_trials_non_uniform(block, 100)

    assert len(experiments) == 24
コード例 #25
0
import operator as op
import pytest

from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition
from sweetpea.constraints import at_most_k_in_a_row, exactly_k_in_a_row
from sweetpea.sampling_strategies.guided import GuidedSamplingStrategy
from sweetpea import fully_cross_block, synthesize_trials
from sweetpea.tests.test_utils import get_level_from_name

# Basic setup
color_list = ["red", "blue"]
color = Factor("color", color_list)
text = Factor("text", color_list)

# Congruent Factor
con_level = DerivedLevel("con", WithinTrial(op.eq, [color, text]))
inc_level = DerivedLevel("inc", WithinTrial(op.ne, [color, text]))
con_factor = Factor("congruent?", [con_level, inc_level])

design = [color, text, con_factor]
crossing = [color, text]
constraints = []

block = fully_cross_block(design, crossing, constraints)


def test_guided_sampling_works():
    trials = synthesize_trials(block,
                               5,
                               sampling_strategy=GuidedSamplingStrategy)
コード例 #26
0
left    = Factor("left", ["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"])
right    = Factor("right", ["0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"])

# ALL POSSIBLE COMBINATIONS


# DEFINE CONGRUENCY FACTOR

def congruent_stimulus(left, right):
    return left[0] == right[0] and left[1] == right[1]

def incongruent_stimulus(left, right):
    return not congruent_stimulus(left, right)

cong_stimulus = DerivedLevel("cong_stimulus", WithinTrial(congruent_stimulus, [left, right]))
incong_stimulus = DerivedLevel("incong_stimulus", WithinTrial(incongruent_stimulus, [left, right]))

stimulus = Factor("stimulus", [
    cong_stimulus,
    incong_stimulus
])

# DEFINE CONGRUENCY FACTOR

def congruent_context(left, right):
    return left[2] == right[2] and left[3] == right[3]

def incongruent_context(left, right):
    return not congruent_context(left, right)
コード例 #27
0
import operator as op

from sweetpea.internal import get_all_external_level_names, intersperse
from sweetpea.primitives import Factor, DerivedLevel, Transition

color = Factor("color", ["red", "blue"])
text = Factor("text", ["red", "blue", "green"])

color_repeats_level = DerivedLevel(
    "yes", Transition(lambda colors: colors[0] == colors[1], [color]))
color_no_repeat_level = DerivedLevel(
    "no", Transition(lambda colors: colors[0] != colors[1], [color]))
color_repeats_factor = Factor("color repeats?",
                              [color_repeats_level, color_no_repeat_level])


def test_get_all_external_level_names():
    assert get_all_external_level_names([color, text]) == [('color', 'red'),
                                                           ('color', 'blue'),
                                                           ('text', 'red'),
                                                           ('text', 'blue'),
                                                           ('text', 'green')]

    assert get_all_external_level_names([color_repeats_factor
                                         ]) == [('color repeats?', 'yes'),
                                                ('color repeats?', 'no')]


def test_intersperse():
    assert list(intersperse('', ['yes', 'no', 'yes'])) == \
        ['yes', '', 'no', '', 'yes']
コード例 #28
0
from sweetpea import fully_cross_block
from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition, Window
from sweetpea.constraints import Exclude, ExactlyKInARow, NoMoreThanKInARow
from sweetpea.sampling_strategies.uniform_combinatoric import UniformCombinatoricSamplingStrategy, UCSolutionEnumerator
from sweetpea.tests.test_utils import get_level_from_name

color = Factor("color", ["red", "blue"])
text = Factor("text", ["red", "blue"])

red_color = get_level_from_name(color, "red")
blue_color = get_level_from_name(color, "blue")
red_text = get_level_from_name(text, "red")
blue_text = get_level_from_name(text, "blue")

con_factor_within_trial = Factor("congruent?", [
    DerivedLevel("con", WithinTrial(op.eq, [color, text])),
    DerivedLevel("inc", WithinTrial(op.ne, [color, text]))
])

con_factor_window = Factor("congruent?", [
    DerivedLevel("con", Window(op.eq, [color, text], 1, 1)),
    DerivedLevel("inc", Window(op.ne, [color, text], 1, 1))
])

color_repeats_factor = Factor("repeated color?", [
    DerivedLevel("yes",
                 Transition(lambda colors: colors[0] == colors[1], [color])),
    DerivedLevel("no",
                 Transition(lambda colors: colors[0] != colors[1], [color]))
])
コード例 #29
0
import operator as op
import pytest

from sweetpea import fully_cross_block, __decode
from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition, Window
from sweetpea.constraints import NoMoreThanKInARow
from sweetpea.logic import to_cnf_tseitin


# Common variables for stroop.
color = Factor("color", ["red", "blue"])
text  = Factor("text",  ["red", "blue"])

con_level  = DerivedLevel("con", WithinTrial(op.eq, [color, text]))
inc_level  = DerivedLevel("inc", WithinTrial(op.ne, [color, text]))
con_factor = Factor("congruent?", [con_level, inc_level])

color_repeats_factor = Factor("color repeats?", [
    DerivedLevel("yes", Transition(lambda colors: colors[0] == colors[1], [color])),
    DerivedLevel("no",  Transition(lambda colors: colors[0] != colors[1], [color]))
])

text_repeats_factor = Factor("text repeats?", [
    DerivedLevel("yes", Transition(lambda colors: colors[0] == colors[1], [text])),
    DerivedLevel("no",  Transition(lambda colors: colors[0] != colors[1], [text]))
])

congruent_bookend = Factor("congruent bookend?", [
    DerivedLevel("yes", Window(lambda color, text: color == text, [color, text], 1, 3)),
    DerivedLevel("no",  Window(lambda color, text: color != text, [color, text], 1, 3))
])
コード例 #30
0
import operator as op
import pytest

from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition, Window

color = Factor("color", ["red", "blue"])
text = Factor("text", ["red", "blue"])

con_level = DerivedLevel("con", WithinTrial(op.eq, [color, text]))
inc_level = DerivedLevel("inc", WithinTrial(op.ne, [color, text]))
con_factor = Factor("congruent?", [con_level, inc_level])

color_repeats_level = DerivedLevel("yes", Transition(op.eq, [color]))
color_no_repeat_level = DerivedLevel("no", Transition(op.ne, [color]))
color_repeats_factor = Factor("color repeats?",
                              [color_repeats_level, color_no_repeat_level])

color3 = Factor("color3", ["red", "blue", "green"])

yes_fn = lambda colors: colors[0] == colors[1] == colors[2]
no_fn = lambda colors: not yes_fn(colors)
color3_repeats_factor = Factor("color3 repeats?", [
    DerivedLevel("yes", Window(yes_fn, [color3], 3, 1)),
    DerivedLevel("no", Window(no_fn, [color3], 3, 1))
])


def test_factor_validation():
    Factor("factor name", ["level 1", "level 2"])

    # Non-string name