Ejemplo n.º 1
0
 def test_single_task(self):
     messages = map(
         Message.new, [
             m(task_uuid='foo', task_level=[1]),
             m(task_uuid='foo', task_level=[2]),
         ])
     self.assertEqual(m(foo=messages), to_tasks(messages))
Ejemplo n.º 2
0
def test_supports_hash_and_equals():
    x = m(a=1, b=2, c=3)
    y = m(a=1, b=2, c=3)
    
    assert hash(x) == hash(y)
    assert x == y
    assert not (x != y)
Ejemplo n.º 3
0
 def test_unordered_messages(self):
     messages = map(
         Message.new, [
             m(task_uuid='foo', task_level=[2]),
             m(task_uuid='foo', task_level=[1]),
         ])
     self.assertEqual(m(foo=[messages[1], messages[0]]), to_tasks(messages))
Ejemplo n.º 4
0
 def test_no_task_level(self):
     messages = map(
         Message.new, [
             m(task_uuid='foo'),
             m(task_uuid='foo'),
         ])
     self.assertEqual(m(foo=messages), to_tasks(messages))
Ejemplo n.º 5
0
def test_not_equal():
    x = m(a=1, b=2, c=3)
    y = m(a=1, b=2)

    assert x != y
    assert not (x == y)

    assert y != x
    assert not (y == x)
Ejemplo n.º 6
0
    def __init__(self, timefunc=time.time):
        self.__data = m(products=m(), transactions=v(), summaries=v())

        self.__event_queue = Queue()    # sequential query execution
        self.__lock = Condition()       # passive waiting only
        self.__stop = Event()

        self.time = timefunc

        Thread(target=self.__run).start()
Ejemplo n.º 7
0
def test_update_with():
    assert m(a=1).update_with(add, m(a=2, b=4)) == m(a=3, b=4)
    assert m(a=1).update_with(lambda l, r: l, m(a=2, b=4)) == m(a=1, b=4)

    def map_add(l, r):
        return dict(list(l.items()) + list(r.items()))

    assert m(a={'c': 3}).update_with(map_add, m(a={'d': 4})) == m(a={'c': 3, 'd': 4})
Ejemplo n.º 8
0
    def __init__(self, pipe = None, new_stack = None):
        if not pipe:
            stack = v(m())
            dump = m()
        else:
            stack = pipe.stack
            dump = pipe.dump

        if new_stack:
            stack = new_stack

        self.stack = stack
        self.dump = dump
Ejemplo n.º 9
0
def test_results_writer():
    """Does the results writer output what it should?"""
    results = m(episode=v(0, 1, 2), step_count=v(12, 22, 11))
    output_path = os.path.join(os.getcwd(), 'results.txt')
    results_descriptor = ResultsDescriptor(2, output_path, ['episode', 'step_count'])
    initialize_results(results_descriptor)
    write_results(results, results_descriptor)
    results_check = read_results(output_path)
    assert numpy.array_equal(results_check, numpy.array([[0., 12.], [1., 22.], [2., 11.]]))
    new_results = m(episode=v(3), step_count=v(12.33))
    write_results(new_results, results_descriptor)
    new_results_check = read_results(output_path)
    assert numpy.array_equal(new_results_check, numpy.array([[0., 12.], [1., 22.], [2., 11.], [3., 12.33]]))
Ejemplo n.º 10
0
 def test_multiple_tasks(self):
     messages = map(
         Message.new, [
             m(task_uuid='foo', task_level=[1]),
             m(task_uuid='bar', task_level=[1]),
             m(task_uuid='foo', task_level=[2]),
         ])
     self.assertEqual(
         m(
             foo=[messages[0], messages[2]],
             bar=[messages[1]],
         ),
         to_tasks(messages))
Ejemplo n.º 11
0
 def test_multiple_tasks(self):
     messages = [
         Message.new(m(
             task_uuid='foo',
             task_level=[1],
             action_type='omelette',
         )),
         Message.new(m(
             task_uuid='bar',
             task_level=[2],
             action_status='succeeded',
         )),
     ]
     self.assertRaises(ValueError, Action.new, messages)
Ejemplo n.º 12
0
def test_mutant_decorator():
    @mutant
    def fn(a_list, a_dict):
        assert a_list == v(1, 2, 3)
        assert isinstance(a_dict, type(m()))
        assert a_dict == {'a': 5}

        return [1, 2, 3], {'a': 3}

    pv, pm = fn([1, 2, 3], a_dict={'a': 5})

    assert pv == v(1, 2, 3)
    assert pm == m(a=3)
    assert isinstance(pm, type(m()))
