
# This file was generated by decaytreeedit-backend
# Copyright © 2025 Kai Habermann

# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

# The Author(s) shall be credited in any publication or presentation that uses this software, including but not limited to conference presentations, journal articles, and theses. The Authors shall be credited by reference to the decayangle and decayamplitude repositories, as well as the citation of the original paper: https://doi.org/10.1103/PhysRevD.111.056015

# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 

from decayamplitude.resonance import Resonance
from decayamplitude.rotation import QN
from decayamplitude.chain import MultiChain
from decayamplitude.combiner import ChainCombiner
from decayamplitude.particle import Particle, DecaySetup
from decayamplitude.backend import numpy as np
from decayangle.decay_topology import Topology, Node
from decayangle.config import config as decayangle_config
from decayamplitude.kinematics_helpers import mass_from_node

import jax

decayangle_config.backend = "numpy"
decayangle_config.sorting = "value"  # this makes sure, that the order of entries in a node is handeled internaly and we do not have to worry about it

if hasattr(decayangle_config, "parallel_cores"):
    decayangle_config.parallel_cores = "auto"
    print("parallel_cores: ", decayangle_config.get_parallel_cores())
if hasattr(decayangle_config, "parallel_chunk_size"):
    decayangle_config.parallel_chunk_size = "auto"
    print("parallel_chunk_size: ", decayangle_config.get_parallel_chunk_size())

import os 
os.environ['XLA_FLAGS'] = "--xla_disable_hlo_passes=constant_folding"
os.environ["JAX_USE_SIMPLIFIED_JAXPR_CONSTANTS"] = "True"
jax.config.update("jax_enable_x64", True)

from jax import jit, grad

def constant_lineshape(L, S, *args):
    #This is a dummy lineshape function, it does nothing, but is needed for the code to work
    # It is suited to model a mother resonance for example
    return 1.0

def BW_lineshape(mass):
    # usually the function is called for a fixed set of points in the phasespace. 
    # Thus we can give the mass values as fixed
    # This allows the compiler to optimize the function better
    # decayamplitude will provide l and s values per default for the resonances, but not the mass values
    def BW(l,s, m0, gamma):
        return 1 / (mass**2 - m0**2 + 1j * mass * gamma) 
    return BW


topologies = [
        Topology(0, decay_topology=((2, 3), 1)),
        Topology(0, decay_topology=((1, 3), 2))
    ]
        
final_state_qn = {
    1: Particle(spin=1, parity=1, name="Lambda_c()+"), 
    2: Particle(spin=0, parity=-1, name="Dbar0"), 
    3: Particle(spin=0, parity=-1, name="K-"), 
}
setup = DecaySetup(final_state_particles=final_state_qn)
topologies = [
    setup.symmetrize(topology) for topology in topologies
]

def amplitude(momenta):
    # momenta has the form of 
    # {
    #  1: np.array(shape=(...,4)), with indices 0,1,2,3 for p_x,p_y,p_z,E
    #  2: np.array(shape=(...,4)), with indices 0,1,2,3 for p_x,p_y,p_z,E
    #  ...
    #}

    resonances = {
        0:    [
            Resonance(Node(0), quantum_numbers=QN(1, 1), lineshape=constant_lineshape, argnames=[], preserve_partity=False, name='Lambda_b()0') 
            # Mother particle, set the QN to what they need to be for your decay. Usually a weak initial decay is assumed, so parity is not preserved. If this is not the case set it to True here or in the frontend.
                    # Replace the lineshape with a function of your liking, the call signatrue has to be f(L, S, *args), where the args will be exposed under the names you give in argnames
                    # The mass points at which to evaluate the lineshape are not given at runtime. Look at the bw_lineshpe for details
            ],
        
        (2, 3): [
        Resonance(Node((2, 3)), quantum_numbers=QN(2, -1), lineshape=constant_lineshape, argnames=[], preserve_partity=True, name='D_s_Kmatrix'),
            Resonance(Node((2, 3)), quantum_numbers=QN(0, 1), lineshape=constant_lineshape, argnames=[], preserve_partity=True, name='D_s0^*(2317)-')
        ],

        (1, 3): [
        Resonance(Node((1, 3)), quantum_numbers=QN(3, -1), lineshape=constant_lineshape, argnames=[], preserve_partity=True, name='Xi_c(2815)0'),
            Resonance(Node((1, 3)), quantum_numbers=QN(1, -1), lineshape=constant_lineshape, argnames=[], preserve_partity=True, name='Xi_c(2923)')
        ]
    }


    chains = [
        MultiChain(
            topology=topology,
            resonances = resonances,
            momenta = momenta,
            final_state_qn = final_state_qn
        ) for topology in topologies
    ]
    full = ChainCombiner(chains)
    # Start parameters for lineshape fitting
    start_parameters = {}
    
    # Add start parameters to the full object for easy access
    full.start_parameters = start_parameters

    return full

def test_Lb2LcD0K():



    import json
    import numpy as onp
    M_lb = 5.61951  # Mass of Lambda_b in GeV/c^2
    m_Lc = 2.28646  # Mass of Lambda_c+ in GeV/c^2
    m_D0 = 1.86484  # Mass of D0bar in GeV/c^2
    m_K = 0.49368   # Mass of K- in GeV/c^2

    with open("tests/test_data/Lb2LcD0K_momenta.json", "r") as f:
        momenta = json.load(f)
        momenta = {
            int(k): onp.array(v) for k, v in momenta.items()
        }
    full = amplitude(momenta)

    unpolarized, param_names = full.unpolarized_amplitude(full.generate_couplings())

    start_params = {
        name: full.start_parameters.get(name, 1.0) for name in param_names
    }

    print("Compiling unpolarized amplitude...")
    unpolarized = jit(unpolarized)
    unolarized_values = unpolarized(**start_params)
    print("Unpolarized amplitude compiled.")
    unolarized_values = onp.array(unolarized_values)
    
    # Calculate the weights
    weights_calc = onp.abs(onp.array(unolarized_values))**2 
    

if __name__ == "__main__":
    test_Lb2LcD0K()