Ejemplo n.º 1
0
def build_particle_collection(definition: dict,
                              validate: bool = True) -> ParticleCollection:
    if validate:
        validation.particle_list(definition)
    definition = definition["ParticleList"]
    particles = ParticleCollection()
    for name, particle_def in definition.items():
        particles.add(build_particle(name, particle_def))
    return particles
Ejemplo n.º 2
0
def particle_selection(output_dir, particle_database: ParticleCollection):
    selection = ParticleCollection()
    selection += particle_database.filter(lambda p: p.name.startswith("pi"))
    selection += particle_database.filter(lambda p: p.name.startswith("K"))
    selection += particle_database.filter(lambda p: p.name.startswith("D"))
    selection += particle_database.filter(lambda p: p.name.startswith("J/psi"))
    io.write(selection, output_dir + XML_FILE)
    io.write(selection, output_dir + YAML_FILE)
    return selection
Ejemplo n.º 3
0
def _generate_particle_collection(
    graphs: List[StateTransitionGraph[ParticleWithSpin]],
) -> ParticleCollection:
    particles = ParticleCollection()
    for graph in graphs:
        for edge_props in map(graph.get_edge_props, graph.edges):
            particle_name = edge_props[0].name
            if particle_name not in particles:
                particles.add(edge_props[0])
    return particles
Ejemplo n.º 4
0
 def get_intermediate_particles(self) -> ParticleCollection:
     """Extract the names of the intermediate state particles."""
     intermediate_states = ParticleCollection()
     for graph in self.solutions:
         for edge_props in map(
             graph.get_edge_props, graph.get_intermediate_state_edge_ids()
         ):
             if edge_props:
                 particle, _ = edge_props
                 if particle not in intermediate_states:
                     intermediate_states.add(particle)
     return intermediate_states
Ejemplo n.º 5
0
def load_pdg() -> ParticleCollection:
    all_pdg_particles = PdgDatabase.findall(
        lambda item: item.charge is not None and item.charge.is_integer(
        )  # remove quarks
        and item.J is not None  # remove new physics and nuclei
        and abs(item.pdgid) < 1e9  # p and n as nucleus
        and item.name not in __skip_particles and not (
            item.mass is None and not item.name.startswith("nu")))
    particle_collection = ParticleCollection()
    for pdg_particle in all_pdg_particles:
        new_particle = __convert_pdg_instance(pdg_particle)
        particle_collection.add(new_particle)
    return particle_collection
Ejemplo n.º 6
0
def build_particle_collection(definition: dict) -> ParticleCollection:
    if isinstance(definition, dict):
        definition = definition.get("root", definition)
    if isinstance(definition, dict):
        definition = definition.get("ParticleList", definition)
    if isinstance(definition, dict):
        definition = definition.get("Particle", definition)
    if isinstance(definition, list):
        particle_list: Union[List[dict], ValuesView] = definition
    elif isinstance(definition, dict):
        particle_list = definition.values()
    else:
        raise ValueError(
            "The following definition cannot be converted to a ParticleCollection\n"
            f"{definition}")
    collection = ParticleCollection()
    for particle_def in particle_list:
        collection.add(build_particle(particle_def))
    return collection
Ejemplo n.º 7
0
 def test_init(particle_database: ParticleCollection):
     new_pdg = ParticleCollection(particle_database)
     assert new_pdg is not particle_database
     assert new_pdg == particle_database
     with pytest.raises(TypeError):
         ParticleCollection(1)  # type: ignore