Ejemplo n.º 13
0
def test_various_iterations():
    assert set(['a', 'b']) == set(m(a=1, b=2))
    assert ['a', 'b'] == sorted(m(a=1, b=2).keys())
    assert isinstance(m().keys(), PVector)

    assert set([1, 2]) == set(m(a=1, b=2).itervalues())
    assert [1, 2] == sorted(m(a=1, b=2).values())
    assert isinstance(m().values(), PVector)

    assert set([('a', 1), ('b', 2)]) == set(m(a=1, b=2).iteritems())
    assert set([('a', 1), ('b', 2)]) == set(m(a=1, b=2).items())
    assert isinstance(m().items(), PVector)
Ejemplo n.º 14
0
def test_evolver_remove_element_not_present():
    e = m(a=1000, b=2000).evolver()

    with pytest.raises(KeyError) as error:
        del e['c']

    assert str(error.value) == "'c'"
Ejemplo n.º 15
0
def test_remove_non_existing_element_raises_key_error():
    m1 = m(a=1)

    with pytest.raises(KeyError) as error:
        m1.remove('b')

    assert str(error.value) == "'b'"
Ejemplo n.º 16
0
def test_dot_access_of_non_existing_element_raises_attribute_error():
    m1 = m(a=10)

    with pytest.raises(AttributeError) as error:
        m1.b

    assert "'b'" in str(error.value)
Ejemplo n.º 17
0
    def __init__(self, x_size, y_size, tile_size):
        self.size = pyrsistent.m(x=x_size, y=y_size)

        tile_types = [
            tile.GrassTile,
            tile.GrassTile,
            tile.WaterTile,
        ]

        self.tiles = {
            vector.Vector2(x, y): random.choice(tile_types)()
            for x in range(x_size)
            for y in range(y_size)
        }

        self.sprite_batch = multimedia.SpriteBatch()

        self.sprites = pyrsistent.pmap({
            coord: multimedia.Sprite(
                self.tiles[coord].image,
                vector.Vector2(
                    x=coord.x*tile_size,
                    y=coord.y*tile_size,
                ),
                batch=self.sprite_batch,
            )
            for coord in self.tiles
        })
Ejemplo n.º 18
0
def iter_valid_plays_for_card(card, myself, others):
    """Iterate through a list of valid plays for the given card.

    The plays are only valid within the rules of the game. They don't pay
    attention to the current state. Thus, they might guess that a player has
    the Minister even though it has already been played.

    The order of iteration is irrelevant and not guaranteed to be stable.
    """
    play = m(card=card)
    if card in ('Priestess', 'Minister', 'Prince'):
        yield play
    elif card in ('Wizard',):
        yield play.set('target', myself)
        for target in others:
            yield play.set('target', target)
    elif card in ('Clown', 'Knight', 'General'):
        for target in others:
            yield play.set('target', target)
    else:
        for target in others:
            targeted = play.set('target', target)
            for card in CARDS:
                if card == 'Soldier':
                    continue
                yield targeted.set('guess', card)
Ejemplo n.º 19
0
def start_configuration():
    """
    Creates the initial PMap that will be passed down the pipeline

    :return:
    """
    return pyr.m()
Ejemplo n.º 20
0
def test_evolver_simple_update():
    x = m(a=1000, b=2000)
    e = x.evolver()
    e['b'] = 3000

    assert e['b'] == 3000
    assert e.persistent()['b'] == 3000
    assert x['b'] == 2000
Ejemplo n.º 21
0
def test_pmap_field_create_from_nested_serialized_data():
    class Foo(PRecord):
        foo = field(type=str)

    class Bar(PRecord):
        bar = pmap_field(str, Foo)

    data = Bar(bar=m(foo_key=Foo(foo="foo")))
    Bar.create(data.serialize()) == data
Ejemplo n.º 22
0
    def test_args(self):
        arglist = ["-r https://rhsm-jenkins.rhev-ci-vms.eng.rdu2.redhat.com/view/Scratch/job/stoner-gui-test-smoke/93/artifact/test-output/testng-results.xml",
                   "--testrun-prefix RHSM",
                   "--testrun-suffix blah"]
        argstr = " ".join(arglist)
        self.cfg = cfg.CLIConfigurator(args=argstr)

        start_map = pyr.m()
        end_map = self.cfg(start_map)
