#!/usr/bin

import numpy as np
import scipy.optimize
import pdb
"""
This file gathers all the functions required for the solution of the wave problem in an elastic bar following a gradient damage model.
"""


def computeFragmentsLength(dx,x,damage,thresh):
    index=np.where(damage<=thresh)[0]
    lengths=[]
    start=index[0]
    end=index[0]
    ## loop over unbroken cells
    for k in range(len(index))[1:]:
        ## next cell is not a neighbor of the current one -> crack inbetween
        if (index[k]!=index[k-1]+1):
            end=index[k-1]
            #print ("fragment detected!",start,end,y[end]-y[start]+dx)
            lengths.append(x[end]-x[start]+dx)
            #pdb.set_trace()
            start=index[k]
        else :
            if k<len(index)-1: continue
            else :
                end=index[k-1]
                # print ("fragment detected!",start,end,y[end]-y[start]+dx)
                lengths.append(x[end]-x[start]+dx)
    return lengths

def computeMaxSpeed(U,damagedTangentModulus,density,c_damage):
    c_elast=[]
    for i in range(np.shape(U)[0]):
        c_elast.append(np.sqrt(damagedTangentModulus(U[i,2],U[i,0])/density))
    #print (max(c_elast),c_damage)
    return max(max(c_elast),c_damage)

def positivePart(f):
    return (np.abs(f)+f)/2.

def negativePart(f):
    return (np.abs(f)-f)/2.

