Как вы используете список в качестве аргумента индекса для NumPy ndarrays? - PullRequest
0 голосов
/ 05 июля 2018

Итак, у меня есть проблема, которая может быть очень простой. У меня есть эти Nundy ndarrays, которые я выделил и хочу присвоить им значения через индексы, возвращаемые в виде списков. Возможно, будет проще, если я покажу вам пример кода. Сомнительный код, который у меня есть, находится внизу, и в моем тестировании (до фактического масштабирования) я продолжаю получать синтаксические ошибки: '(

РЕДАКТИРОВАТЬ: отредактировано, чтобы упростить поиск и устранение неполадок и поместить пример кода внизу

import numpy as np
def do_stuff(index, mask):
    # this is where the calculations are made
    magic = sum(mask)
    return index, magic

def foo(full_index, comparison_dims, *xargs):
    # I have this function executed in Parallel since I'm using a machine with 36 nodes per core, and can access upto 16 cores for each script #blessed
    # figure out how many dimensions there are, and how big they are
    parent_dims = []
    parent_diffs = []
    for j in xargs:
        parent_dims += [len(j)]
        parent_diffs += [j[1] - j[0]] # this is used to find a mask

    index = [] # this is where the individual dimension indices will be stored

    dim_n = 0
    # loop through the dimensions
    while dim_n < len(parent_dims):
        dim_index = full_index % parent_dims[dim_n]
        index += [dim_index]
        if dim_n == 0:
            mask = (comparison_dims[dim_n] > xargs[dim_n][dim_index] - parent_diffs[dim_n]/2) * \
                   (comparison_dims[dim_n] <= xargs[dim_n][dim_index] +parent_diffs[dim_n] / 2)
        else:
            mask *= (comparison_dims[dim_n] > xargs[dim_n][dim_index] - parent_diffs[dim_n]/2) * \
                    (comparison_dims[dim_n] <=xargs[dim_n][dim_index] +  parent_diffs[dim_n] / 2)
        full_index //= parent_dims[dim_n]
        dim_n += 1

    return do_stuff(index, mask)

def bar(comparison_dims, *xargs):
    if len(xargs) == comparison_dims.shape[0]:
        pass
    elif len(comparison_dims.shape) == 2:
        pass
    else:
        raise ValueError("silly person, you failed")
    from joblib import Parallel, delayed
    dims = []
    for j in xargs:
        dims += [len(j)]

    myArray = np.empty(tuple(dims))
    results = Parallel(n_jobs=1)(
        delayed(foo)(
            index, comparison_dims, *xargs)
        for index in range(np.prod(dims))
    )

    # LOOK HERE, HELP HERE!
    for index_list, result in results:
        # I thought this would work, but oh golly was I was wrong, index_list here is a list of ints, and result is a value
        # for example index, result = [0,3,7], 45.4
        # so in execution, that would yield: myArray[0,3,7] = 45.4
        # instead it yields SyntaxError because I don't know what I'm doing XD
        myArray[*index_list] = result

    return myArray

Любые идеи, как я могу заставить это работать. Что мне нужно сделать?

Я не самый острый инструмент в сарае, но я думаю, что с вашей помощью мы сможем понять это!

Быстрый пример устранения этой проблемы:

compareDims = np.array([np.random.rand(1000), np.random.rand(1000)])
dim0 = np.arange(0,1,1./20)
dim1 = np.arange(0,1,1./30)

myArray = bar(compareDims, dim0, dim1)

1 Ответ

0 голосов
/ 05 июля 2018

Индексирование массива с произвольным списком многомерных индексов. вам действительно нужно использовать кортеж :

for index_list, result in results: myArray[tuple(index_list)] = result

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...