Ejemplo n.º 23
0
def test_not_equal_to_dict():
    x = m(a=1, b=2, c=3)
    y = dict(a=1, b=2, d=4)

    assert x != y
    assert not (x == y)

    assert y != x
    assert not (y == x)
Ejemplo n.º 24
0
def test_pmap_unorderable():
    with pytest.raises(TypeError):
        _ = m(a=1) < m(b=2)

    with pytest.raises(TypeError):
        _ = m(a=1) <= m(b=2)

    with pytest.raises(TypeError):
        _ = m(a=1) > m(b=2)

    with pytest.raises(TypeError):
        _ = m(a=1) >= m(b=2)
Ejemplo n.º 25
0
def test_dot_access_of_non_existing_element_raises_attribute_error():
    m1 = m(a=10)

    with pytest.raises(AttributeError) as error:
        m1.b

    error_message = str(error.value)

    assert "'b'" in error_message
    assert type(m1).__name__ in error_message
Ejemplo n.º 26
0
def compute_check_result_for_job(client, job):
    kwargs = m(
        name="check_tron_job.{}".format(job['name']),
        source="tron",
    )
    if 'realert_every' not in kwargs:
        kwargs = kwargs.set('realert_every', guess_realert_every(job))
    kwargs = kwargs.set('check_every', f"{_run_interval}s")

    # We want to prevent a monitoring config from setting the check_every
    # attribute, since one config should not dictate how often this script runs
    sensu_kwargs = (
        pmap(job['monitoring']).discard(PRECIOUS_JOB_ATTR)
        .discard('check_every')
    )
    kwargs = kwargs.update(sensu_kwargs)

    kwargs_list = []
    if job["status"] == "disabled":
        kwargs = kwargs.set(
            'output',
            "OK: {} is disabled and won't be checked.".format(job['name'], )
        )
        kwargs = kwargs.set('status', 0)
        kwargs_list.append(kwargs)
    else:
        # The job is not disabled, therefore we have to look at its run history
        url_index = client.index()
        tron_id = get_object_type_from_identifier(url_index, job["name"])
        job_content = pmap(
            client.job(
                tron_id.url,
                include_action_runs=True,
            )
        )

        if job['monitoring'].get(PRECIOUS_JOB_ATTR, False):
            dated_runs = sort_runs_by_interval(job_content, interval='day')
        else:
            dated_runs = {'': job_content['runs']}

        for date, runs in dated_runs.items():
            results = compute_check_result_for_job_runs(
                job=job,
                job_content=job_content.set('runs', runs),
                client=client,
            )
            dated_kwargs = kwargs.update(results)
            if date:  # if empty date, leave job name alone
                dated_kwargs = dated_kwargs.set(
                    'name', f"{kwargs['name']}-{date}"
                )
            kwargs_list.append(dated_kwargs)

    return [dict(kws) for kws in kwargs_list]
Ejemplo n.º 27
0
def kickstart(yaml_path=None, args=None):
    """
    Kicks everything off by creating the configuration function pipeline

    :return:
    """
    # Create the CLIConfigurator first, because it may override defaults (eg, it can override the
    # default location of pylarion_path or exporter_config, which are needed by PylarionConfigurator
    # and YAMLConfigurator)

    cli_cfg = CLIConfigurator()
    start_map = pyr.m()
    init_map = cli_cfg(start_map)
    pyl_path = init_map.get("pylarion_path")
    yaml_path = init_map.get("exporter_config")
    env_path = init_map.get("environment_file")

    pyl_cfg = PylarionConfigurator(path=pyl_path)
    env_cfg = OSEnvironmentConfigurator()
    yml_cfg = YAMLConfigurator(cfg_path=yaml_path)
    jnk_cfg = None
    if env_path:
        jnk_cfg = JenkinsConfigurator(env_path)
    cli_cfg = CLIConfigurator(args=args)

    if env_path:
        pipeline = compose(cli_cfg, jnk_cfg, yml_cfg, env_cfg, pyl_cfg)
    else:
        pipeline = compose(cli_cfg, yml_cfg, env_cfg, pyl_cfg)
    end_map = pipeline(start_map)

    log.log(DEFAULT_LOG_LEVEL, "================ end_map ===================")
    dprint(end_map)

    try:
        final = ConfigRecord(**end_map)
    except pyr._checked_types.InvariantException as ex:
        print ex
        if ex.missing_fields:
            log.error("Following fields not configured: " + str(ex.missing_fields))
        if False and  ex.invariant_errors:
            log.error("Invariants broken: " + str(ex.invariant_errors))
        log.error("Please correct the above and run again")
        sys.exit(1)
    log.log(logging.INFO, "================= final ====================")
    dprint(final, log_lvl=logging.INFO)
    log.log(logging.INFO, "============================================\n")

    result = {"pyl_cfg": pyl_cfg,
              "env_cfg": env_cfg,
              "yml_cfg": yml_cfg,
              "cli_cfg": cli_cfg,
              "config": final}
    return result
