Page MenuHomec4science

FreeFemConversionTools.py
No OneTemporary

File Metadata

Created
Mon, Aug 19, 23:40

FreeFemConversionTools.py

#!/usr/bin/python
import numpy as np
import scipy.sparse as sp
import os
import utilities
from RROMPyTypes import Np1D, Np2D
def prod2(v1 : str = "u", v2 : str = "v", compl : bool = True) -> str:
if compl:
return "({} * conj({}))".format(v1, v2)
else:
return "({} * {})".format(v1, v2)
def diff(var : str = "u", dim : int = 2) -> str:
dstr = "(abs(dx({}))^2".format(var)
if dim > 1:
dstr = dstr + " + abs(dy({}))^2".format(var)
if dim > 2:
dstr = dstr + " + abs(dz({}))^2".format(var)
return dstr + ")"
def diff2(v1 : str = "u", v2 : str = "v", dim : int = 2,
compl : bool = True) -> str:
dstr = prod2("(dx({})".format(v1), "dx({})".format(v2), compl)
if dim > 1:
dstr = dstr + " + " + prod2("dy({})".format(v1),
"dy({})".format(v2), compl)
if dim > 2:
dstr = dstr + " + " + prod2("dz({})".format(v1),
"dz({})".format(v2), compl)
return dstr + ")"
def ffvec2npvec(filename:str) -> Np1D:
with open(filename) as f:
a = f.readline()
v = np.zeros(int(a), dtype = np.complex)
i = 0
for line in f:
for x in line[: -1].split():
if "(" in x:
y = x[1:-1].split(",")
v[i] = float(y[0]) + 1.j * float(y[1])
else:
v[i] = complex(x)
i = i + 1
return v
def ffmat2spmat(filename:str) -> Np2D:
with open(filename) as f:
a = f.readline()[: -1]
while a[0] == "#":
a = f.readline()[: -1]
n, m, sym, nnz = [int(x) for x in a.split()]
row = np.zeros(nnz)
col = np.zeros(nnz)
data = np.zeros(nnz, dtype = np.complex)
for i, line in enumerate(f):
x = line[: -1].split()
row[i] = int(x[0]) - 1
col[i] = int(x[1]) - 1
if "(" in x[2]:
y = x[2][1:-1].split(",")
data[i] = float(y[0]) + 1.j * float(y[1])
else:
data[i] = complex(x)
return sp.coo_matrix((data, (row, col)), shape = (n, m))
def npvec2ffvec(v:Np1D) -> str:
filename = utilities.getNewFilename("v", "tmp")
with open(filename, 'w', buffering = 1) as f:
f.write(str(len(v)) + '\n')
for x in v:
if v.dtype == np.complex:
f.write("({0},{1})\n".format(np.real(x), np.imag(x)))
else:
f.write(str(x) + '\n')
return filename
def spmat2ffmat(m:Np2D) -> str:
mEff = m.tocoo()
filename = utilities.getNewFilename("m", "tmp")
with open(filename, 'w', buffering = 1) as f:
f.write(("# Sparse Matrix (Morse)\n# first line: n m (is symmetic) "
"nbcoef\n# after for each nonzero coefficient: i j a_ij "
"where (i,j) \in {1,...,n}x{1,...,m}\n"))
f.write("{} {} 0 {}\n".format(mEff.shape[0], mEff.shape[1], mEff.nnz))
for i in range(mEff.nnz):
r = mEff.row[i]
c = mEff.col[i]
x = mEff.data[i]
if mEff.dtype == np.complex:
f.write("{} {} ({},{})\n".format(r, c, np.real(x), np.imag(x)))
else:
f.write("{} {} {}\n".format(r, c, x))
return filename

Event Timeline