diff options
Diffstat (limited to 'phstuff/diphawrapper.py')
-rw-r--r-- | phstuff/diphawrapper.py | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/phstuff/diphawrapper.py b/phstuff/diphawrapper.py index 517a929..6dc2861 100644 --- a/phstuff/diphawrapper.py +++ b/phstuff/diphawrapper.py @@ -69,6 +69,41 @@ def save_weight_matrix(fname, weights): for j in range(0, m): f.write(struct.pack("<d", factor*weights[i,j])) + +def load_weight_matrix(fname): + """Load a DIPHA full distance matrix as a NumPy array. + + Parameters: + ----------- + + fname: Name of file to read. + + Returns: + ---------- + + A NumPy array. + + """ + + with open(fname, "rb") as f: + if struct.unpack('<q', f.read(8))[0] != DIPHA_MAGIC: + raise IOError("File %s is not a valid DIPHA file." %(fname)) + if struct.unpack('<q', f.read(8))[0] != DIPHA_DISTANCE_MATRIX: + raise IOError("File %s is not a valid DIPHA matrix file." %(fname)) + + m = struct.unpack('<q', f.read(8))[0] + if m <= 0: + raise IOError("Matrix dimension non-sensical (%d)." %(m)) + + X = np.zeros((m, m)) + + for i in range(0, m): + for j in range(0, m): + X[i, j] = struct.unpack('<d', f.read(8))[0] + + return X + + def save_masked_weight_matrix(fname, weights): """Write a masked NumPy weight matrix to a DIPHA sparse distance matrix file, keeping edges only for unmasked entries. Corresponds |