Ejemplo n.º 28
0
 def test_simple_action_task_uuid(self):
     start_time = time.time()
     end_time = start_time + 10
     messages = [
         Message.new(m(
             task_uuid='foo',
             task_level=[1],
             action_type='omelette',
             timestamp=start_time,
         )),
         Message.new(m(
             task_uuid='foo',
             task_level=[2],
             action_status='succeeded',
             timestamp=end_time,
         )),
     ]
     action = Action.new(messages)
     self.assertEqual('foo', action.task_uuid)
     self.assertEqual('succeeded', action.status)
     self.assertEqual([], action.messages)
     self.assertEqual(datetime.fromtimestamp(start_time), action.start_time)
Ejemplo n.º 29
0
 def test_as_dict(self):
     task_uuid = self.make_uuid()
     task_level = [1]
     timestamp = self.make_timestamp()
     data = m(
         task_uuid=task_uuid,
         task_level=task_level,
         timestamp=timestamp,
         foo="bar",
         baz="qux",
     )
     message = Message.new(data)
     self.assertEqual(
         m(
             task_uuid=task_uuid,
             task_level=task_level,
             timestamp=datetime.fromtimestamp(timestamp),
             foo="bar",
             baz="qux",
         ),
         message.as_dict(),
     )
Ejemplo n.º 30
0
def run_interval(interval_id, initial_agent, environment, interval_steps):
    """Run through a single planning interval.  Returns the results for that interval."""
    if interval_id > 0:
        initial_agent.policy = initial_agent.vi_policy
    logging.info('Starting interval {}'.format(interval_id))
    for step_data in generate_state(initial_agent, environment):
        if step_data.step_id == interval_steps:
            logging.info('Planning...')
            initial_agent.plan()
            if initial_agent.viz:
                initial_agent.viz.update()
            agent = step_data.agent
            results = m(interval_id=interval_id, steps=step_data.step_id)
            return IntervalData(agent, results, interval_id)
Ejemplo n.º 31
0
def test_freeze_recurse_in_dictionary_values():
    result = freeze({'a': [1]})
    assert result == m(a=v(1))
    assert type(result['a']) is type(v())
Ejemplo n.º 32
0
def test_freeze_recurse_in_lists():
    result = freeze(['a', {'b': 3}])
    assert result == v('a', m(b=3))
    assert type(result[1]) is type(m())
Ejemplo n.º 33
0
def test_thaw_recurse_in_dict_values():
    result = thaw({'a': v(1, m(b=2))})
    assert result == {'a': [1, {'b': 2}]}
    assert type(result['a']) is list
    assert type(result['a'][1]) is dict
Ejemplo n.º 34
0
def test_thaw_recurse_in_lists():
    result = thaw(v(['a', m(b=1), v(2)]))
    assert result == [['a', {'b': 1}, [2]]]
    assert type(result[0]) is list
    assert type(result[0][1]) is dict
Ejemplo n.º 35
0
def test_thaw_non_strict_no_recurse_in_dict_values():
    result = thaw({'a': v(1, m(b=2))}, strict=False)
    assert result == {'a': [1, {'b': 2}]}
    assert type(result['a']) is type(v())
    assert type(result['a'][1]) is type(m())
Ejemplo n.º 36
0
def test_thaw_non_strict_no_recurse_in_lists():
    result = thaw(v(['a', m(b=1), v(2)]), strict=False)
    assert result == [['a', {'b': 1}, [2]]]
    assert type(result[0][1]) is type(m())
Ejemplo n.º 37
0
def test_transform_when_appending(pvector):
    from pyrsistent import m
    x = pvector([1, 2])

    assert x.transform([2, 'd'], 999) == pvector([1, 2, m(d=999)])