Ejemplo n.º 8
0
    def __init__(  # pylint: disable=too-many-arguments,too-many-branches
        self,
        initial_state: Sequence[StateDefinition],
        final_state: Sequence[StateDefinition],
        particles: Optional[ParticleCollection] = None,
        allowed_intermediate_particles: Optional[List[str]] = None,
        interaction_type_settings: Dict[
            InteractionTypes, Tuple[EdgeSettings, NodeSettings]
        ] = None,
        formalism_type: str = "helicity",
        topology_building: str = "isobar",
        number_of_threads: Optional[int] = None,
        solving_mode: SolvingMode = SolvingMode.Fast,
        reload_pdg: bool = False,
    ) -> None:
        if interaction_type_settings is None:
            interaction_type_settings = {}
        allowed_formalism_types = [
            "helicity",
            "canonical-helicity",
            "canonical",
        ]
        if formalism_type not in allowed_formalism_types:
            raise NotImplementedError(
                f"Formalism type {formalism_type} not implemented."
                f" Use {allowed_formalism_types} instead."
            )
        self.__formalism_type = str(formalism_type)
        self.__particles = ParticleCollection()
        if particles is not None:
            self.__particles = particles
        if number_of_threads is None:
            self.number_of_threads = multiprocessing.cpu_count()
        else:
            self.number_of_threads = int(number_of_threads)
        self.reaction_mode = str(solving_mode)
        self.initial_state = initial_state
        self.final_state = final_state
        self.interaction_type_settings = interaction_type_settings

        self.interaction_determinators: List[InteractionDeterminator] = [
            LeptonCheck(),
            GammaCheck(),
        ]
        self.final_state_groupings: Optional[List[List[List[str]]]] = None
        self.allowed_interaction_types: List[InteractionTypes] = [
            InteractionTypes.Strong,
            InteractionTypes.EM,
            InteractionTypes.Weak,
        ]
        self.filter_remove_qns: Set[Type[NodeQuantumNumber]] = set()
        self.filter_ignore_qns: Set[Type[NodeQuantumNumber]] = set()
        if formalism_type == "helicity":
            self.filter_remove_qns = {
                NodeQuantumNumbers.l_magnitude,
                NodeQuantumNumbers.l_projection,
                NodeQuantumNumbers.s_magnitude,
                NodeQuantumNumbers.s_projection,
            }
        if "helicity" in formalism_type:
            self.filter_ignore_qns = {NodeQuantumNumbers.parity_prefactor}
        int_nodes = []
        use_mass_conservation = True
        use_nbody_topology = False
        if topology_building == "isobar":
            if len(initial_state) == 1:
                int_nodes.append(InteractionNode("TwoBodyDecay", 1, 2))
        else:
            int_nodes.append(
                InteractionNode(
                    "NBodyScattering", len(initial_state), len(final_state)
                )
            )
            use_nbody_topology = True
            # turn of mass conservation, in case more than one initial state
            # particle is present
            if len(initial_state) > 1:
                use_mass_conservation = False

        if not self.interaction_type_settings:
            self.interaction_type_settings = (
                create_default_interaction_settings(
                    formalism_type,
                    nbody_topology=use_nbody_topology,
                    use_mass_conservation=use_mass_conservation,
                )
            )
        self.topology_builder = SimpleStateTransitionTopologyBuilder(int_nodes)

        if reload_pdg or len(self.__particles) == 0:
            self.__particles = load_default_particles()

        self.__allowed_intermediate_particles = list()
        if allowed_intermediate_particles is not None:
            self.set_allowed_intermediate_particles(
                allowed_intermediate_particles
            )
        else:
            self.__allowed_intermediate_particles = [
                create_edge_properties(x) for x in self.__particles
            ]
Ejemplo n.º 9
0
    def collapse_graphs(
        self,
    ) -> List[StateTransitionGraph[ParticleCollection]]:
        def merge_into(
            graph: StateTransitionGraph[Particle],
            merged_graph: StateTransitionGraph[ParticleCollection],
        ) -> None:
            if (
                graph.get_intermediate_state_edge_ids()
                != merged_graph.get_intermediate_state_edge_ids()
            ):
                raise ValueError(
                    "Cannot merge graphs that don't have the same edge IDs"
                )
            for i in graph.edges:
                particle = graph.get_edge_props(i)
                other_particles = merged_graph.get_edge_props(i)
                if particle not in other_particles:
                    other_particles += particle

        def is_same_shape(
            graph: StateTransitionGraph[Particle],
            merged_graph: StateTransitionGraph[ParticleCollection],
        ) -> bool:
            if graph.edges != merged_graph.edges:
                return False
            for edge_id in (
                graph.get_initial_state_edge_ids()
                + graph.get_final_state_edge_ids()
            ):
                edge_prop = merged_graph.get_edge_props(edge_id)
                if len(edge_prop) != 1:
                    return False
                other_particle = next(iter(edge_prop))
                if other_particle != graph.get_edge_props(edge_id):
                    return False
            return True

        graphs = self.get_particle_graphs()
        inventory: List[StateTransitionGraph[ParticleCollection]] = list()
        for graph in graphs:
            append_to_inventory = True
            for merged_graph in inventory:
                if is_same_shape(graph, merged_graph):
                    merge_into(graph, merged_graph)
                    append_to_inventory = False
                    break
            if append_to_inventory:
                new_edge_props = {
                    edge_id: ParticleCollection(
                        {graph.get_edge_props(edge_id)}
                    )
                    for edge_id in graph.edges
                }
                inventory.append(
                    StateTransitionGraph[ParticleCollection](
                        topology=Topology(
                            nodes=set(graph.nodes), edges=graph.edges
                        ),
                        node_props={
                            i: graph.get_node_props(i) for i in graph.nodes
                        },
                        edge_props=new_edge_props,
                    )
                )
        return inventory