#! /usr/bin/env python3
"""------------------------------*- python -*----------------------------------
  ==  == ====== ====   ====    |
                    \\     ||  | HZDR Multiphase Case Collection for OpenFOAM
  ======   //   ||  || ===//   | Website: https://doi.org/10.14278/rodare.811
  ||  ||  //    ||  // || \\   | License: Creative Commons Attribution 4.0
  ==  == ====== ====   ==  ==  |
-------------------------------------------------------------------------------
License
    This file is part of the HZDR Multiphase Case Collection for OpenFOAM.

    Copyright (C) 2022 Helmholtz-Zentrum Dresden-Rossendorf

    The HZDR Multiphase Case Collection for OpenFOAM is licensed under the
    Creative Commons Attribution 4.0 International License. To view a copy of
    this license, visit http://creativecommons.org/licenses/by/4.0/ or send a
    letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.

Description
    Reconstruct a three-dimensional bubble trajectory from the lateral position
    and from the inlet velocity, which is integrated over time.

----------------------------------------------------------------------------"""

import numpy as np


def closest(array, value, col=0):
    """Find closest value in array"""
    return array[np.abs(array[:,col] - value).argmin()]

#pylint: disable=unnecessary-lambda-assignment
conv = lambda s: float(s.strip(b'()'))
convs = {0:conv}
for i in range(1, 4):
    convs[i] = conv

fname='postProcessing/probes/0/U.water'
print('Loading ', fname)
data=np.loadtxt(fname, converters=convs)[:,[0,3]]

print('Calculating Z')
t=data[:,0]
u=data[:,1]
dt=(t[1:]-t[:-1])[-1]
dz=-dt*u
z=np.cumsum(dz)
tz=np.vstack((t,z)).T

fname='postProcessing/trackBubble/0/trackBubble.dat_processed'
print('Loading ', fname)
posxy=np.loadtxt(fname)[:,[0,1,2]]


print('Selecting correct times from z')
tempt=np.array([])
tempz=np.array([])

for time in posxy[:,0]:
    tempt=np.append(tempt, closest(tz, time)[0])
    tempz=np.append(tempz, closest(tz, time)[1])

print('Maximum time deviation: ', np.max(tempt-posxy[:,0]))

fname='postProcessing/3Dtrajectory.dat'
print('Saving ', fname)
np.savetxt(fname, np.hstack((posxy, tempz[:,np.newaxis])))

print('done')