Ejemplo n.º 38
0
 def test_default(self):
     """
     Default content parsers.
     """
     interceptors = [body_params()]
     request = m(
         content_type=
         'multipart/form-data; boundary=---------------------------114772229410704779042051621609',
         body=open_test_data('data/multipart_request'))
     context = empty_context.set(REQUEST, request)
     self.assertThat(
         execute(context, interceptors),
         succeeded(
             ContainsDict({
                 REQUEST:
                 ContainsDict({
                     'multipart_params':
                     MatchesDict({
                         u'name':
                         Multipart(content_length=Equals(8),
                                   name=Equals(u'name'),
                                   headers=MatchesDict({
                                       u'Content-Disposition':
                                       Equals(u'form-data; name="name"'),
                                   }),
                                   body=Equals(b'Some One')),
                         u'email':
                         Multipart(content_length=Equals(16),
                                   name=Equals(u'email'),
                                   headers=MatchesDict({
                                       u'Content-Disposition':
                                       Equals(u'form-data; name="email"'),
                                   }),
                                   body=Equals(b'*****@*****.**')),
                         u'avatar':
                         Multipart(
                             content_length=Equals(869),
                             content_type=Equals(u'image/png'),
                             filename=Equals(u'smiley-cool.png'),
                             name=Equals(u'avatar'),
                             headers=MatchesDict({
                                 u'Content-Type':
                                 Equals(u'image/png'),
                                 u'Content-Disposition':
                                 Equals(
                                     u'form-data; name="avatar"; filename="smiley-cool.png"'
                                 ),
                             }),
                             body=After(
                                 lambda x: hashlib.sha256(x).hexdigest(),
                                 Equals(
                                     b'25fbe073db80f71a13fb8e0a190a76c0fda494d18849fa6fa87ea5a0924baa07'
                                 ))),
                         # XXX: This syntax isn't supported by the multipart
                         # parser, multiple things with the same name are
                         # overwritten.
                         u'attachments[]':
                         Always(),
                     }),
                     'form_params':
                     MatchesDict({
                         u'name': Equals(u'Some One'),
                         u'email': Equals(u'*****@*****.**')
                     })
                 })
             })))
Ejemplo n.º 39
0
#!/usr/bin/env python
"""
A performance benchmark using the example from issue #232:

https://github.com/Julian/jsonschema/pull/232

"""
from bp.filepath import FilePath
from perf import Runner
from pyrsistent import m

from jsonschema.tests._suite import Collection
import jsonschema

collection = Collection(
    path=FilePath(__file__).sibling("issue232"),
    remotes=m(),
    name="issue232",
    validator=jsonschema.Draft7Validator,
)

if __name__ == "__main__":
    collection.benchmark(runner=Runner())
Ejemplo n.º 40
0
####################################################################################################
# contrast/__init__.py
# The second-order contrast module of the standard cortical observer.
# By Noah C. Benson
'''
The sco.contrast module of the standard cortical observer library is responsible for calculating the
first- and second-order contrast present in the normalized stimulus image array.
'''

import pyrsistent as _pyr
import pimms as _pimms
from .core import (ImageArrayContrastView, ImageArrayContrastFilter,
                   calc_contrast_filter, calc_contrast_constants,
                   calc_contrast_energies, calc_compressive_constants,
                   calc_compressive_nonlinearity, calc_pRF_SOC)

contrast_plan_data = _pyr.m(
    contrast_constants=calc_contrast_constants,
    compressive_constants=calc_compressive_constants,
    contrast_filter=calc_contrast_filter,
    contrast_energies=calc_contrast_energies,
    pRF_SOC=calc_pRF_SOC,
    compressive_nonlinearity=calc_compressive_nonlinearity)

