Удалить строки трехмерного массива, которые присутствуют в массиве 4D - PullRequest
0 голосов
/ 20 октября 2018

У меня есть трехмерный массив numpy = содержащий координаты точек в пространстве.Преобразовав этот массив с помощью матричных операций, я получил 4-мерный массив, так что для каждой строки есть соответствующий 3D-блок в 4D-массиве после преобразования матрицы (включая операцию идентификации).Таким образом, нулевая ось обоих массивов равна.

Теперь мне нужно выяснить, присутствует ли какая-либо строка с индексом [i] или нет в j-й строке, если она присутствует, затем удалите i или j.не имеет значения, если это я или J).Также я =!J, так как у нас есть операция идентификации.В качестве примера, чтобы уточнить:

>>> a  # 3d array
array([[[0, 1, 2],
        [0, 0, 2]],

       [[2, 0, 0],
        [0, 0, 2]],

       [[0, 2, 1],
        [0, 0, 0]]])

>>> b  #4d array after applying transformation to 3d array(a)
array([[[[0, 1, 2],
         [0, 0, 2]],

        [[0, 0, 0],
         [2, 1, 1]],

        [[0, 2, 1],
         [0, 0, 1]]],


       [[[2, 0, 0],
         [0, 0, 2]],

        [[0, 2, 2],
         [2, 0, 0]],

        [[2, 2, 2],
         [1, 0, 2]]],


       [[[0, 2, 1],
         [0, 0, 0]],

        [[2, 0, 0],
         [0, 0, 2]],

        [[2, 0, 1],
         [2, 2, 0]]]])

Теперь, если вы посмотрите внимательно, a такой же, как b [:, 0].Причина в преобразовании идентичности. Поэтому мы, конечно, не хотим сравнивать a [0] с b [0].A [1] = b [2,0], поэтому код должен удалить либо a [1], либо a [2], но не оба.Окончательный результат должен быть:

>>> output
array([[[0, 1, 2],
        [0, 0, 2]],

       [[2, 0, 0],
        [0, 0, 2]]])

ИЛИ,

>>> output
array([[[0, 1, 2],
        [0, 0, 2]],

       [[0, 2, 1],
        [0, 0, 0]]])

Первое решение. Решение.пока у меня есть это,

def giveuniquestructures_fast(marray, symarray, noofF):
    """ Removes configurations ith (2d block of marray) which are found in symmarray at jth position such that i != j """

# noofF is the number of points in each configuration(i.e. noofF = len(marray[0])
# The shape of the two arrays is, marray 3D-array(positions, nofF, 3),
# symarray 4D-array(positions, symmetryopration, noofF, 3)


print("Sorting the input arrays:\\n")

symarray = sort4D(symarray)    # sorting the symarray(4D-array)

marray = sorter3d_v1(marray)    # sorting the marray(3D-array)
print("sorting is complete now comparison is starting: ")

delindex = np.empty(0, dtype=int) 
delcheck = False
print("The total number of configurations are", len(marray))

 # flattening the array to reduce one dimension

symarray = symarray.reshape(marray.shape[0],-1,3*noofF) 
marray = marray.reshape(-1, 3*noofF)
bol = np.ones(symarray.shape[0], dtype=bool)
     # boolean array for masking the symarray along 0-axis

for i in range(len(marray)):

        print("checking %dth configuration for symmetrical equivalencey \\n" % i)
        bol[i] = False
        bol1 = marray[i] == symarray[bol]
        bol1 = bol1.all(-1)
        bol[i] = True # setting it back to true for next run

        if bol1.any() :

            delindex = np.append(delindex, i)
            delcheck = True

if delcheck:

    marray = np.delete(marray, delindex, 0)

print("Search for UNique configurations are ending now :\\n")
return marray.reshape(-1, noofF,3)  # converting back to input shape

----------- на всякий случай, если вы хотите увидеть функции сортировки ------------

def sorter3d_v1(a):

    """sorts the 1D blocks within 2D blocks of array in order of first column, 2nd column, 3rd column"""

    print("Input array is \\n", a)
    print("shape of input array is ",a.shape)
    ind = np.lexsort((a[:,:,2], a[:,:,1], a[:,:,0]), axis=1)  # getting the sorter index

    s = np.arange(len(a))[:,np.newaxis] # getting the evenly distributed number array  based on length of ind to select the sorted

    a = a[s,ind,:]

    print("sorted array is \\n")
    print(a)

    return  a

Как вы уже догадались, проблема с этой функцией - эффективность.Если во входном массиве строки равны 1/10 от миллиона, то запуск цикла занимает много времени.Фактическое узкое место заключается в утверждении, использующем функцию np.all (), то есть

bol1 = bol1.all(-1)

. Любая помощь по ее улучшению будет высоко оценена.Надеюсь, это не смущает.

Второе решение Второе решение, которое мне удалось кодировать с векторизацией:

def giveuniquestructures_fast_v1(marray, symarray, noofF):
    """The new implementation of the previous function (uniquestructures_fast) """

    # The shape of the two arrays is, marray 3D-array(positions, nofF, 3),
    # symarray 4D-array(positions, symmetryopration, noofF, 3)

    try:

        if (len(marray) != len(symarray)):
            raise Exception("The length of the two arrays doesn't match")

    except Exception:
        raise

    print("Sorting the input arrays:\\n")

    symarray = sort4D(symarray)  # sorting the barray(4D-array)

    marray = sorter3d_v1(marray)  # sorting the marray(3D-array)
    print("sorting is complete now comparison is starting: ")
    print("The total number of configurations is", len(marray))

    # flattening the array to reduce one dimension

    symarray = symarray.reshape(symarray.shape[0], -1, 3 * noofF)
    marray = marray.reshape(-1, 3 * noofF)

    # Batch operation may give Memory error in case array is big!!! 

    bol = marray[:,np.newaxis,np.newaxis,:] == symarray  # 4d array
    maskindices = np.arange(len(bol)) # to falsify the identity matrix operaterated values
    bol[maskindices[:,np.newaxis], maskindices[:,np.newaxis]] = False  # setting the identity rows value to False
    delindices   = np.where(bol.all(-1)) # The first and second tuple entries are relevant for next step

    # Need to check for swapping indices as possibility of removing both equal arrays may happen

    # removing the configurations which are symmetrically equivalent
    marray = np.delete(marray, np.unique(delindices,axis=-1)[0], 0)

    # reverting the dimensions back to the input array dimensions

    marray = marray.reshape(-1, noofF, 3)
    print("Search for UNique configurations are ending now :\\n")
    return marray

Проблема со вторым солом. Векторизация не помогает, когда массив становится достаточно большим, чтобы вызвать ошибку памяти.Есть идеи? !!

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