import math


def rspace_sum(rs, qs, basis, kappa, rlim):
    """
    Real space part of the sum
    Parameters:
       rs -- list of particle positions
       qs -- list of particle charges
       basis -- real space basis
       kappa -- splitting parameter
       rlim -- size of lattice (one side of a cube of points)
    """
    rspace_sum = 0.0
    for i in range(len(rs)):
        for j in range(len(rs)):
            q = qs[i]*qs[j]
            r = rs[j] - rs[i]
            for n1 in range(-rlim+1, rlim):
                for n2 in range(-rlim+1, rlim):
                    for n3 in range(-rlim+1, rlim):
                        if i == j and n1 == 0 and n2 == 0 and n3 == 0:
                            continue
                        lat = n1*basis[0] + n2*basis[1] + n3*basis[2]
                        d = r + lat
                        rd = math.sqrt(d.dot(d))
                        rspace_sum += q * math.erfc(kappa*rd)/rd
    return rspace_sum