contrast_plan = _pimms.plan(contrast_plan_data)
Ejemplo n.º 41
0
def main():
  device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
  model_params = m(min_num_occurances=10,
                   append_hadamard=False,
                   append_difference=False,
                   hidden_layer_sizes=[100],
                   token_embed_len=100)
  train_params = m(dropout_keep_prob=0.8,
                   batch_size=512,
                   use_layer_norm=True,
                   use_batch_norm=False,
                   use_bce_loss=False,
                   num_cv_folds=5)
  lazy = LazyBuilder('./cache')
  diagnoses_desc_df = pd.read_csv('data/D_ICD_DIAGNOSES.csv')
  diagnoses_df = pd.read_csv('data/diagnoses.csv')
  label_lookup = get_to_label_mapping(set(diagnoses_desc_df['ICD9_CODE'].tolist() + diagnoses_df.icd9_code.tolist()))
  num_icd9_codes = len(label_lookup)
  diagnoses_df['label'] = diagnoses_df.icd9_code.map(lambda val: label_lookup[val])
  diagnoses_df.sort_values('hadm_id', inplace=True)
  diagnoses = diagnoses_df.to_dict('list')
  pairs_by_hadm_id, num_pairs = to_pairs_by_hadm_id(diagnoses)
  icd_desc_lookup = fetch_icd_desc_lookup()
  icd_desc_lookup_by_label = {label: icd_desc_lookup.get(icd9, '')
                              for icd9, label in label_lookup.items()}
  tokenizer = get_default_tokenizer()
  token_set = get_token_set(tokenizer,
                            icd_desc_lookup_by_label,
                            opts=dict(min_num_occurances=model_params.min_num_occurances))
  token_lookup = dict(zip(token_set, range(len(token_set))))
  notes_bow = CachedBoW(tokenizer=tokenizer, path='data/notes/', token_lookup=token_lookup)
  icd_desc_bow, __ = prepare_bow(icd_desc_lookup_by_label, token_lookup=token_lookup, token_set=token_set)
  num_unique_tokens = len(token_lookup)
  folds = get_cv_folds(train_params.num_cv_folds, pairs_by_hadm_id.keys())
  for test_fold_num in range(train_params.num_cv_folds):
    print('Fold num', test_fold_num)
    test_keys = folds[test_fold_num]
    test, train = deal_folds(pairs_by_hadm_id, test_keys)
    test_rel_sets = to_rel_sets(test)
    test_hadm_ids = [hadm_id for hadm_id, g in groupby(test, itemgetter(0))]
    test_note_id_by_hadm_id = {hadm_id: next(g)[0]
                               for hadm_id, g in groupby(test, itemgetter(0))}
    note = [notes_bow[test_note_id_by_hadm_id[hadm_id]] for hadm_id in test_hadm_ids]
    candidates = list(range(num_icd9_codes))
    icd = [icd_desc_bow[label] for label in candidates]
    token_embeds = nn.Embedding(num_unique_tokens, model_params.token_embed_len)
    pointwise_scorer = PointwiseScorer(token_embeds, token_embeds, model_params, train_params)
    pairwise_scorer = PairwiseScorer(token_embeds, token_embeds, model_params, train_params)
    ranker = PointwiseRanker(device, pointwise_scorer)
    criteria = nn.CrossEntropyLoss()
    optimizer = Adam(pairwise_scorer.parameters())
    dataset = MimicDataset(notes_bow, icd_desc_bow, train)
    dataloader = DataLoader(dataset, batch_sampler=BatchSampler(RandomSampler(dataset),
                                                                train_params.batch_size,
                                                                False))
    for batch_num, batch in enumerate(dataloader):
      optimizer.zero_grad()
      out = pairwise_scorer(*(tens.to(device) for tens in batch))
      loss = criteria(torch.zeros_like(out), out)
      if batch_num % 100 == 0: print('batch', batch_num, 'loss', loss)
      if batch_num % 10000 == 0:
        rankings = ranker(note, icd).tolist()
        print('batch', batch_num, metrics_at_k(rankings, test_rel_sets))
      loss.backward()
      optimizer.step()
Ejemplo n.º 42
0
####################################################################################################
# sco/pRF/__init__.py
# pRF-related calculations for the standard cortical observer library.
# By Noah C. Benson
'''
The sco.pRF module contains calculation plans for producing PRFSpec objects, which track the data
for each pRF involved in the sco calculation and can extract and sum over regions from images.
'''

import pyrsistent as pyr
import pimms
from .core import (calc_compressive_constants, calc_pRF_sigmas,
                   calc_pRF_centers, calc_pRFs, calc_cpd_sensitivities,
                   PRFSpec)

pRF_plan_data = pyr.m(compressive_constants=calc_compressive_constants,
                      pRF_sigmas=calc_pRF_sigmas,
                      pRF_centers=calc_pRF_centers,
                      pRFs=calc_pRFs,
                      cpd_sensitivites=calc_cpd_sensitivities)

pRF_plan = pimms.plan(pRF_plan_data)
Ejemplo n.º 43
0
def test_get_in():
    # This is not an extensive test. The doctest covers that fairly good though.
    get_in(m(a=v(1, 2, 3)), ['m', 1]) == 2
Ejemplo n.º 44
0
# Node:
#   Source : NodeId {InputSlotId  [0],  OutputSlotId [n]}
#   Trans  : NodeId {InputSlotId  [n] , OutputSlotId [k]}
#   Sink   : NodeId {InputSlotId  [n] , OutputSlotId [0]}
# Node: n_inputs: int, n_outputs: int

Node = NamedTuple('Node', [('n_inputs', int), ('n_outputs', int)])

Graph = namedtuple('Graph', ['nodes', 'links'])
# an isomorphic graph, where the nodes are pairs (node_id, [output|input]_slot_ix)
# would be tree-like:
#   an output can be connected to multiple inputs,
#   but an input can be connected to only one output.
#   (for now - we might add 'variadic inputs',
#    or inputs that connect to any number of outputs)
Graph.empty = Graph(nodes=m(), links=s())

# node_boxes : Map[ NodeId, Id ]

# nodes : PMap_[Id, Node]

# links : Set[ (InputSlotId, OutputSlotId) ]


class GraphAction(sumtype):
    def AddNode(id_: Id, node: Node):
        ...

    def RemoveNode(id_: Id):
        ...
Ejemplo n.º 45
0
    def fn(a_list, a_dict):
        assert a_list == v(1, 2, 3)
        assert isinstance(a_dict, type(m()))
        assert a_dict == {'a': 5}

        return [1, 2, 3], {'a': 3}
Ejemplo n.º 46
0
def test_set_in_when_appending(pvector):
    from pyrsistent import m
    x = pvector([1, 2])

    assert x.set_in([2, 'd'], 999) == pvector([1, 2, m(d=999)])
Ejemplo n.º 47
0
def test_freeze_dict():
    result = freeze({'a': 'b'})
    assert result == m(a='b')
    assert type(freeze({'a': 'b'})) is type(m())
Ejemplo n.º 48
0
 def __init__(self, root):
     UndoLog.__init__(self)
     self.log("init", pyrsistent.m())
     self.set_root(root)  # Needs to be calculated now
     self.dirty = set()  # Should be made into an (ordered) set?
     self.to_delete = set()
Ejemplo n.º 49
0
def test_thaw_recurse_in_tuples():
    result = thaw(('a', m()))
    assert result == ('a', {})
    assert type(result[1]) is dict
Ejemplo n.º 50
0
####################################################################################################
# neuropythy/io/core.py
# This file implements the load and save functions that can be used to read and write various kinds
# of neuroscience data

import numpy as np
import pyrsistent as pyr
import nibabel as nib
import os, six, json, gzip, pimms

# The list of import-types we understand
importers = pyr.m()
'''
neuropythy.io.core.importers is the persistent map of file-types that can be imported by neuropythy.
See also neuropythy.io.load.
'''


def guess_import_format(filename, **kwargs):
    '''
    guess_import_format(filename) attempts to guess the file format for the given filename; it does
      this guessing by looking at the file extension and using registered sniff-tests from
      importers. It will not attempt to load the file, so if the extension of the filename is
      missing, it is unlikely that this function will deduce the file-type (though load will often
      succeeed at extracting the data by trying all types exhaustively). If guess_import_format
      cannot deduce the format, it yields None.

    Note that if the filename has an extension that is recognized by neuropythy but the file itself
    is of another format, this function will never look beyond the extention in the filename;
    neither this function nor load perform that level of deduction.
    
Ejemplo n.º 51
0
def test_thaw_recurse_in_vectors():
    result = thaw(v('a', m(b=3)))
    assert result == ['a', {'b': 3}]
    assert type(result[1]) is dict
Ejemplo n.º 52
0
def test_freeze_recurse_in_tuples():
    """Values in tuples are recursively frozen."""
    result = freeze(('a', {}))
    assert result == ('a', m())
    assert type(result[1]) is type(m())
Ejemplo n.º 53
0
def test_thaw_dict():
    result = thaw(m(a='b'))
    assert result == {'a': 'b'}
    assert type(result) is dict
Ejemplo n.º 54
0
def test_thaw_recurse_in_mapping_values():
    result = thaw(m(a=v(1)))
    assert result == {'a': [1]}
    assert type(result['a']) is list