Skip to content

cosmology

cosmology

Author: Corentin Ravoux

Description : Classes to return a Dachshund input based on data that can be treated via picca software.

DeltaModifier

DeltaModifier(pwd, delta_path)

Bases: object

Transform delta files: shuffle, redshift-cut and subsample lines of sight.

Used both to build null (shuffled) mocks and to thin the line-of-sight density, optionally matching a reference density/separation profile.

Store the output and input delta directories.

Parameters:

Name Type Description Default
pwd str

Output directory for the modified deltas.

required
delta_path str

Input delta directory.

required
Source code in lelantos/cosmology.py
527
528
529
530
531
532
533
534
535
def __init__(self, pwd, delta_path):
    """Store the output and input delta directories.

    Args:
        pwd (str): Output directory for the modified deltas.
        delta_path (str): Input delta directory.
    """
    self.pwd = pwd
    self.delta_path = delta_path

shuffle_deltas

shuffle_deltas(other_delta_path=None, other_path_out=None, seed=None)

Randomly permute all delta/ivar pixels to build a null field.

Parameters:

Name Type Description Default
other_delta_path str

Second delta set shuffled in lock-step (same permutation).

None
other_path_out str

Output directory for the second set.

None
seed int

RNG seed (random if None).

None
Source code in lelantos/cosmology.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def shuffle_deltas(self, other_delta_path=None, other_path_out=None, seed=None):
    """Randomly permute all delta/ivar pixels to build a null field.

    Args:
        other_delta_path (str, optional): Second delta set shuffled in
            lock-step (same permutation).
        other_path_out (str, optional): Output directory for the second set.
        seed (int, optional): RNG seed (random if None).
    """
    namefile = get_delta_list(self.delta_path)
    namefile_other = None
    if other_delta_path is not None:
        namefile_other = get_delta_list(other_delta_path)

    (delta, ivar, delta_other, weight_other) = self.get_delta_sigma_array(
        namefile, namefile_other=namefile_other
    )
    if seed is None:
        seed = np.random.randint(10000000)
    np.random.seed(seed)
    ivar_rand = np.random.permutation(ivar)
    delta_rand = np.random.permutation(delta)
    if other_delta_path is not None:
        np.random.seed(seed)
        weight_other_rand = np.random.permutation(weight_other)
        delta_other_rand = np.random.permutation(delta_other)

    self.write_delta_sigma_array(
        delta_rand,
        ivar_rand,
        namefile,
        other_delta_path=other_delta_path,
        namefile_other=namefile_other,
        delta_other_rand=delta_other_rand,
        weight_other_rand=weight_other_rand,
        other_path_out=other_path_out,
    )

shuffle_deltas_cut_z

shuffle_deltas_cut_z(n_cut, zmin, zmax, other_delta_path=None, other_path_out=None, seed=None)

Shuffle delta/ivar pixels independently within redshift bins.

Parameters:

Name Type Description Default
n_cut int

Number of redshift bins the shuffling is confined to.

required
zmin float

Minimum redshift of the binning.

required
zmax float

Maximum redshift of the binning.

required
other_delta_path str

Second delta set (lock-step).

None
other_path_out str

Output directory for the second set.

None
seed int

RNG seed (random if None).

None
Source code in lelantos/cosmology.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
def shuffle_deltas_cut_z(
    self, n_cut, zmin, zmax, other_delta_path=None, other_path_out=None, seed=None
):
    """Shuffle delta/ivar pixels independently within redshift bins.

    Args:
        n_cut (int): Number of redshift bins the shuffling is confined to.
        zmin (float): Minimum redshift of the binning.
        zmax (float): Maximum redshift of the binning.
        other_delta_path (str, optional): Second delta set (lock-step).
        other_path_out (str, optional): Output directory for the second set.
        seed (int, optional): RNG seed (random if None).
    """
    namefile = get_delta_list(self.delta_path)
    namefile_other = None
    if other_delta_path is not None:
        namefile_other = get_delta_list(other_delta_path)
    redshift_cut = np.linspace(zmin, zmax, n_cut + 1)
    (delta, ivar, delta_other, weight_other) = self.get_delta_sigma_array_cut_z(
        namefile, redshift_cut, namefile_other=namefile_other
    )

    if seed is None:
        seed = np.random.randint(10000000)
    ivar_rand, delta_rand = [], []
    np.random.seed(seed)
    for k in range(n_cut):
        ivar_rand.append(np.random.permutation(ivar[k]))
    np.random.seed(seed)
    for k in range(n_cut):
        delta_rand.append(np.random.permutation(delta[k]))
    if other_delta_path is not None:
        weight_other_rand, delta_other_rand = [], []
        np.random.seed(seed)
        for k in range(n_cut):
            weight_other_rand.append(np.random.permutation(weight_other[k]))
        np.random.seed(seed)
        for k in range(n_cut):
            delta_other_rand.append(np.random.permutation(delta_other[k]))

    self.write_delta_sigma_array_cut_z(
        delta_rand,
        ivar_rand,
        namefile,
        n_cut,
        redshift_cut,
        other_delta_path=other_delta_path,
        namefile_other=namefile_other,
        delta_other_rand=delta_other_rand,
        weight_other_rand=weight_other_rand,
        other_path_out=other_path_out,
    )

get_delta_sigma_array

get_delta_sigma_array(namefile, namefile_other=None)

Concatenate the delta and ivar pixels of all delta files.

Parameters:

Name Type Description Default
namefile list[str]

Delta file paths.

required
namefile_other list[str]

Second delta set.

None

Returns:

Name Type Description
tuple

(delta, ivar, delta_other, weight_other) flat arrays

(the *_other entries are None if no second set is given).

Source code in lelantos/cosmology.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
def get_delta_sigma_array(self, namefile, namefile_other=None):
    """Concatenate the delta and ivar pixels of all delta files.

    Args:
        namefile (list[str]): Delta file paths.
        namefile_other (list[str], optional): Second delta set.

    Returns:
        tuple: ``(delta, ivar, delta_other, weight_other)`` flat arrays
        (the ``*_other`` entries are None if no second set is given).
    """
    weight_other, delta_other = None, None
    if namefile_other is not None:
        weight_other, delta_other = [], []
    ivar, delta = [], []
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=True)
        delta_tomo.read()
        for j in range(len(delta_tomo.delta_array)):
            ivar.append(delta_tomo.delta_array[j].ivar)
            delta.append(delta_tomo.delta_array[j].delta)
        if namefile_other is not None:
            delta_tomo_other = tomographic_objects.Delta(
                name=namefile_other[i], pk1d_type=False
            )
            delta_tomo_other.read()
            for j in range(len(delta_tomo_other.delta_array)):
                weight_other.append(delta_tomo_other.delta_array[j].weights)
                delta_other.append(delta_tomo_other.delta_array[j].delta)
    ivar = np.concatenate(ivar, axis=0)
    delta = np.concatenate(delta, axis=0)
    if namefile_other is not None:
        weight_other = np.concatenate(weight_other, axis=0)
        delta_other = np.concatenate(delta_other, axis=0)
    return (delta, ivar, delta_other, weight_other)

write_delta_sigma_array

write_delta_sigma_array(delta_rand, ivar_rand, namefile, other_delta_path=None, namefile_other=None, delta_other_rand=None, weight_other_rand=None, other_path_out=None)

Write shuffled delta/ivar pixels back into per-file delta objects.

Parameters:

Name Type Description Default
delta_rand ndarray

Shuffled delta pixels.

required
ivar_rand ndarray

Shuffled ivar pixels.

required
namefile list[str]

Input delta file paths (define the LOS lengths).

required
other_delta_path str

Second delta set input directory.

None
namefile_other list[str]

Second delta file paths.

None
delta_other_rand ndarray

Shuffled second deltas.

None
weight_other_rand ndarray

Shuffled second weights.

None
other_path_out str

Second delta set output directory.

None
Source code in lelantos/cosmology.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def write_delta_sigma_array(
    self,
    delta_rand,
    ivar_rand,
    namefile,
    other_delta_path=None,
    namefile_other=None,
    delta_other_rand=None,
    weight_other_rand=None,
    other_path_out=None,
):
    """Write shuffled delta/ivar pixels back into per-file delta objects.

    Args:
        delta_rand (numpy.ndarray): Shuffled delta pixels.
        ivar_rand (numpy.ndarray): Shuffled ivar pixels.
        namefile (list[str]): Input delta file paths (define the LOS lengths).
        other_delta_path (str, optional): Second delta set input directory.
        namefile_other (list[str], optional): Second delta file paths.
        delta_other_rand (numpy.ndarray, optional): Shuffled second deltas.
        weight_other_rand (numpy.ndarray, optional): Shuffled second weights.
        other_path_out (str, optional): Second delta set output directory.
    """
    ibegin = 0
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=True)
        delta_tomo.read()
        delta_obj_list = []
        for j in range(len(delta_tomo.delta_array)):
            delta_tomo.delta_array[j].de = delta_rand[
                ibegin : ibegin + len(delta_tomo.delta_array[j].de)
            ]
            delta_tomo.delta_array[j].iv = ivar_rand[
                ibegin : ibegin + len(delta_tomo.delta_array[j].iv)
            ]
            ibegin = ibegin + len(delta_tomo.delta_array[j].de)
            delta_obj_list.append(delta_tomo.delta_array[j])
        name_delta = os.path.join(
            self.pwd, namefile[i].split(self.delta_path)[-1].split("/")[-1]
        )
        new_delta_tomo = tomographic_objects.Delta(name=name_delta, pk1d_type=True)
        new_delta_tomo.delta_array = delta_obj_list
        new_delta_tomo.write()

    if other_delta_path is not None:
        ibegin = 0
        for i in range(len(namefile_other)):
            delta_tomo_other = tomographic_objects.Delta(
                name=namefile_other[i], pk1d_type=False
            )
            delta_tomo_other.read()
            delta_obj_list = []
            for j in range(len(delta_tomo_other.delta_array)):
                delta_tomo_other.delta_array[j].de = delta_other_rand[
                    ibegin : ibegin + len(delta_tomo_other.delta_array[j].de)
                ]
                delta_tomo_other.delta_array[j].we = weight_other_rand[
                    ibegin : ibegin + len(delta_tomo_other.delta_array[j].we)
                ]
                ibegin = ibegin + len(delta_tomo_other.delta_array[j].de)
                delta_obj_list.append(delta_tomo_other.delta_array[j])
            name_delta = os.path.join(
                other_path_out,
                namefile_other[i].split(other_delta_path)[-1].split("/")[-1],
            )
            new_delta_tomo = tomographic_objects.Delta(
                name=name_delta, pk1d_type=False
            )
            new_delta_tomo.delta_array = delta_obj_list
            new_delta_tomo.write()

get_delta_sigma_array_cut_z

get_delta_sigma_array_cut_z(namefile, redshift_cut, namefile_other=None)

Concatenate delta/ivar pixels grouped into redshift bins.

Parameters:

Name Type Description Default
namefile list[str]

Delta file paths.

required
redshift_cut array - like

Bin edges (n_cut + 1 values).

required
namefile_other list[str]

Second delta set.

None

Returns:

Name Type Description
tuple

(delta, ivar, delta_other, weight_other) as lists of

per-bin flat arrays.

Source code in lelantos/cosmology.py
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
def get_delta_sigma_array_cut_z(self, namefile, redshift_cut, namefile_other=None):
    """Concatenate delta/ivar pixels grouped into redshift bins.

    Args:
        namefile (list[str]): Delta file paths.
        redshift_cut (array-like): Bin edges (``n_cut + 1`` values).
        namefile_other (list[str], optional): Second delta set.

    Returns:
        tuple: ``(delta, ivar, delta_other, weight_other)`` as lists of
        per-bin flat arrays.
    """
    n_cut = len(redshift_cut) - 1
    weight_other, delta_other = None, None
    if namefile_other is not None:
        weight_other, delta_other = [[] for i in range(n_cut)], [
            [] for i in range(n_cut)
        ]
    ivar, delta = [[] for i in range(n_cut)], [[] for i in range(n_cut)]
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=True)
        delta_tomo.read()
        for j in range(len(delta_tomo.delta_array)):
            redshift = (
                10 ** delta_tomo.delta_array[j].log_lambda / utils.lambdaLy
            ) - 1
            for k in range(n_cut):
                mask = (redshift >= redshift_cut[k]) & (
                    redshift < redshift_cut[k + 1]
                )
                ivar[k].append(delta_tomo.delta_array[j].ivar[mask])
                delta[k].append(delta_tomo.delta_array[j].delta[mask])
        if namefile_other is not None:
            delta_tomo_other = tomographic_objects.Delta(
                name=namefile_other[i], pk1d_type=False
            )
            delta_tomo_other.read()
            for j in range(len(delta_tomo_other.delta_array)):
                redshift = (
                    10 ** delta_tomo_other.delta_array[j].log_lambda
                    / utils.lambdaLy
                ) - 1
                for k in range(n_cut):
                    mask = (redshift >= redshift_cut[k]) & (
                        redshift < redshift_cut[k + 1]
                    )
                    weight_other[k].append(
                        delta_tomo_other.delta_array[j].weights[mask]
                    )
                    delta_other[k].append(
                        delta_tomo_other.delta_array[j].delta[mask]
                    )
    for k in range(n_cut):
        ivar[k] = np.concatenate(ivar[k], axis=0)
        delta[k] = np.concatenate(delta[k], axis=0)
    if namefile_other is not None:
        for k in range(n_cut):
            weight_other[k] = np.concatenate(weight_other[k], axis=0)
            delta_other[k] = np.concatenate(delta_other[k], axis=0)
    return (delta, ivar, delta_other, weight_other)

write_delta_sigma_array_cut_z

write_delta_sigma_array_cut_z(delta_rand, ivar_rand, namefile, n_cut, redshift_cut, other_delta_path=None, namefile_other=None, delta_other_rand=None, weight_other_rand=None, other_path_out=None)

Write per-redshift-bin shuffled pixels back into delta objects.

Parameters:

Name Type Description Default
delta_rand list[array]

Per-bin shuffled delta pixels.

required
ivar_rand list[array]

Per-bin shuffled ivar pixels.

required
namefile list[str]

Input delta file paths.

required
n_cut int

Number of redshift bins.

required
redshift_cut array - like

Bin edges.

required
other_delta_path str

Second delta set input directory.

None
namefile_other list[str]

Second delta file paths.

None
delta_other_rand list[array]

Second shuffled deltas.

None
weight_other_rand list[array]

Second shuffled weights.

None
other_path_out str

Second delta set output directory.

None
Source code in lelantos/cosmology.py
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
def write_delta_sigma_array_cut_z(
    self,
    delta_rand,
    ivar_rand,
    namefile,
    n_cut,
    redshift_cut,
    other_delta_path=None,
    namefile_other=None,
    delta_other_rand=None,
    weight_other_rand=None,
    other_path_out=None,
):
    """Write per-redshift-bin shuffled pixels back into delta objects.

    Args:
        delta_rand (list[array]): Per-bin shuffled delta pixels.
        ivar_rand (list[array]): Per-bin shuffled ivar pixels.
        namefile (list[str]): Input delta file paths.
        n_cut (int): Number of redshift bins.
        redshift_cut (array-like): Bin edges.
        other_delta_path (str, optional): Second delta set input directory.
        namefile_other (list[str], optional): Second delta file paths.
        delta_other_rand (list[array], optional): Second shuffled deltas.
        weight_other_rand (list[array], optional): Second shuffled weights.
        other_path_out (str, optional): Second delta set output directory.
    """
    ibegin = [0 for i in range(n_cut)]
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=True)
        delta_tomo.read()
        delta_obj_list = []
        for j in range(len(delta_tomo.delta_array)):
            redshift = (
                10 ** delta_tomo.delta_array[j].log_lambda / utils.lambdaLy
            ) - 1
            for k in range(n_cut):
                mask = (redshift >= redshift_cut[k]) & (
                    redshift < redshift_cut[k + 1]
                )
                delta_tomo.delta_array[j].de[mask] = delta_rand[k][
                    ibegin[k] : ibegin[k] + len(delta_tomo.delta_array[j].de[mask])
                ]
                delta_tomo.delta_array[j].iv[mask] = ivar_rand[k][
                    ibegin[k] : ibegin[k] + len(delta_tomo.delta_array[j].iv[mask])
                ]
                ibegin[k] = ibegin[k] + len(delta_tomo.delta_array[j].de[mask])
            delta_obj_list.append(delta_tomo.delta_array[j])
        name_delta = os.path.join(
            self.pwd, namefile[i].split(self.delta_path)[-1].split("/")[-1]
        )
        new_delta_tomo = tomographic_objects.Delta(name=name_delta, pk1d_type=True)
        new_delta_tomo.delta_array = delta_obj_list
        new_delta_tomo.write()

    if other_delta_path is not None:
        ibegin = [0 for i in range(n_cut)]
        for i in range(len(namefile_other)):
            delta_tomo_other = tomographic_objects.Delta(
                name=namefile_other[i], pk1d_type=False
            )
            delta_tomo_other.read()
            delta_obj_list = []
            for j in range(len(delta_tomo_other.delta_array)):
                redshift = (
                    10 ** delta_tomo_other.delta_array[j].log_lambda
                    / utils.lambdaLy
                ) - 1
                for k in range(n_cut):
                    mask = (redshift >= redshift_cut[k]) & (
                        redshift < redshift_cut[k + 1]
                    )
                    delta_tomo_other.delta_array[j].de[mask] = delta_other_rand[k][
                        ibegin[k] : ibegin[k]
                        + len(delta_tomo_other.delta_array[j].de[mask])
                    ]
                    delta_tomo_other.delta_array[j].we[mask] = weight_other_rand[k][
                        ibegin[k] : ibegin[k]
                        + len(delta_tomo_other.delta_array[j].we[mask])
                    ]
                    ibegin[k] = ibegin[k] + len(
                        delta_tomo_other.delta_array[j].de[mask]
                    )
                delta_obj_list.append(delta_tomo_other.delta_array[j])
            name_delta = os.path.join(
                other_path_out,
                namefile_other[i].split(other_delta_path)[-1].split("/")[-1],
            )
            new_delta_tomo = tomographic_objects.Delta(
                name=name_delta, pk1d_type=False
            )
            new_delta_tomo.delta_array = delta_obj_list
            new_delta_tomo.write()

get_new_healpix

get_new_healpix(number_cut, random_density_parameter=None, number_repeat=1, iterative_selection_parameters=None, ra_cut_min=None, ra_cut_max=None, dec_cut_min=None, dec_cut_max=None, z_cut_min=None, z_cut_max=None, center_ra=True)

Build a (optionally thinned) set of lines of sight split by RA.

Dispatches to a plain, randomly-thinned, or iteratively density-matched selection depending on the arguments.

Parameters:

Name Type Description Default
number_cut int

Number of RA sub-regions.

required
random_density_parameter float

Target LOS density; None keeps all lines of sight.

None
number_repeat int

Number of iterative selection trials.

1
iterative_selection_parameters dict

Reference density / separation config for the iterative selection.

None
ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max float

Sky window.

required
z_cut_min, z_cut_max float

Redshift window.

required
center_ra bool

Recenter RA around 0.

True

Returns:

Name Type Description
dict

Per-RA-region lists of selected delta objects.

Source code in lelantos/cosmology.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
def get_new_healpix(
    self,
    number_cut,
    random_density_parameter=None,
    number_repeat=1,
    iterative_selection_parameters=None,
    ra_cut_min=None,
    ra_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    z_cut_min=None,
    z_cut_max=None,
    center_ra=True,
):
    """Build a (optionally thinned) set of lines of sight split by RA.

    Dispatches to a plain, randomly-thinned, or iteratively density-matched
    selection depending on the arguments.

    Args:
        number_cut (int): Number of RA sub-regions.
        random_density_parameter (float, optional): Target LOS density; None
            keeps all lines of sight.
        number_repeat (int, optional): Number of iterative selection trials.
        iterative_selection_parameters (dict, optional): Reference density /
            separation config for the iterative selection.
        ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max (float, optional):
            Sky window.
        z_cut_min, z_cut_max (float, optional): Redshift window.
        center_ra (bool, optional): Recenter RA around 0.

    Returns:
        dict: Per-RA-region lists of selected delta objects.
    """
    if random_density_parameter is None:
        deltas = self.create_healpix(
            number_cut,
            random=None,
            return_len_ra=False,
            ra_cut_min=ra_cut_min,
            ra_cut_max=ra_cut_max,
            dec_cut_min=dec_cut_min,
            dec_cut_max=dec_cut_max,
            center_ra=center_ra,
        )
    else:
        if number_repeat == 1:
            deltas = self.create_healpix(
                number_cut,
                random=random_density_parameter,
                return_len_ra=False,
                ra_cut_min=ra_cut_min,
                ra_cut_max=ra_cut_max,
                dec_cut_min=dec_cut_min,
                dec_cut_max=dec_cut_max,
                center_ra=center_ra,
            )
        else:
            if iterative_selection_parameters is None:
                return KeyError(
                    "Please dictionary parameter for the iterative selection"
                )
            deltas = self.iterate_healpix_creation(
                number_cut,
                random_density_parameter,
                number_repeat,
                iterative_selection_parameters,
                ra_cut_min=ra_cut_min,
                ra_cut_max=ra_cut_max,
                dec_cut_min=dec_cut_min,
                dec_cut_max=dec_cut_max,
                z_cut_min=z_cut_min,
                z_cut_max=z_cut_max,
            )
    return deltas

create_healpix

create_healpix(number_cut, random=None, return_len_ra=False, ra_cut_min=None, ra_cut_max=None, dec_cut_min=None, dec_cut_max=None, center_ra=True)

Split the lines of sight into RA sub-regions, optionally thinned.

Parameters:

Name Type Description Default
number_cut int

Number of RA sub-regions.

required
random float

Target LOS density for random thinning.

None
return_len_ra bool

Also return the number of LOS.

False
ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max float

Sky window.

required
center_ra bool

Recenter RA around 0.

True

Returns:

Type Description

dict | tuple: The per-region delta dict, or (deltas, n_los) when

return_len_ra is True.

Source code in lelantos/cosmology.py
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
def create_healpix(
    self,
    number_cut,
    random=None,
    return_len_ra=False,
    ra_cut_min=None,
    ra_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    center_ra=True,
):
    """Split the lines of sight into RA sub-regions, optionally thinned.

    Args:
        number_cut (int): Number of RA sub-regions.
        random (float, optional): Target LOS density for random thinning.
        return_len_ra (bool, optional): Also return the number of LOS.
        ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max (float, optional):
            Sky window.
        center_ra (bool, optional): Recenter RA around 0.

    Returns:
        dict | tuple: The per-region delta dict, or ``(deltas, n_los)`` when
        ``return_len_ra`` is True.
    """
    namefile = get_delta_list(self.delta_path)
    deltas = {}
    ra_array = []
    dec_array = []
    for cut in range(number_cut):
        deltas[cut] = []
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=True)
        delta_tomo.read()
        for j in range(len(delta_tomo.delta_array)):
            if center_ra:
                if delta_tomo.delta_array[j].ra * 180 / np.pi > 180:
                    ra = (delta_tomo.delta_array[j].ra * 180 / np.pi) - 360
                else:
                    ra = delta_tomo.delta_array[j].ra * 180 / np.pi
            else:
                ra = delta_tomo.delta_array[j].ra * 180 / np.pi
            dec = delta_tomo.delta_array[j].dec * 180 / np.pi
            if (
                (ra > ra_cut_min)
                & (ra < ra_cut_max)
                & (dec > dec_cut_min)
                & (dec < dec_cut_max)
            ):
                ra_array.append(ra)
                dec_array.append(dec)
                for cut in range(number_cut):
                    interval_ra = ((cut) / (number_cut)) * (
                        ra_cut_max - ra_cut_min
                    ) + ra_cut_min, ((cut + 1) / (number_cut)) * (
                        ra_cut_max - ra_cut_min
                    ) + ra_cut_min
                    if (ra > interval_ra[0]) & (ra <= interval_ra[1]):
                        if center_ra:
                            delta_tomo.delta_array[j].ra = (
                                delta_tomo.delta_array[j].ra - 2 * np.pi
                            )
                        deltas[cut].append(delta_tomo.delta_array[j])
    if random is not None:
        deltas = self.randomize_choice_of_los(
            deltas,
            random,
            number_cut,
            len(ra_array),
            ra_cut_min=ra_cut_min,
            ra_cut_max=ra_cut_max,
            dec_cut_min=dec_cut_min,
            dec_cut_max=dec_cut_max,
        )
    if return_len_ra:
        return (deltas, len(ra_array))
    else:
        return deltas

randomize_choice_of_los

randomize_choice_of_los(deltas_dict, random, number_cut, number_ra, ra_cut_min=None, ra_cut_max=None, dec_cut_min=None, dec_cut_max=None)

Randomly downsample the lines of sight to a target density.

Parameters:

Name Type Description Default
deltas_dict dict

Per-region delta lists.

required
random float

Target LOS density (per deg^2).

required
number_cut int

Number of RA sub-regions.

required
number_ra int

Current total number of lines of sight.

required
ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max float

Sky window (defines the area).

required

Returns:

Name Type Description
dict

The thinned per-region delta lists.

Source code in lelantos/cosmology.py
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def randomize_choice_of_los(
    self,
    deltas_dict,
    random,
    number_cut,
    number_ra,
    ra_cut_min=None,
    ra_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
):
    """Randomly downsample the lines of sight to a target density.

    Args:
        deltas_dict (dict): Per-region delta lists.
        random (float): Target LOS density (per deg^2).
        number_cut (int): Number of RA sub-regions.
        number_ra (int): Current total number of lines of sight.
        ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max (float, optional):
            Sky window (defines the area).

    Returns:
        dict: The thinned per-region delta lists.
    """
    deltas = deltas_dict.copy()
    density = number_ra / ((ra_cut_max - ra_cut_min) * (dec_cut_max - dec_cut_min))
    utils.Logger.add("density before random choice =" + str(density))
    random_cut = random / density
    ra_random = []
    dec_random = []
    for cut in range(number_cut):
        number_of_delta_to_select = int(round(len(deltas[cut]) * random_cut, 0))
        deltas[cut] = sample(deltas[cut], number_of_delta_to_select)
        for i in range(len(deltas[cut])):
            ra_random.append(deltas[cut][i].ra * 180 / np.pi)
            dec_random.append(deltas[cut][i].dec * 180 / np.pi)
    density = len(ra_random) / (
        (ra_cut_max - ra_cut_min) * (dec_cut_max - dec_cut_min)
    )
    utils.Logger.add("density after random choice =" + str(density))
    return deltas

iterate_healpix_creation

iterate_healpix_creation(number_cut, random_density_parameter, number_repeat, iterative_selection_parameters, property_file_name, ra_cut_min=None, ra_cut_max=None, dec_cut_min=None, dec_cut_max=None, z_cut_min=None, z_cut_max=None, center_ra=True)

Pick the random LOS thinning closest to a reference n(z)/separation.

Repeats the random selection number_repeat times and keeps the draw that best matches the reference density and mean-separation profiles.

Parameters:

Name Type Description Default
number_cut int

Number of RA sub-regions.

required
random_density_parameter float

Target LOS density.

required
number_repeat int

Number of random trials.

required
iterative_selection_parameters dict

Reference density/separation file names, Om and coordinate transform.

required
property_file_name str

Pixel-property file for the cartesian map.

required
ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max float

Sky window.

required
z_cut_min, z_cut_max float

Redshift window.

required
center_ra bool

Recenter RA around 0.

True

Returns:

Name Type Description
dict

The best-matching per-region delta selection.

Source code in lelantos/cosmology.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
def iterate_healpix_creation(
    self,
    number_cut,
    random_density_parameter,
    number_repeat,
    iterative_selection_parameters,
    property_file_name,
    ra_cut_min=None,
    ra_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    z_cut_min=None,
    z_cut_max=None,
    center_ra=True,
):
    """Pick the random LOS thinning closest to a reference n(z)/separation.

    Repeats the random selection ``number_repeat`` times and keeps the draw
    that best matches the reference density and mean-separation profiles.

    Args:
        number_cut (int): Number of RA sub-regions.
        random_density_parameter (float): Target LOS density.
        number_repeat (int): Number of random trials.
        iterative_selection_parameters (dict): Reference density/separation
            file names, ``Om`` and coordinate transform.
        property_file_name (str): Pixel-property file for the cartesian map.
        ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max (float, optional):
            Sky window.
        z_cut_min, z_cut_max (float, optional): Redshift window.
        center_ra (bool, optional): Recenter RA around 0.

    Returns:
        dict: The best-matching per-region delta selection.
    """
    density_names = iterative_selection_parameters["density_names"]
    dperp_names = iterative_selection_parameters["separation_names"]
    Om = iterative_selection_parameters["Om"]
    (rcomov, distang, inv_rcomov, inv_distang) = utils.get_cosmo_function(Om)
    coordinate_transform = iterative_selection_parameters["coordinate_transform"]
    suplementary_parameters = utils.return_suplementary_parameters(
        coordinate_transform, zmin=z_cut_min, zmax=z_cut_max
    )
    density_ref = {}
    dperp_ref = {}
    for cut in range(number_cut):
        density_ref[cut] = PixelAnalizer.read_density_file(density_names[cut])[1]
        dperp_ref[cut] = PixelAnalizer.read_dperp_file(dperp_names[cut])[1]
    min_density, min_dperp = np.inf, np.inf
    delta_to_keep = {}
    utils.Logger.add("Beginning of the random iteration selection")
    deltas_dict, number_ra = self.create_healpix(
        number_cut, random=False, return_len_ra=True, center_ra=center_ra
    )
    deltas_random = {}
    for i in range(number_repeat):
        utils.Logger.add("repeat " + str(i))
        utils.Logger.add("deltas " + str(i) + " computed")
        diff_dperp, diff_density = [], []
        deltas_random = self.randomize_choice_of_los(
            deltas_dict,
            random_density_parameter,
            number_cut,
            number_ra,
            ra_cut_min=ra_cut_min,
            ra_cut_max=ra_cut_max,
            dec_cut_min=dec_cut_min,
            dec_cut_max=dec_cut_max,
        )
        for cut in range(number_cut):
            delta_file = tomographic_objects.Delta(
                delta_file=None,
                delta_array=deltas_random[cut],
                name="delta_" + str(cut) + "_to_test.pickle",
            )
            delta_file.write()
            namefile = "delta_" + str(cut) + "_to_test.pickle"
            (ra, dec, z, zqso, ids, sigmas, deltas) = get_deltas(namefile)
            sky_deltas = np.array(
                [
                    [ra[i], dec[i], z[i][j], sigmas[i][j], deltas[i][j]]
                    for i in range(len(ra))
                    for j in range(len(z[i]))
                ]
            )
            sky_deltas = sky_deltas[
                utils.cut_sky_catalog(
                    sky_deltas[:, 0],
                    sky_deltas[:, 1],
                    sky_deltas[:, 2],
                    ramin=ra_cut_min,
                    ramax=ra_cut_max,
                    decmin=dec_cut_min,
                    decmax=dec_cut_max,
                    zmin=z_cut_min,
                    zmax=z_cut_max,
                )
            ]
            cartesian_deltas = np.zeros(sky_deltas.shape)
            (
                cartesian_deltas[:, 0],
                cartesian_deltas[:, 1],
                cartesian_deltas[:, 2],
            ) = utils.convert_sky_to_cartesian(
                sky_deltas[:, 0],
                sky_deltas[:, 1],
                sky_deltas[:, 2],
                coordinate_transform,
                rcomov=rcomov,
                distang=distang,
                suplementary_parameters=suplementary_parameters,
            )
            pixel = tomographic_objects.Pixel.init_from_property_files(
                property_file_name, pixel_array=cartesian_deltas, name=None
            )
            pixel_analyzer = PixelAnalizer(pixel=pixel)
            (
                zpar,
                dperpz,
                densityz,
            ) = pixel_analyzer.compute_plot_mean_distance_density("", plot=False)
            diff_dperp.append(
                np.mean(abs(np.array(dperpz) - np.array(dperp_ref[cut])))
            )
            diff_density.append(
                np.mean(abs(np.array(densityz) - np.array(density_ref[cut])))
            )
        utils.Logger.add(
            "Mean difference in term LOS density : {}".format(np.mean(diff_density))
        )
        utils.Logger.add(
            "Mean difference in term of Mean LOS separation : {}".format(
                np.mean(diff_dperp)
            )
        )
        if (np.mean(diff_density) < min_density) & (
            np.mean(diff_dperp) < min_dperp
        ):
            utils.Logger.add("Better at the repeat " + str(i))
            min_density = np.mean(diff_density)
            min_dperp = np.mean(diff_dperp)
            delta_to_keep = deltas_random
    for cut in range(number_cut):
        os.remove("delta_" + str(cut) + "_to_test.pickle")
    utils.Logger.add("End of the random iteration selection")
    return delta_to_keep

save_deltas

save_deltas(deltas, name_out, number_cut)

Write each RA sub-region of selected deltas to its own FITS file.

Parameters:

Name Type Description Default
deltas dict

Per-region delta lists.

required
name_out str

Output file base name.

required
number_cut int

Number of RA sub-regions.

required
Source code in lelantos/cosmology.py
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def save_deltas(self, deltas, name_out, number_cut):
    """Write each RA sub-region of selected deltas to its own FITS file.

    Args:
        deltas (dict): Per-region delta lists.
        name_out (str): Output file base name.
        number_cut (int): Number of RA sub-regions.
    """
    for cut in range(number_cut):
        delta = tomographic_objects.Delta(
            name=os.path.join(self.pwd, f"{name_out}_{cut}.fits"),
            delta_array=deltas[cut],
        )
        delta.write()

subsample_deltas

subsample_deltas(name_out, number_cut, random_density_parameter=None, number_repeat=1, iterative_selection_parameters=None, ra_cut_min=None, ra_cut_max=None, dec_cut_min=None, dec_cut_max=None, z_cut_min=None, z_cut_max=None, center_ra=True)

Build a (thinned) LOS selection and write it to disk.

Parameters:

Name Type Description Default
name_out str

Output file base name.

required
number_cut int

Number of RA sub-regions.

required
random_density_parameter float

Target LOS density.

None
number_repeat int

Number of iterative trials.

1
iterative_selection_parameters dict

Reference config.

None
ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max float

Sky window.

required
z_cut_min, z_cut_max float

Redshift window.

required
center_ra bool

Recenter RA around 0.

True
Source code in lelantos/cosmology.py
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
def subsample_deltas(
    self,
    name_out,
    number_cut,
    random_density_parameter=None,
    number_repeat=1,
    iterative_selection_parameters=None,
    ra_cut_min=None,
    ra_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    z_cut_min=None,
    z_cut_max=None,
    center_ra=True,
):
    """Build a (thinned) LOS selection and write it to disk.

    Args:
        name_out (str): Output file base name.
        number_cut (int): Number of RA sub-regions.
        random_density_parameter (float, optional): Target LOS density.
        number_repeat (int, optional): Number of iterative trials.
        iterative_selection_parameters (dict, optional): Reference config.
        ra_cut_min, ra_cut_max, dec_cut_min, dec_cut_max (float, optional):
            Sky window.
        z_cut_min, z_cut_max (float, optional): Redshift window.
        center_ra (bool, optional): Recenter RA around 0.
    """
    deltas = self.get_new_healpix(
        number_cut,
        random_density_parameter=random_density_parameter,
        number_repeat=number_repeat,
        iterative_selection_parameters=iterative_selection_parameters,
        ra_cut_min=ra_cut_min,
        ra_cut_max=ra_cut_max,
        dec_cut_min=dec_cut_min,
        dec_cut_max=dec_cut_max,
        z_cut_min=z_cut_min,
        z_cut_max=z_cut_max,
        center_ra=center_ra,
    )
    self.save_deltas(deltas, name_out, number_cut)

DeltaConverter

DeltaConverter(pwd, Omega_m, delta_path, coordinate_transform, plot_pixel_properties, software, return_qso_catalog=None, return_dla_catalog=None, dla_catalog=None, return_sky_catalogs=False, repeat=False, center_ra=True)

Convert picca delta files into a tomographic solver input.

Applies the footprint / redshift / sigma cuts, transforms sky coordinates to cartesian (Mpc.h^-1), writes the pixel binary (serial or tiled parallel) and the map property file, and emits the QSO/DLA sky and cartesian catalogs.

Store the conversion configuration.

Parameters:

Name Type Description Default
pwd str

Output directory.

required
Omega_m float

Fiducial matter density for the comoving transform.

required
delta_path str

Input delta directory.

required
coordinate_transform str

Sky<->cartesian transform mode.

required
plot_pixel_properties bool

Produce LOS density/separation plots.

required
software str

Solver backend (e.g. "dachshund").

required
return_qso_catalog str

Output QSO catalog file name.

None
return_dla_catalog str

Output DLA catalog file name.

None
dla_catalog str

Input DLA catalog file.

None
return_sky_catalogs bool

Also write sky-coordinate catalogs.

False
repeat bool

Merge multiple exposures of each LOS.

False
center_ra bool

Recenter RA around 0.

True
Source code in lelantos/cosmology.py
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
def __init__(
    self,
    pwd,
    Omega_m,
    delta_path,
    coordinate_transform,
    plot_pixel_properties,
    software,
    return_qso_catalog=None,
    return_dla_catalog=None,
    dla_catalog=None,
    return_sky_catalogs=False,
    repeat=False,
    center_ra=True,
):
    """Store the conversion configuration.

    Args:
        pwd (str): Output directory.
        Omega_m (float): Fiducial matter density for the comoving transform.
        delta_path (str): Input delta directory.
        coordinate_transform (str): Sky<->cartesian transform mode.
        plot_pixel_properties (bool): Produce LOS density/separation plots.
        software (str): Solver backend (e.g. ``"dachshund"``).
        return_qso_catalog (str, optional): Output QSO catalog file name.
        return_dla_catalog (str, optional): Output DLA catalog file name.
        dla_catalog (str, optional): Input DLA catalog file.
        return_sky_catalogs (bool, optional): Also write sky-coordinate
            catalogs.
        repeat (bool, optional): Merge multiple exposures of each LOS.
        center_ra (bool, optional): Recenter RA around 0.
    """
    self.pwd = pwd
    self.delta_path = delta_path
    self.Omega_m = Omega_m
    self.coordinate_transform = coordinate_transform
    self.plot_pixel_properties = plot_pixel_properties
    self.return_qso_catalog = return_qso_catalog
    self.return_dla_catalog = return_dla_catalog
    self.dla_catalog = dla_catalog
    self.return_sky_catalogs = return_sky_catalogs
    self.repeat = repeat
    self.software = software
    self.center_ra = center_ra

transform_delta_to_pixel_file

transform_delta_to_pixel_file(rebin=None, sigma_min=None, sigma_max=None, z_cut_min=None, z_cut_max=None, dec_cut_min=None, dec_cut_max=None, ra_cut_min=None, ra_cut_max=None)

Read the deltas and produce cartesian/sky pixel and catalog arrays.

Reads (optionally exposure-merged, rebinned) deltas, applies the sky / redshift cuts, converts to cartesian coordinates shifted to the box origin, clips sigma, and builds the matching QSO and DLA arrays.

Parameters:

Name Type Description Default
rebin int

Rebin factor along each LOS.

None
sigma_min, sigma_max float

Clip the pixel noise.

required
z_cut_min, z_cut_max float

Redshift window.

required
dec_cut_min, dec_cut_max, ra_cut_min, ra_cut_max float

Sky window.

required

Returns:

Name Type Description
tuple

``(cartesian_deltas, cartesian_qso_catalog,

cartesian_dla_catalog, sky_deltas, sky_qso_catalog,

sky_dla_catalog, properties_map_pixels)``.

Source code in lelantos/cosmology.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
def transform_delta_to_pixel_file(
    self,
    rebin=None,
    sigma_min=None,
    sigma_max=None,
    z_cut_min=None,
    z_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    ra_cut_min=None,
    ra_cut_max=None,
):
    """Read the deltas and produce cartesian/sky pixel and catalog arrays.

    Reads (optionally exposure-merged, rebinned) deltas, applies the sky /
    redshift cuts, converts to cartesian coordinates shifted to the box
    origin, clips sigma, and builds the matching QSO and DLA arrays.

    Args:
        rebin (int, optional): Rebin factor along each LOS.
        sigma_min, sigma_max (float, optional): Clip the pixel noise.
        z_cut_min, z_cut_max (float, optional): Redshift window.
        dec_cut_min, dec_cut_max, ra_cut_min, ra_cut_max (float, optional):
            Sky window.

    Returns:
        tuple: ``(cartesian_deltas, cartesian_qso_catalog,
        cartesian_dla_catalog, sky_deltas, sky_qso_catalog,
        sky_dla_catalog, properties_map_pixels)``.
    """
    namefile = get_delta_list(self.delta_path)
    # namefile = preselect_deltas(namefile,
    #                             ramin=ra_cut_min,
    #                             ramax=ra_cut_max,
    #                             decmin=dec_cut_min,
    #                             decmax=dec_cut_max)
    properties_map_pixels = {}
    (rcomov, distang, inv_rcomov, inv_distang) = utils.get_cosmo_function(
        self.Omega_m
    )
    if self.repeat:
        (
            ra,
            dec,
            z,
            zqso,
            ids,
            sigmas,
            deltas,
        ) = get_merged_multiple_exposure_deltas(namefile)
    else:
        (ra, dec, z, zqso, ids, sigmas, deltas) = get_deltas(
            namefile, center_ra=self.center_ra
        )

    if rebin is not None:
        (z, deltas, sigmas) = self.rebin_data(z, deltas, sigmas, rebin)

    if self.return_dla_catalog is not None:
        zdlas, z_qso_dlas = [], []
        if self.dla_catalog is None:
            raise KeyError(
                "Please give a DLA catalog name or turn off the return_dla_catalog option"
            )
        dla_catalog = tomographic_objects.DLACatalog.init_from_fits(
            self.dla_catalog
        )
        for i in range(len(ids)):
            mask = dla_catalog.primary_key == ids[i]
            if z_cut_min is not None:
                mask &= dla_catalog.coord_z > z_cut_min
            if z_cut_max is not None:
                mask &= dla_catalog.coord_z < z_cut_max
            zdlas.append(dla_catalog.coord_z[mask])
            z_qso_dlas.append(dla_catalog.z_qso[mask])

    sky_deltas = np.array(
        [
            [ra[i], dec[i], z[i][j], sigmas[i][j], deltas[i][j]]
            for i in range(len(ra))
            for j in range(len(z[i]))
        ]
    )
    sky_deltas = sky_deltas[
        utils.cut_sky_catalog(
            sky_deltas[:, 0],
            sky_deltas[:, 1],
            sky_deltas[:, 2],
            ramin=ra_cut_min,
            ramax=ra_cut_max,
            decmin=dec_cut_min,
            decmax=dec_cut_max,
            zmin=z_cut_min,
            zmax=z_cut_max,
        )
    ]
    suplementary_parameters = utils.return_suplementary_parameters(
        self.coordinate_transform,
        zmin=np.min(sky_deltas[:, 2]),
        zmax=np.max(sky_deltas[:, 2]),
    )
    cartesian_deltas = np.zeros(sky_deltas.shape)
    (
        cartesian_deltas[:, 0],
        cartesian_deltas[:, 1],
        cartesian_deltas[:, 2],
    ) = utils.convert_sky_to_cartesian(
        sky_deltas[:, 0],
        sky_deltas[:, 1],
        sky_deltas[:, 2],
        self.coordinate_transform,
        rcomov=rcomov,
        distang=distang,
        suplementary_parameters=suplementary_parameters,
    )
    cartesian_deltas[:, 3], cartesian_deltas[:, 4] = (
        sky_deltas[:, 3],
        sky_deltas[:, 4],
    )
    (
        properties_map_pixels["minx"],
        properties_map_pixels["miny"],
        properties_map_pixels["minz"],
    ) = (
        np.min(cartesian_deltas[:, 0]),
        np.min(cartesian_deltas[:, 1]),
        np.min(cartesian_deltas[:, 2]),
    )
    (
        properties_map_pixels["maxx"],
        properties_map_pixels["maxy"],
        properties_map_pixels["maxz"],
    ) = (
        np.max(cartesian_deltas[:, 0]),
        np.max(cartesian_deltas[:, 1]),
        np.max(cartesian_deltas[:, 2]),
    )
    (
        properties_map_pixels["minra"],
        properties_map_pixels["mindec"],
        properties_map_pixels["minredshift"],
    ) = (
        np.min(sky_deltas[:, 0]),
        np.min(sky_deltas[:, 1]),
        np.min(sky_deltas[:, 2]),
    )
    (
        properties_map_pixels["maxra"],
        properties_map_pixels["maxdec"],
        properties_map_pixels["maxredshift"],
    ) = (
        np.max(sky_deltas[:, 0]),
        np.max(sky_deltas[:, 1]),
        np.max(sky_deltas[:, 2]),
    )
    cartesian_deltas = cartesian_deltas - np.array(
        [
            properties_map_pixels["minx"],
            properties_map_pixels["miny"],
            properties_map_pixels["minz"],
            0,
            0,
        ]
    )

    if sigma_min is not None:
        cartesian_deltas[:, 3][cartesian_deltas[:, 3] < sigma_min] = sigma_min
    if sigma_max is not None:
        cartesian_deltas[:, 3][cartesian_deltas[:, 3] > sigma_max] = sigma_max

    if self.return_qso_catalog is not None:
        sky_qso_catalog = np.array(
            [[ra[i], dec[i], zqso[i], ids[i]] for i in range(len(ra))]
        )
        sky_qso_catalog = sky_qso_catalog[
            utils.cut_sky_catalog(
                sky_qso_catalog[:, 0],
                sky_qso_catalog[:, 1],
                sky_qso_catalog[:, 2],
                ramin=ra_cut_min,
                ramax=ra_cut_max,
                decmin=dec_cut_min,
                decmax=dec_cut_max,
                zmin=z_cut_min,
                zmax=z_cut_max,
            ),
            :,
        ]
        cartesian_qso_catalog = np.zeros(sky_qso_catalog.shape)
        (
            cartesian_qso_catalog[:, 0],
            cartesian_qso_catalog[:, 1],
            cartesian_qso_catalog[:, 2],
        ) = utils.convert_sky_to_cartesian(
            sky_qso_catalog[:, 0],
            sky_qso_catalog[:, 1],
            sky_qso_catalog[:, 2],
            self.coordinate_transform,
            rcomov=rcomov,
            distang=distang,
            suplementary_parameters=suplementary_parameters,
        )
        cartesian_qso_catalog[:, 3] = sky_qso_catalog[:, 3]
        cartesian_qso_catalog = cartesian_qso_catalog - np.array(
            [
                properties_map_pixels["minx"],
                properties_map_pixels["miny"],
                properties_map_pixels["minz"],
                0,
            ]
        )

    else:
        sky_qso_catalog, cartesian_qso_catalog = None, None

    if self.return_dla_catalog is not None:
        sky_dla_catalog = np.array(
            [
                [ra[i], dec[i], zdlas[i][j], z_qso_dlas[i][j]]
                for i in range(len(ra))
                for j in range(len(zdlas[i]))
            ]
        )
        sky_dla_catalog = sky_dla_catalog[
            utils.cut_sky_catalog(
                sky_dla_catalog[:, 0],
                sky_dla_catalog[:, 1],
                sky_dla_catalog[:, 2],
                ramin=ra_cut_min,
                ramax=ra_cut_max,
                decmin=dec_cut_min,
                decmax=dec_cut_max,
                zmin=z_cut_min,
                zmax=z_cut_max,
            )
        ]
        cartesian_dla_catalog = np.zeros(sky_dla_catalog.shape)
        (
            cartesian_dla_catalog[:, 0],
            cartesian_dla_catalog[:, 1],
            cartesian_dla_catalog[:, 2],
        ) = utils.convert_sky_to_cartesian(
            sky_dla_catalog[:, 0],
            sky_dla_catalog[:, 1],
            sky_dla_catalog[:, 2],
            self.coordinate_transform,
            rcomov=rcomov,
            distang=distang,
            suplementary_parameters=suplementary_parameters,
        )
        cartesian_qso_catalog[:, 3] = sky_qso_catalog[:, 3]
        cartesian_dla_catalog = cartesian_dla_catalog - np.array(
            [
                properties_map_pixels["minx"],
                properties_map_pixels["miny"],
                properties_map_pixels["minz"],
                0,
            ]
        )
    else:
        sky_dla_catalog, cartesian_dla_catalog = None, None

    return (
        cartesian_deltas,
        cartesian_qso_catalog,
        cartesian_dla_catalog,
        sky_deltas,
        sky_qso_catalog,
        sky_dla_catalog,
        properties_map_pixels,
    )

rebin_data

rebin_data(z, deltas, sigmas, bin_pixel, method='gauss')

Rebin each line of sight by grouping bin_pixel pixels together.

Parameters:

Name Type Description Default
z list[array]

Per-LOS redshift arrays.

required
deltas list[array]

Per-LOS delta arrays.

required
sigmas list[array]

Per-LOS sigma arrays.

required
bin_pixel int

Number of pixels per output bin.

required
method str

Reduction ("gauss", "mean" ...).

'gauss'

Returns:

Name Type Description
tuple

(z, deltas, sigmas) rebinned in place.

Source code in lelantos/cosmology.py
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
def rebin_data(self, z, deltas, sigmas, bin_pixel, method="gauss"):
    """Rebin each line of sight by grouping ``bin_pixel`` pixels together.

    Args:
        z (list[array]): Per-LOS redshift arrays.
        deltas (list[array]): Per-LOS delta arrays.
        sigmas (list[array]): Per-LOS sigma arrays.
        bin_pixel (int): Number of pixels per output bin.
        method (str, optional): Reduction (``"gauss"``, ``"mean"`` ...).

    Returns:
        tuple: ``(z, deltas, sigmas)`` rebinned in place.
    """
    for i in range(len(z)):
        if len(z[i]) > 1:
            if len(z[i]) <= bin_pixel:
                z[i] = [np.mean(z[i])]
                deltas[i] = [np.mean(deltas[i])]
                sigmas[i] = [np.mean(sigmas[i])]
            else:
                new_shape = len(z[i]) // bin_pixel
                first_coord = len(z[i]) - (len(z[i]) // bin_pixel) * bin_pixel
                if first_coord == 0:
                    z[i] = utils.bin_ndarray(
                        np.array(z[i])[:], [new_shape], operation=method
                    )
                    deltas[i] = utils.bin_ndarray(
                        np.array(deltas[i])[:], [new_shape], operation=method
                    )
                    sigmas[i] = utils.bin_ndarray(
                        np.array(sigmas[i])[:], [new_shape], operation=method
                    )
                else:
                    z[i] = np.concatenate(
                        [
                            [np.mean(np.array(z[i])[:first_coord])],
                            utils.bin_ndarray(
                                np.array(z[i])[first_coord:],
                                [new_shape],
                                operation=method,
                            ),
                        ]
                    )
                    deltas[i] = np.concatenate(
                        [
                            [np.mean(np.array(deltas[i])[:first_coord])],
                            utils.bin_ndarray(
                                np.array(deltas[i])[first_coord:],
                                [new_shape],
                                operation=method,
                            ),
                        ]
                    )
                    sigmas[i] = np.concatenate(
                        [
                            [np.mean(np.array(sigmas[i])[:first_coord])],
                            utils.bin_ndarray(
                                np.array(sigmas[i])[first_coord:],
                                [new_shape],
                                operation=method,
                            ),
                        ]
                    )
    return (z, deltas, sigmas)

create_input_files

create_input_files(coordinates_to_write, properties, name_pixel, create_launcher=None)

Write the solver pixel input, dispatching on the solver backend.

Parameters:

Name Type Description Default
coordinates_to_write ndarray

Pixel coordinates + values.

required
properties dict

Solver/geometry parameters.

required
name_pixel str

Output pixel file name.

required
create_launcher str

If set, also write the launcher.

None
Source code in lelantos/cosmology.py
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
def create_input_files(
    self, coordinates_to_write, properties, name_pixel, create_launcher=None
):
    """Write the solver pixel input, dispatching on the solver backend.

    Args:
        coordinates_to_write (numpy.ndarray): Pixel coordinates + values.
        properties (dict): Solver/geometry parameters.
        name_pixel (str): Output pixel file name.
        create_launcher (str, optional): If set, also write the launcher.
    """
    if self.software.lower() == "dachshund":
        self.create_dachshund_input_files(
            coordinates_to_write,
            properties,
            name_pixel,
            create_launcher=create_launcher,
        )

create_dachshund_input_files

create_dachshund_input_files(coordinates_to_write, properties, name_pixel, create_launcher=None)

Write the Dachshund pixel binary and optionally its .cfg launcher.

Parameters:

Name Type Description Default
coordinates_to_write ndarray

Pixel coordinates + values.

required
properties dict

Solver/geometry parameters.

required
name_pixel str

Output pixel file name.

required
create_launcher str

If set, launcher base name to write.

None
Source code in lelantos/cosmology.py
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
def create_dachshund_input_files(
    self, coordinates_to_write, properties, name_pixel, create_launcher=None
):
    """Write the Dachshund pixel binary and optionally its ``.cfg`` launcher.

    Args:
        coordinates_to_write (numpy.ndarray): Pixel coordinates + values.
        properties (dict): Solver/geometry parameters.
        name_pixel (str): Output pixel file name.
        create_launcher (str, optional): If set, launcher base name to write.
    """
    pixel = tomographic_objects.Pixel(
        name=os.path.join(self.pwd, name_pixel), pixel_array=coordinates_to_write
    )
    pixel.write()
    if create_launcher is not None:
        self.create_dachshund_launcher(
            np.max(coordinates_to_write[:, 0]),
            np.max(coordinates_to_write[:, 1]),
            np.max(coordinates_to_write[:, 2]),
            len(coordinates_to_write),
            properties["shape"][0],
            properties["shape"][1],
            properties["shape"][2],
            properties["sigma_f"],
            properties["lperp"],
            properties["lpar"],
            properties["name_pixel"],
            properties["name_map"],
            create_launcher,
        )

create_dachshund_launcher

create_dachshund_launcher(lx, ly, lz, npix, nx, ny, nz, sigmaf, lperp, lpar, namepixel, namemap, nameinput)

Write a Dachshund .cfg launcher describing one (sub-)map.

Parameters:

Name Type Description Default
lx, ly, lz float

Domain size in each direction (Mpc.h^-1).

required
npix int

Total number of pixels.

required
nx, ny, nz int

Map grid sizes.

required
sigmaf float

Signal covariance amplitude sigma_f^2.

required
lperp float

Transverse correlation length.

required
lpar float

Radial correlation length.

required
namepixel str

Input pixel binary path.

required
namemap str

Output map binary path.

required
nameinput str

Launcher base name (.cfg appended).

required
Source code in lelantos/cosmology.py
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
def create_dachshund_launcher(
    self,
    lx,
    ly,
    lz,
    npix,
    nx,
    ny,
    nz,
    sigmaf,
    lperp,
    lpar,
    namepixel,
    namemap,
    nameinput,
):
    """Write a Dachshund ``.cfg`` launcher describing one (sub-)map.

    Args:
        lx, ly, lz (float): Domain size in each direction (Mpc.h^-1).
        npix (int): Total number of pixels.
        nx, ny, nz (int): Map grid sizes.
        sigmaf (float): Signal covariance amplitude sigma_f^2.
        lperp (float): Transverse correlation length.
        lpar (float): Radial correlation length.
        namepixel (str): Input pixel binary path.
        namemap (str): Output map binary path.
        nameinput (str): Launcher base name (``.cfg`` appended).
    """
    f = open(os.path.join(self.pwd, f"{nameinput}.cfg"), "w")
    f.write("#lx, ly, lz: the domain size in each direction.\n")
    f.write("#num_pixels: the *total* number of pixels.\n")
    f.write(
        "#map_nx, map_ny, map_nz: the number of map points. The map points are arbitrary but for now these n's are used to setup a uniform grid across the domain given above.\n"
    )
    f.write("#corr_var_s: the signal cov prefactor sigma_f^2\n")
    f.write("#corr_l_perp: the signal cov perp scale.\n")
    f.write("#corr_l_para: the signal cov para scale.\n")
    f.write(
        "#pcg_max_iter: the PCG max number of iterations. 100 should be good.\n"
    )
    f.write(
        "#pcg_tol: the PCG stopping tolerance. I found 1.0e-3 is good enough. Set it very small if you want the most accurate map.\n"
    )
    f.write("lx = {}\n".format(lx))
    f.write("ly = {}\n".format(ly))
    f.write("lz = {}\n".format(lz))
    f.write("\n")
    f.write("# From output of GEN_DACH_INPUT.PRO\n")
    f.write("num_pixels = {}\n".format(npix))
    f.write("\n")
    f.write("map_nx = {}\n".format(nx))
    f.write("map_ny = {}\n".format(ny))
    f.write("map_nz = {}\n".format(nz))
    f.write("\n")
    f.write("corr_var_s = {}\n".format(sigmaf))
    f.write("corr_l_perp = {}\n".format(lperp))
    f.write("corr_l_para = {}\n".format(lpar))
    f.write("\n")
    f.write("pcg_max_iter = 500\n")
    f.write("pcg_tol = 1.0e-3\n")
    f.write("#pcg_step_r = 1\n")
    f.write("\n")
    f.write("option_map_covar = 0\n")
    f.write("option_noise_covar = 0\n")
    f.write("pixel_data_path = {}\n".format(namepixel))
    f.write("map_path = {}\n".format(namemap))
    f.close()

create_dachshund_map_pixel_property_file

create_dachshund_map_pixel_property_file(name_out, cartesian_coordinates, sky_coordinates, shape, properties_map_pixels)

Build the map pixel-property object from the conversion metadata.

Parameters:

Name Type Description Default
name_out str

Output property file name.

required
cartesian_coordinates ndarray

Cartesian pixel coordinates.

required
sky_coordinates ndarray

Sky pixel coordinates.

required
shape tuple[int]

Map pixel shape.

required
properties_map_pixels dict

Cartesian/sky bounds of the box.

required

Returns:

Type Description

tomographic_objects.MapPixelProperty: The property object (unwritten).

Source code in lelantos/cosmology.py
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
def create_dachshund_map_pixel_property_file(
    self,
    name_out,
    cartesian_coordinates,
    sky_coordinates,
    shape,
    properties_map_pixels,
):
    """Build the map pixel-property object from the conversion metadata.

    Args:
        name_out (str): Output property file name.
        cartesian_coordinates (numpy.ndarray): Cartesian pixel coordinates.
        sky_coordinates (numpy.ndarray): Sky pixel coordinates.
        shape (tuple[int]): Map pixel shape.
        properties_map_pixels (dict): Cartesian/sky bounds of the box.

    Returns:
        tomographic_objects.MapPixelProperty: The property object (unwritten).
    """
    size = (
        np.max(cartesian_coordinates[:, 0]),
        np.max(cartesian_coordinates[:, 1]),
        np.max(cartesian_coordinates[:, 2]),
    )
    coordinate_transform = self.coordinate_transform
    boundary_cartesian_coord = (
        (
            properties_map_pixels["minx"],
            properties_map_pixels["miny"],
            properties_map_pixels["minz"],
        ),
        (
            properties_map_pixels["maxx"],
            properties_map_pixels["maxy"],
            properties_map_pixels["maxz"],
        ),
    )
    boundary_sky_coord = (
        (
            properties_map_pixels["minra"],
            properties_map_pixels["mindec"],
            properties_map_pixels["minredshift"],
        ),
        (
            properties_map_pixels["maxra"],
            properties_map_pixels["maxdec"],
            properties_map_pixels["maxredshift"],
        ),
    )
    property_file = tomographic_objects.MapPixelProperty(
        name=os.path.join(self.pwd, name_out),
        size=size,
        shape=shape,
        boundary_cartesian_coord=boundary_cartesian_coord,
        boundary_sky_coord=boundary_sky_coord,
        coordinate_transform=coordinate_transform,
        Omega_m=self.Omega_m,
    )
    return property_file

create_serial_input

create_serial_input(nameout, properties, cartesian_deltas, sky_deltas)

Write the single-box (serial) solver input and optional sky pixels.

Parameters:

Name Type Description Default
nameout str

Launcher base name.

required
properties dict

Solver/geometry parameters.

required
cartesian_deltas ndarray

Cartesian pixels.

required
sky_deltas ndarray

Sky pixels (written if configured).

required

Returns:

Type Description

tuple[int]: The map pixel shape.

Source code in lelantos/cosmology.py
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
def create_serial_input(self, nameout, properties, cartesian_deltas, sky_deltas):
    """Write the single-box (serial) solver input and optional sky pixels.

    Args:
        nameout (str): Launcher base name.
        properties (dict): Solver/geometry parameters.
        cartesian_deltas (numpy.ndarray): Cartesian pixels.
        sky_deltas (numpy.ndarray): Sky pixels (written if configured).

    Returns:
        tuple[int]: The map pixel shape.
    """
    self.create_input_files(
        cartesian_deltas,
        properties,
        properties["name_pixel"],
        create_launcher=nameout,
    )
    if self.return_sky_catalogs:
        self.create_input_files(
            sky_deltas,
            properties,
            "{}_sky_coordinates".format(properties["name_pixel"]),
            create_launcher=None,
        )
    return properties["shape"]

cut_in_chunks

cut_in_chunks(cartesian_deltas, number_chunks, overlaping, shape_sub_map)

Split the cartesian pixels into overlapping transverse chunks.

Parameters:

Name Type Description Default
cartesian_deltas ndarray

Cartesian pixels + values.

required
number_chunks tuple[int]

Chunk grid (nx, ny).

required
overlaping float

Chunk overlap (Mpc.h^-1).

required
shape_sub_map tuple[int]

Pixel shape of one sub-map.

required

Returns:

Name Type Description
tuple

(Chunks, (shape_x, shape_y)) — per-chunk pixel arrays and

limits, and the merged transverse pixel shape.

Source code in lelantos/cosmology.py
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
def cut_in_chunks(self, cartesian_deltas, number_chunks, overlaping, shape_sub_map):
    """Split the cartesian pixels into overlapping transverse chunks.

    Args:
        cartesian_deltas (numpy.ndarray): Cartesian pixels + values.
        number_chunks (tuple[int]): Chunk grid ``(nx, ny)``.
        overlaping (float): Chunk overlap (Mpc.h^-1).
        shape_sub_map (tuple[int]): Pixel shape of one sub-map.

    Returns:
        tuple: ``(Chunks, (shape_x, shape_y))`` — per-chunk pixel arrays and
        limits, and the merged transverse pixel shape.
    """
    if overlaping is None:
        overlaping = 0.0
    minx, maxx = np.min(cartesian_deltas[:, 0]), np.max(cartesian_deltas[:, 0])
    miny, maxy = np.min(cartesian_deltas[:, 1]), np.max(cartesian_deltas[:, 1])
    minz, maxz = np.min(cartesian_deltas[:, 2]), np.max(cartesian_deltas[:, 2])
    intervalx = maxx - minx
    intervaly = maxy - miny
    intervalz = maxz - minz
    subIntervalx = intervalx / number_chunks[0]
    subIntervaly = intervaly / number_chunks[1]
    Chunks = {}
    shape_x = number_chunks[0] * shape_sub_map[0]
    shape_y = number_chunks[1] * shape_sub_map[1]
    remove_shape_x, remove_shape_y = 0, 0
    for i in range(number_chunks[0]):
        for j in range(number_chunks[1]):
            filename = f"{i:03d}" + f"{j:03d}"
            Chunks[filename] = {}
            if (i == number_chunks[0] - 1) & (i == 0):
                intervalxChunk = [i * subIntervalx, (i + 1) * subIntervalx]
            elif i == 0:
                intervalxChunk = [
                    i * subIntervalx,
                    (i + 1) * subIntervalx + overlaping,
                ]
            elif i == number_chunks[0] - 1:
                intervalxChunk = [i * subIntervalx - overlaping, intervalx]
            else:
                intervalxChunk = [
                    i * subIntervalx - overlaping,
                    (i + 1) * subIntervalx + overlaping,
                ]
            if (j == number_chunks[1] - 1) & (j == 0):
                intervalyChunk = [j * subIntervaly, (j + 1) * subIntervaly]
            elif j == 0:
                intervalyChunk = [
                    j * subIntervaly,
                    (j + 1) * subIntervaly + overlaping,
                ]
            elif j == number_chunks[1] - 1:
                intervalyChunk = [j * subIntervaly - overlaping, intervaly]
            else:
                intervalyChunk = [
                    j * subIntervaly - overlaping,
                    (j + 1) * subIntervaly + overlaping,
                ]
            mask = (cartesian_deltas[:, 0] < intervalxChunk[1]) & (
                cartesian_deltas[:, 0] >= intervalxChunk[0]
            )
            mask &= (cartesian_deltas[:, 1] < intervalyChunk[1]) & (
                cartesian_deltas[:, 1] >= intervalyChunk[0]
            )
            chunks_deltas = []
            chunks_deltas.append(cartesian_deltas[:, 0][mask] - intervalxChunk[0])
            chunks_deltas.append(cartesian_deltas[:, 1][mask] - intervalyChunk[0])
            chunks_deltas.append(cartesian_deltas[:, 2][mask])
            chunks_deltas.append(cartesian_deltas[:, 3][mask])
            chunks_deltas.append(cartesian_deltas[:, 4][mask])
            chunks_deltas = np.transpose(np.stack(chunks_deltas))
            Chunks[filename]["coord"] = chunks_deltas
            Chunks[filename]["limits"] = [
                intervalxChunk[0],
                intervalxChunk[1],
                intervalyChunk[0],
                intervalyChunk[1],
                np.min(cartesian_deltas[:, 2]),
                np.max(cartesian_deltas[:, 2]),
            ]
            size = (
                intervalxChunk[1] - intervalxChunk[0],
                intervalyChunk[1] - intervalyChunk[0],
                intervalz,
            )
            pixel_to_remove = np.around(
                utils.pixel_per_mpc(size, shape_sub_map) * overlaping, 0
            ).astype(int)
            if number_chunks[0] != 1:
                if (i == 0) | (i == number_chunks[0] - 1):
                    remove_shape_x = remove_shape_x + pixel_to_remove[0]
                else:
                    remove_shape_x = remove_shape_x + 2 * pixel_to_remove[0]
            if number_chunks[1] != 1:
                if (j == 0) | (j == number_chunks[1] - 1):
                    remove_shape_y = remove_shape_y + pixel_to_remove[1]
                else:
                    remove_shape_y = remove_shape_y + 2 * pixel_to_remove[1]
    shape_x = shape_x - remove_shape_x // number_chunks[1]
    shape_y = shape_y - remove_shape_y // number_chunks[0]
    Chunks["overlaping"] = overlaping
    return (Chunks, (shape_x, shape_y))

create_parallel_input

create_parallel_input(properties, cartesian_deltas, number_chunks, overlaping, shape_sub_map)

Build the per-chunk launcher parameters for a tiled solver run.

Parameters:

Name Type Description Default
properties dict

Solver parameters (sigma_f, l_perp, l_par ...).

required
cartesian_deltas ndarray

Cartesian pixels + values.

required
number_chunks tuple[int]

Chunk grid.

required
overlaping float

Chunk overlap (Mpc.h^-1).

required
shape_sub_map tuple[int]

Pixel shape of one sub-map.

required

Returns:

Name Type Description
tuple

(parallel_launcher_params, filename, chunks, shape).

Source code in lelantos/cosmology.py
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
def create_parallel_input(
    self, properties, cartesian_deltas, number_chunks, overlaping, shape_sub_map
):
    """Build the per-chunk launcher parameters for a tiled solver run.

    Args:
        properties (dict): Solver parameters (sigma_f, l_perp, l_par ...).
        cartesian_deltas (numpy.ndarray): Cartesian pixels + values.
        number_chunks (tuple[int]): Chunk grid.
        overlaping (float): Chunk overlap (Mpc.h^-1).
        shape_sub_map (tuple[int]): Pixel shape of one sub-map.

    Returns:
        tuple: ``(parallel_launcher_params, filename, chunks, shape)``.
    """
    chunks, shape = self.cut_in_chunks(
        cartesian_deltas, number_chunks, overlaping, shape_sub_map
    )
    shape = (shape[0], shape[1], shape_sub_map[2])
    filename = []
    parallel_launcher_params = []
    for i in range(len(list(chunks.keys()))):
        key = list(chunks.keys())[i]
        if key != "overlaping":
            filename.append(key)
            parallel_launcher_params.append({})
            parallel_launcher_params[i]["maxx"] = chunks[key]["limits"][1]
            parallel_launcher_params[i]["minx"] = chunks[key]["limits"][0]
            parallel_launcher_params[i]["maxy"] = chunks[key]["limits"][3]
            parallel_launcher_params[i]["miny"] = chunks[key]["limits"][2]
            parallel_launcher_params[i]["maxz"] = chunks[key]["limits"][5]
            parallel_launcher_params[i]["minz"] = chunks[key]["limits"][4]
            parallel_launcher_params[i]["lx"] = (
                chunks[key]["limits"][1] - chunks[key]["limits"][0]
            )
            parallel_launcher_params[i]["ly"] = (
                chunks[key]["limits"][3] - chunks[key]["limits"][2]
            )
            parallel_launcher_params[i]["lz"] = (
                chunks[key]["limits"][5] - chunks[key]["limits"][4]
            )
            parallel_launcher_params[i]["npix"] = len(chunks[key]["coord"])
            parallel_launcher_params[i]["nx"] = shape_sub_map[0]
            parallel_launcher_params[i]["ny"] = shape_sub_map[1]
            parallel_launcher_params[i]["nz"] = shape_sub_map[2]
            parallel_launcher_params[i]["sigmaf"] = properties["sigma_f"]
            parallel_launcher_params[i]["lperp"] = properties["lperp"]
            parallel_launcher_params[i]["lpar"] = properties["lpar"]
            parallel_launcher_params[i]["namepixel"] = "{}_{}".format(
                properties["name_pixel"], key
            )
            parallel_launcher_params[i]["namemap"] = "map_{}_{}".format(
                properties["name_pixel"], key
            )
            parallel_launcher_params[i]["nameinput"] = "input_{}.cfg".format(key)
    return (parallel_launcher_params, filename, chunks, shape)

write_parallel_input

write_parallel_input(cartesian_deltas, parallel_launcher_params, filename, chunks, properties, nameout, number_chunks, overlaping)

Write the full and per-chunk pixel files and the launch pickle.

Parameters:

Name Type Description Default
cartesian_deltas ndarray

Full cartesian pixel set.

required
parallel_launcher_params list[dict]

Per-chunk solver params.

required
filename list[str]

Per-chunk keys.

required
chunks dict

Per-chunk pixel arrays.

required
properties dict

Solver parameters.

required
nameout str

Base name for the launch pickle.

required
number_chunks tuple[int]

Chunk grid.

required
overlaping float

Chunk overlap (Mpc.h^-1).

required
Source code in lelantos/cosmology.py
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
def write_parallel_input(
    self,
    cartesian_deltas,
    parallel_launcher_params,
    filename,
    chunks,
    properties,
    nameout,
    number_chunks,
    overlaping,
):
    """Write the full and per-chunk pixel files and the launch pickle.

    Args:
        cartesian_deltas (numpy.ndarray): Full cartesian pixel set.
        parallel_launcher_params (list[dict]): Per-chunk solver params.
        filename (list[str]): Per-chunk keys.
        chunks (dict): Per-chunk pixel arrays.
        properties (dict): Solver parameters.
        nameout (str): Base name for the launch pickle.
        number_chunks (tuple[int]): Chunk grid.
        overlaping (float): Chunk overlap (Mpc.h^-1).
    """
    self.create_input_files(
        cartesian_deltas, properties, properties["name_pixel"], create_launcher=None
    )
    for i in range(len(list(chunks.keys()))):
        key = list(chunks.keys())[i]
        if key != "overlaping":
            self.create_input_files(
                chunks[key]["coord"],
                properties,
                f"{properties['name_pixel']}_{key}",
                create_launcher=None,
            )
    pickle.dump(
        [filename, parallel_launcher_params, number_chunks, overlaping],
        open(os.path.join(self.pwd, f"{nameout}_launch_data.pickle"), "wb"),
    )

create_additional_catalogs

create_additional_catalogs(cartesian_qso_catalog, cartesian_dla_catalog, sky_qso_catalog, sky_dla_catalog, properties_map_pixels)

Build and write the QSO and DLA catalogs (cartesian and sky).

Parameters:

Name Type Description Default
cartesian_qso_catalog ndarray | None

Cartesian QSO array.

required
cartesian_dla_catalog ndarray | None

Cartesian DLA array.

required
sky_qso_catalog ndarray | None

Sky QSO array.

required
sky_dla_catalog ndarray | None

Sky DLA array.

required
properties_map_pixels dict

Cartesian/sky bounds of the box.

required
Source code in lelantos/cosmology.py
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
def create_additional_catalogs(
    self,
    cartesian_qso_catalog,
    cartesian_dla_catalog,
    sky_qso_catalog,
    sky_dla_catalog,
    properties_map_pixels,
):
    """Build and write the QSO and DLA catalogs (cartesian and sky).

    Args:
        cartesian_qso_catalog (numpy.ndarray | None): Cartesian QSO array.
        cartesian_dla_catalog (numpy.ndarray | None): Cartesian DLA array.
        sky_qso_catalog (numpy.ndarray | None): Sky QSO array.
        sky_dla_catalog (numpy.ndarray | None): Sky DLA array.
        properties_map_pixels (dict): Cartesian/sky bounds of the box.
    """
    boundary_cartesian_coord = (
        (
            properties_map_pixels["minx"],
            properties_map_pixels["miny"],
            properties_map_pixels["minz"],
        ),
        (
            properties_map_pixels["maxx"],
            properties_map_pixels["maxy"],
            properties_map_pixels["maxz"],
        ),
    )
    boundary_sky_coord = (
        (
            properties_map_pixels["minra"],
            properties_map_pixels["mindec"],
            properties_map_pixels["minredshift"],
        ),
        (
            properties_map_pixels["maxra"],
            properties_map_pixels["maxdec"],
            properties_map_pixels["maxredshift"],
        ),
    )
    if self.return_dla_catalog is not None:
        dla_catalog_cartesian = (
            tomographic_objects.DLACatalog.init_from_pixel_catalog(
                cartesian_dla_catalog,
                name=os.path.join(self.pwd, self.return_dla_catalog),
                coordinate_transform=self.coordinate_transform,
                Omega_m=self.Omega_m,
                boundary_cartesian_coord=boundary_cartesian_coord,
                boundary_sky_coord=boundary_sky_coord,
            )
        )
        dla_catalog_cartesian.write()
        if self.return_sky_catalogs:
            dla_catalog_sky = (
                tomographic_objects.DLACatalog.init_from_pixel_catalog(
                    sky_dla_catalog,
                    name=os.path.join(
                        self.pwd, f"{self.return_dla_catalog}_sky_coordinates"
                    ),
                    coordinate_transform=self.coordinate_transform,
                    Omega_m=self.Omega_m,
                    boundary_cartesian_coord=boundary_cartesian_coord,
                    boundary_sky_coord=boundary_sky_coord,
                )
            )
            dla_catalog_sky.write()
    if self.return_qso_catalog is not None:
        quasar_catalog_cartesian = (
            tomographic_objects.QSOCatalog.init_from_pixel_catalog(
                cartesian_qso_catalog,
                name=os.path.join(self.pwd, self.return_qso_catalog),
                coordinate_transform=self.coordinate_transform,
                Omega_m=self.Omega_m,
                boundary_cartesian_coord=boundary_cartesian_coord,
                boundary_sky_coord=boundary_sky_coord,
            )
        )
        quasar_catalog_cartesian.write()
        if self.return_sky_catalogs:
            quasar_catalog_sky = (
                tomographic_objects.QSOCatalog.init_from_pixel_catalog(
                    sky_qso_catalog,
                    name=os.path.join(
                        self.pwd, f"{self.return_qso_catalog}_sky_coordinates"
                    ),
                    coordinate_transform=self.coordinate_transform,
                    Omega_m=self.Omega_m,
                    catalog_type="sky",
                    boundary_cartesian_coord=boundary_cartesian_coord,
                    boundary_sky_coord=boundary_sky_coord,
                )
            )
            quasar_catalog_sky.write()

write_additional_catalogs

write_additional_catalogs(dla_catalog_sky, dla_catalog_cartesian, quasar_catalog_sky, quasar_catalog_cartesian)

Write any provided QSO/DLA catalog objects to disk.

Parameters:

Name Type Description Default
dla_catalog_sky

Sky DLA catalog object or None.

required
dla_catalog_cartesian

Cartesian DLA catalog object or None.

required
quasar_catalog_sky

Sky QSO catalog object or None.

required
quasar_catalog_cartesian

Cartesian QSO catalog object or None.

required
Source code in lelantos/cosmology.py
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
def write_additional_catalogs(
    self,
    dla_catalog_sky,
    dla_catalog_cartesian,
    quasar_catalog_sky,
    quasar_catalog_cartesian,
):
    """Write any provided QSO/DLA catalog objects to disk.

    Args:
        dla_catalog_sky: Sky DLA catalog object or None.
        dla_catalog_cartesian: Cartesian DLA catalog object or None.
        quasar_catalog_sky: Sky QSO catalog object or None.
        quasar_catalog_cartesian: Cartesian QSO catalog object or None.
    """
    if dla_catalog_sky is not None:
        dla_catalog_sky.write()
    if dla_catalog_cartesian is not None:
        dla_catalog_cartesian.write()
    if quasar_catalog_sky is not None:
        quasar_catalog_sky.write()
    if quasar_catalog_cartesian is not None:
        quasar_catalog_cartesian.write()

transform_delta

transform_delta(mode, nameout, properties, property_file_name, rebin=False, sigma_min=None, sigma_max=None, z_cut_min=None, z_cut_max=None, dec_cut_min=None, dec_cut_max=None, ra_cut_min=None, ra_cut_max=None, number_chunks=None, overlaping=None, shape_sub_map=None)

Full delta->solver-input conversion (main entry point).

Reads and cuts the deltas, writes the serial or parallel solver input, writes the map property file and QSO/DLA catalogs, and optionally produces the LOS density/separation diagnostic plots.

Parameters:

Name Type Description Default
mode str

"serial" or "parallel".

required
nameout str

Run base name (launcher / launch pickle).

required
properties dict

Solver parameters.

required
property_file_name str

Output map property file name.

required
rebin int

Rebin factor along each LOS.

False
sigma_min, sigma_max float

Clip the pixel noise.

required
z_cut_min, z_cut_max float

Redshift window.

required
dec_cut_min, dec_cut_max, ra_cut_min, ra_cut_max float

Sky window.

required
number_chunks tuple[int]

Chunk grid (parallel mode).

None
overlaping float

Chunk overlap (parallel mode).

None
shape_sub_map tuple[int]

Sub-map shape (parallel mode).

None

Raises:

Type Description
KeyError

If mode is neither "serial" nor "parallel".

Source code in lelantos/cosmology.py
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
def transform_delta(
    self,
    mode,
    nameout,
    properties,
    property_file_name,
    rebin=False,
    sigma_min=None,
    sigma_max=None,
    z_cut_min=None,
    z_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    ra_cut_min=None,
    ra_cut_max=None,
    number_chunks=None,
    overlaping=None,
    shape_sub_map=None,
):
    """Full delta->solver-input conversion (main entry point).

    Reads and cuts the deltas, writes the serial or parallel solver input,
    writes the map property file and QSO/DLA catalogs, and optionally
    produces the LOS density/separation diagnostic plots.

    Args:
        mode (str): ``"serial"`` or ``"parallel"``.
        nameout (str): Run base name (launcher / launch pickle).
        properties (dict): Solver parameters.
        property_file_name (str): Output map property file name.
        rebin (int, optional): Rebin factor along each LOS.
        sigma_min, sigma_max (float, optional): Clip the pixel noise.
        z_cut_min, z_cut_max (float, optional): Redshift window.
        dec_cut_min, dec_cut_max, ra_cut_min, ra_cut_max (float, optional):
            Sky window.
        number_chunks (tuple[int], optional): Chunk grid (parallel mode).
        overlaping (float, optional): Chunk overlap (parallel mode).
        shape_sub_map (tuple[int], optional): Sub-map shape (parallel mode).

    Raises:
        KeyError: If ``mode`` is neither ``"serial"`` nor ``"parallel"``.
    """
    (
        cartesian_deltas,
        cartesian_qso_catalog,
        cartesian_dla_catalog,
        sky_deltas,
        sky_qso_catalog,
        sky_dla_catalog,
        properties_map_pixels,
    ) = self.transform_delta_to_pixel_file(
        rebin=rebin,
        sigma_min=sigma_min,
        sigma_max=sigma_max,
        z_cut_min=z_cut_min,
        z_cut_max=z_cut_max,
        dec_cut_min=dec_cut_min,
        dec_cut_max=dec_cut_max,
        ra_cut_min=ra_cut_min,
        ra_cut_max=ra_cut_max,
    )
    if mode.lower() == "serial":
        shape = self.create_serial_input(
            nameout, properties, cartesian_deltas, sky_deltas
        )
    elif mode.lower() == "parallel":
        (
            parallel_launcher_params,
            filename,
            chunks,
            shape,
        ) = self.create_parallel_input(
            properties, cartesian_deltas, number_chunks, overlaping, shape_sub_map
        )
        self.write_parallel_input(
            cartesian_deltas,
            parallel_launcher_params,
            filename,
            chunks,
            properties,
            nameout,
            number_chunks,
            overlaping,
        )
    else:
        raise KeyError("Please choose a mode between serial and parallel")
    property_file = self.create_dachshund_map_pixel_property_file(
        property_file_name,
        cartesian_deltas,
        sky_deltas,
        shape,
        properties_map_pixels,
    )
    property_file.write()
    self.create_additional_catalogs(
        cartesian_qso_catalog,
        cartesian_dla_catalog,
        sky_qso_catalog,
        sky_dla_catalog,
        properties_map_pixels,
    )
    if self.plot_pixel_properties:
        pixel_analyzer = PixelAnalizer(
            pixel=os.path.join(self.pwd, properties["name_pixel"]),
            property_file=os.path.join(self.pwd, property_file_name),
        )
        pixel_analyzer.analyze_pixels(
            False,
            True,
            name_dperp=os.path.join(self.pwd, nameout),
            coupled_plot=True,
        )

PixelAnalizer

PixelAnalizer(pixel=None, property_file=None)

Bases: object

Analyse a pixel file: line-of-sight density and mean separation.

Computes and plots the redshift dependence of the mean nearest-LOS separation and the LOS surface density, and can compare two datasets.

Load the pixel object to analyse.

Parameters:

Name Type Description Default
pixel str | Pixel

Pixel file path or a Pixel object.

None
property_file str

Property file (if pixel is a path).

None
Source code in lelantos/cosmology.py
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
def __init__(self, pixel=None, property_file=None):
    """Load the pixel object to analyse.

    Args:
        pixel (str | Pixel, optional): Pixel file path or a Pixel object.
        property_file (str, optional): Property file (if ``pixel`` is a path).
    """
    if type(pixel) == str:
        pixel_class = tomographic_objects.Pixel.init_from_property_files(
            property_file, name=pixel
        )
        pixel_class.read()
    else:
        pixel_class = pixel
    self.pixel = pixel_class

write_density_file staticmethod

write_density_file(z, dperp, name)

Pickle a (z, density) profile to disk.

Parameters:

Name Type Description Default
z array - like

Redshift bin centres.

required
dperp array - like

Profile values (density here).

required
name str

Output pickle file.

required
Source code in lelantos/cosmology.py
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
@staticmethod
def write_density_file(z, dperp, name):
    """Pickle a ``(z, density)`` profile to disk.

    Args:
        z (array-like): Redshift bin centres.
        dperp (array-like): Profile values (density here).
        name (str): Output pickle file.
    """
    pickle.dump([z, dperp], open(name, "wb"))

write_dperp_file staticmethod

write_dperp_file(z, dperp, name)

Pickle a (z, mean-separation) profile to disk.

Parameters:

Name Type Description Default
z array - like

Redshift bin centres.

required
dperp array - like

Mean nearest-LOS separation per bin.

required
name str

Output pickle file.

required
Source code in lelantos/cosmology.py
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
@staticmethod
def write_dperp_file(z, dperp, name):
    """Pickle a ``(z, mean-separation)`` profile to disk.

    Args:
        z (array-like): Redshift bin centres.
        dperp (array-like): Mean nearest-LOS separation per bin.
        name (str): Output pickle file.
    """
    pickle.dump([z, dperp], open(name, "wb"))

read_density_file staticmethod

read_density_file(name)

Read a pickled (z, density) profile.

Parameters:

Name Type Description Default
name str

Pickle file.

required

Returns:

Name Type Description
tuple

(z, density).

Source code in lelantos/cosmology.py
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
@staticmethod
def read_density_file(name):
    """Read a pickled ``(z, density)`` profile.

    Args:
        name (str): Pickle file.

    Returns:
        tuple: ``(z, density)``.
    """
    a = pickle.load(open(name, "rb"))
    return (a[0], a[1])

read_dperp_file staticmethod

read_dperp_file(name)

Read a pickled (z, mean-separation) profile.

Parameters:

Name Type Description Default
name str

Pickle file.

required

Returns:

Name Type Description
tuple

(z, dperp).

Source code in lelantos/cosmology.py
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
@staticmethod
def read_dperp_file(name):
    """Read a pickled ``(z, mean-separation)`` profile.

    Args:
        name (str): Pickle file.

    Returns:
        tuple: ``(z, dperp)``.
    """
    a = pickle.load(open(name, "rb"))
    return (a[0], a[1])

plot_histogram_mean_distance staticmethod

plot_histogram_mean_distance(zpar, dmin, name_histo, nb_bins=50)

Plot the histogram of nearest-LOS distances at a fixed redshift.

Parameters:

Name Type Description Default
zpar float

Redshift of the slab.

required
dmin array - like

Nearest-LOS distances.

required
name_histo str

Output figure base name.

required
nb_bins int

Number of histogram bins.

50
Source code in lelantos/cosmology.py
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
@staticmethod
def plot_histogram_mean_distance(zpar, dmin, name_histo, nb_bins=50):
    """Plot the histogram of nearest-LOS distances at a fixed redshift.

    Args:
        zpar (float): Redshift of the slab.
        dmin (array-like): Nearest-LOS distances.
        name_histo (str): Output figure base name.
        nb_bins (int, optional): Number of histogram bins.
    """
    plt.figure()
    plt.hist(dmin, nb_bins)
    plt.xlabel("minimal distance histogram at Z={}".format(zpar))
    plt.savefig(f"{name_histo}_at_Z{zpar}.pdf", format="pdf")

plot_mean_distance_density staticmethod

plot_mean_distance_density(zpar, dperpz, densityz, nameout, coupled_plot=False, comparison=False, dperp_comparison=None, density_comparison=None, zpar_comparison=None, legend=None, dperp_other=None, density_other=None, **kwargs)

Plot mean LOS separation and density vs redshift (coupled or not).

Parameters:

Name Type Description Default
zpar array - like

Redshift bin centres.

required
dperpz array - like

Mean nearest-LOS separation per bin.

required
densityz array - like

LOS density per bin.

required
nameout str

Output figure base name.

required
coupled_plot bool

Draw both curves on twin axes.

False
comparison bool

Overlay a comparison dataset.

False
dperp_comparison, density_comparison, zpar_comparison optional

Comparison profiles.

required
legend list[str]

Legend labels.

None
dperp_other, density_other optional

Extra comparison profiles.

required
**kwargs

Styling options.

{}
Source code in lelantos/cosmology.py
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
@staticmethod
def plot_mean_distance_density(
    zpar,
    dperpz,
    densityz,
    nameout,
    coupled_plot=False,
    comparison=False,
    dperp_comparison=None,
    density_comparison=None,
    zpar_comparison=None,
    legend=None,
    dperp_other=None,
    density_other=None,
    **kwargs,
):
    """Plot mean LOS separation and density vs redshift (coupled or not).

    Args:
        zpar (array-like): Redshift bin centres.
        dperpz (array-like): Mean nearest-LOS separation per bin.
        densityz (array-like): LOS density per bin.
        nameout (str): Output figure base name.
        coupled_plot (bool, optional): Draw both curves on twin axes.
        comparison (bool, optional): Overlay a comparison dataset.
        dperp_comparison, density_comparison, zpar_comparison (optional):
            Comparison profiles.
        legend (list[str], optional): Legend labels.
        dperp_other, density_other (optional): Extra comparison profiles.
        **kwargs: Styling options.
    """
    if coupled_plot:
        PixelAnalizer.plot_mean_distance_density_coupled(
            zpar,
            dperpz,
            densityz,
            nameout,
            comparison=comparison,
            dperp_comparison=dperp_comparison,
            density_comparison=density_comparison,
            zpar_comparison=zpar_comparison,
            legend=legend,
            dperp_other=dperp_other,
            density_other=density_other,
            **kwargs,
        )
    else:
        PixelAnalizer.plot_mean_distance_density_not_coupled(
            zpar,
            dperpz,
            densityz,
            nameout,
            comparison=comparison,
            dperp_comparison=dperp_comparison,
            density_comparison=density_comparison,
            zpar_comparison=zpar_comparison,
            legend=legend,
            dperp_other=dperp_other,
            density_other=density_other,
            **kwargs,
        )

plot_mean_distance_density_not_coupled staticmethod

plot_mean_distance_density_not_coupled(zpar, dperpz, densityz, nameout, comparison=False, dperp_comparison=None, density_comparison=None, zpar_comparison=None, legend=None, dperp_other=None, density_other=None, **kwargs)

Plot LOS separation and density vs redshift on separate figures.

Parameters:

Name Type Description Default
zpar array - like

Redshift bin centres.

required
dperpz array - like

Mean nearest-LOS separation per bin.

required
densityz array - like

LOS density per bin.

required
nameout str

Output figure base name.

required
comparison bool

Overlay a comparison dataset.

False
dperp_comparison, density_comparison, zpar_comparison optional

Comparison profiles.

required
legend list[str]

Legend labels.

None
dperp_other, density_other optional

Extra comparison profiles.

required
**kwargs

Styling options.

{}
Source code in lelantos/cosmology.py
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
@staticmethod
def plot_mean_distance_density_not_coupled(
    zpar,
    dperpz,
    densityz,
    nameout,
    comparison=False,
    dperp_comparison=None,
    density_comparison=None,
    zpar_comparison=None,
    legend=None,
    dperp_other=None,
    density_other=None,
    **kwargs,
):
    """Plot LOS separation and density vs redshift on separate figures.

    Args:
        zpar (array-like): Redshift bin centres.
        dperpz (array-like): Mean nearest-LOS separation per bin.
        densityz (array-like): LOS density per bin.
        nameout (str): Output figure base name.
        comparison (bool, optional): Overlay a comparison dataset.
        dperp_comparison, density_comparison, zpar_comparison (optional):
            Comparison profiles.
        legend (list[str], optional): Legend labels.
        dperp_other, density_other (optional): Extra comparison profiles.
        **kwargs: Styling options.
    """
    plt.figure()
    plt.xlabel("Redshift")
    plt.ylabel("Mean los separation [" + r"$\mathrm{Mpc\cdot h^{-1}}$" + "]")
    plt.grid()
    plt.plot(zpar, dperpz)
    if comparison:
        plt.plot(zpar_comparison, dperp_comparison)
        plt.legend(legend)
        if dperp_other is not None:
            for i in range(len(dperp_other)):
                plt.plot(dperp_other[i][0], dperp_other[i][1])
    plt.savefig(f"{nameout}_separation.pdf", format="pdf")

    plt.figure()
    plt.xlabel("Redshift")
    plt.ylabel("Density [" + r"$\mathrm{deg^{-2}}$" + "]")
    plt.grid()
    plt.plot(zpar, densityz)
    if comparison:
        plt.plot(zpar_comparison, density_comparison)
        plt.legend(legend)
        if density_other is not None:
            for i in range(len(density_other)):
                plt.plot(density_other[i][0], density_other[i][1])
    plt.savefig(f"{nameout}_density.pdf", format="pdf")

plot_mean_distance_density_coupled staticmethod

plot_mean_distance_density_coupled(zpar, dperpz, densityz, nameout, comparison=False, dperp_comparison=None, density_comparison=None, zpar_comparison=None, legend=None, dperp_other=None, density_other=None, **kwargs)

Plot LOS separation and density vs redshift on shared twin axes.

Parameters:

Name Type Description Default
zpar array - like

Redshift bin centres.

required
dperpz array - like

Mean nearest-LOS separation per bin.

required
densityz array - like

LOS density per bin.

required
nameout str

Output figure base name.

required
comparison bool

Overlay a comparison dataset.

False
dperp_comparison, density_comparison, zpar_comparison optional

Comparison profiles.

required
legend list[str]

Legend labels.

None
dperp_other, density_other optional

Extra comparison profiles.

required
**kwargs

Styling options.

{}
Source code in lelantos/cosmology.py
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
@staticmethod
def plot_mean_distance_density_coupled(
    zpar,
    dperpz,
    densityz,
    nameout,
    comparison=False,
    dperp_comparison=None,
    density_comparison=None,
    zpar_comparison=None,
    legend=None,
    dperp_other=None,
    density_other=None,
    **kwargs,
):
    """Plot LOS separation and density vs redshift on shared twin axes.

    Args:
        zpar (array-like): Redshift bin centres.
        dperpz (array-like): Mean nearest-LOS separation per bin.
        densityz (array-like): LOS density per bin.
        nameout (str): Output figure base name.
        comparison (bool, optional): Overlay a comparison dataset.
        dperp_comparison, density_comparison, zpar_comparison (optional):
            Comparison profiles.
        legend (list[str], optional): Legend labels.
        dperp_other, density_other (optional): Extra comparison profiles.
        **kwargs: Styling options.
    """
    figsize = utils.return_key(kwargs, "figsize", (8, 6))
    grid = utils.return_key(kwargs, "grid", True)
    fontsize = utils.return_key(kwargs, "fontsize", 13)
    fontsize_scale = utils.return_key(kwargs, "fontscalesize", 13)
    ylabel1 = utils.return_key(
        kwargs,
        "ylabel1",
        "Mean separation between nearest los ["
        + r"$h^{-1}$"
        + r"$\cdot$"
        + "Mpc"
        + "]",
    )
    ylabel2 = utils.return_key(
        kwargs, "ylabel2", "Density [" + r"$\mathrm{deg}^{-2}$" + "]"
    )
    xlabel = utils.return_key(kwargs, "xlabel", r"Redshift $z$")

    fig, ax1 = plt.subplots(1, 1, figsize=figsize)
    if grid:
        ax1.grid()
    line = ["dotted", "dashdot", "densely dashdotdotted"]

    color = "C0"
    ax1.set_xlabel(xlabel, fontsize=fontsize)
    ax1.set_ylabel(ylabel1, color=color, fontsize=fontsize)
    ax1.tick_params(axis="x", labelsize=fontsize_scale)
    ax1.tick_params(axis="y", labelsize=fontsize_scale)
    ax1.plot(zpar, dperpz, color=color)
    if comparison:
        ax1.plot(zpar_comparison, dperp_comparison, color=color, linestyle="--")
        if dperp_other is not None:
            for i in range(len(dperp_other)):
                ax1.plot(
                    dperp_other[i][0],
                    dperp_other[i][1],
                    color=color,
                    linestyle=line[i],
                )
    ax1.tick_params(axis="y", labelcolor=color)

    ax2 = ax1.twinx()
    if grid:
        ax2.grid()
    color = "C1"
    ax2.set_ylabel(ylabel2, color=color, fontsize=fontsize)
    ax2.tick_params(axis="y", labelsize=fontsize_scale)
    ax2.plot(zpar, densityz, color=color)
    if comparison:
        ax2.plot(zpar_comparison, density_comparison, color=color, linestyle="--")
        if density_other is not None:
            for i in range(len(density_other)):
                ax2.plot(
                    density_other[i][0],
                    density_other[i][1],
                    color=color,
                    linestyle=line[i],
                )
    ax2.tick_params(axis="y", labelcolor=color)

    fig.tight_layout()
    if comparison:
        legend_elements = [
            Line2D([0], [0], color="k", lw=1, label=legend[0]),
            Line2D([0], [0], color="k", linestyle="--", lw=1, label=legend[1]),
        ]
        if dperp_other is not None:
            for i in range(len(dperp_other)):
                legend_elements.append(
                    Line2D(
                        [0],
                        [0],
                        color="k",
                        linestyle=line[i],
                        lw=1,
                        label=legend[i + 2],
                    )
                )

        ax1.legend(handles=legend_elements, loc="upper center")
    plt.savefig(f"{nameout}_separation_density.pdf", format="pdf")

plot_histo_mean_distance_comparison staticmethod

plot_histo_mean_distance_comparison(dpername1, dpername2, densityname1, densityname2, nameout, legend, coupled_plot=False, **kwargs)

Compare the separation/density profiles of two datasets from files.

Parameters:

Name Type Description Default
dpername1, dpername2 str | list[str]

Separation profile file(s) for datasets 1 and 2 (averaged if lists).

required
densityname1, densityname2 str | list[str]

Density profile file(s).

required
nameout str

Output figure base name.

required
legend list[str]

Legend labels.

required
coupled_plot bool

Draw both curves on twin axes.

False
**kwargs

Styling options.

{}
Source code in lelantos/cosmology.py
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
@staticmethod
def plot_histo_mean_distance_comparison(
    dpername1,
    dpername2,
    densityname1,
    densityname2,
    nameout,
    legend,
    coupled_plot=False,
    **kwargs,
):
    """Compare the separation/density profiles of two datasets from files.

    Args:
        dpername1, dpername2 (str | list[str]): Separation profile file(s)
            for datasets 1 and 2 (averaged if lists).
        densityname1, densityname2 (str | list[str]): Density profile file(s).
        nameout (str): Output figure base name.
        legend (list[str]): Legend labels.
        coupled_plot (bool, optional): Draw both curves on twin axes.
        **kwargs: Styling options.
    """
    if type(dpername1) is str:
        zpar, dperp = PixelAnalizer.read_dperp_file(dpername1)
        zpar_comparison, dperp_comparison = PixelAnalizer.read_dperp_file(dpername2)
        zpar, density = PixelAnalizer.read_density_file(densityname1)
        zpar_comparison, density_comparison = PixelAnalizer.read_density_file(
            densityname2
        )
    else:
        zpar, dperp = np.mean(
            [
                PixelAnalizer.read_dperp_file(dpername1[i])
                for i in range(len(dpername1))
            ],
            axis=0,
        )
        zpar_comparison, dperp_comparison = np.mean(
            [
                PixelAnalizer.read_dperp_file(dpername2[i])
                for i in range(len(dpername2))
            ],
            axis=0,
        )
        zpar, density = np.mean(
            [
                PixelAnalizer.read_density_file(densityname1[i])
                for i in range(len(densityname1))
            ],
            axis=0,
        )
        zpar_comparison, density_comparison = np.mean(
            [
                PixelAnalizer.read_density_file(densityname2[i])
                for i in range(len(densityname2))
            ],
            axis=0,
        )
    PixelAnalizer.plot_mean_distance_density(
        zpar,
        dperp,
        density,
        nameout,
        coupled_plot=coupled_plot,
        comparison=True,
        dperp_comparison=dperp_comparison,
        density_comparison=density_comparison,
        zpar_comparison=zpar_comparison,
        legend=legend,
        **kwargs,
    )

compute_plot_histo_mean_distance

compute_plot_histo_mean_distance(zpar, name_histo)

Compute and plot the nearest-LOS distance histogram at a redshift.

Parameters:

Name Type Description Default
zpar float

Redshift of the slab.

required
name_histo str

Output figure base name.

required
Source code in lelantos/cosmology.py
2715
2716
2717
2718
2719
2720
2721
2722
2723
def compute_plot_histo_mean_distance(self, zpar, name_histo):
    """Compute and plot the nearest-LOS distance histogram at a redshift.

    Args:
        zpar (float): Redshift of the slab.
        name_histo (str): Output figure base name.
    """
    dmin = self.pixel.compute_mean_distance_histogram(zpar)
    PixelAnalizer.plot_histogram_mean_distance(zpar, dmin, name_histo, nb_bins=50)

compute_plot_mean_distance_density

compute_plot_mean_distance_density(nameout, coupled=False, plot=True)

Compute (and optionally plot/save) the separation/density profiles.

Parameters:

Name Type Description Default
nameout str

Output base name for the figures/pickles.

required
coupled bool

Coupled twin-axes plot.

False
plot bool

Write the profiles and figures.

True

Returns:

Name Type Description
tuple

(zpar, dperpz, densityz).

Source code in lelantos/cosmology.py
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
def compute_plot_mean_distance_density(self, nameout, coupled=False, plot=True):
    """Compute (and optionally plot/save) the separation/density profiles.

    Args:
        nameout (str): Output base name for the figures/pickles.
        coupled (bool, optional): Coupled twin-axes plot.
        plot (bool, optional): Write the profiles and figures.

    Returns:
        tuple: ``(zpar, dperpz, densityz)``.
    """
    (zpar, dperpz, densityz) = self.pixel.compute_mean_distance_density()
    if plot:
        PixelAnalizer.write_dperp_file(zpar, dperpz, f"{nameout}_dperp_file.pickle")
        PixelAnalizer.write_density_file(
            zpar, densityz, f"{nameout}_density_file.pickle"
        )
        PixelAnalizer.plot_mean_distance_density(
            zpar, dperpz, densityz, nameout, coupled_plot=coupled
        )
    return (zpar, dperpz, densityz)

analyze_pixels

analyze_pixels(compute_histo, compute_mean_distance_density, histo_zpar=None, name_histo='histogram_dperp', name_dperp='density_mean_distance', coupled_plot=False)

Run the requested pixel analyses (histogram and/or profiles).

Parameters:

Name Type Description Default
compute_histo bool

Compute the nearest-LOS distance histogram.

required
compute_mean_distance_density bool

Compute the profiles.

required
histo_zpar float

Redshift for the histogram.

None
name_histo str

Histogram figure base name.

'histogram_dperp'
name_dperp str

Profile figure base name.

'density_mean_distance'
coupled_plot bool

Coupled twin-axes profile plot.

False
Source code in lelantos/cosmology.py
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
def analyze_pixels(
    self,
    compute_histo,
    compute_mean_distance_density,
    histo_zpar=None,
    name_histo="histogram_dperp",
    name_dperp="density_mean_distance",
    coupled_plot=False,
):
    """Run the requested pixel analyses (histogram and/or profiles).

    Args:
        compute_histo (bool): Compute the nearest-LOS distance histogram.
        compute_mean_distance_density (bool): Compute the profiles.
        histo_zpar (float, optional): Redshift for the histogram.
        name_histo (str, optional): Histogram figure base name.
        name_dperp (str, optional): Profile figure base name.
        coupled_plot (bool, optional): Coupled twin-axes profile plot.
    """
    if compute_histo:
        self.compute_plot_histo_mean_distance(histo_zpar, name_histo)
    if compute_mean_distance_density:
        self.compute_plot_mean_distance_density(name_dperp, coupled=coupled_plot)

DeltaAnalyzer

DeltaAnalyzer(pwd, delta_path, center_ra=True, z_cut_min=None, z_cut_max=None, dec_cut_min=None, dec_cut_max=None, ra_cut_min=None, ra_cut_max=None, degree=True, pk1d_type=True)

Bases: object

Diagnostic plots of picca delta files (histograms, sky maps, trends).

Reads the deltas within a sky/redshift window and plots the distribution and redshift dependence of the delta, sigma, SNR and redshift quantities, plus RA/Dec and LOS-density diagrams, with optional dataset comparisons.

Store the delta path, sky/redshift window and plotting options.

Parameters:

Name Type Description Default
pwd str

Output directory for the figures.

required
delta_path str

Input delta directory.

required
center_ra bool

Recenter RA around 0.

True
z_cut_min, z_cut_max float

Redshift window.

required
dec_cut_min, dec_cut_max, ra_cut_min, ra_cut_max float

Sky window.

required
degree bool

Report/plot angles in degrees.

True
pk1d_type bool

Whether the deltas are in pk1d format.

True
Source code in lelantos/cosmology.py
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
def __init__(
    self,
    pwd,
    delta_path,
    center_ra=True,
    z_cut_min=None,
    z_cut_max=None,
    dec_cut_min=None,
    dec_cut_max=None,
    ra_cut_min=None,
    ra_cut_max=None,
    degree=True,
    pk1d_type=True,
):
    """Store the delta path, sky/redshift window and plotting options.

    Args:
        pwd (str): Output directory for the figures.
        delta_path (str): Input delta directory.
        center_ra (bool, optional): Recenter RA around 0.
        z_cut_min, z_cut_max (float, optional): Redshift window.
        dec_cut_min, dec_cut_max, ra_cut_min, ra_cut_max (float, optional):
            Sky window.
        degree (bool, optional): Report/plot angles in degrees.
        pk1d_type (bool, optional): Whether the deltas are in pk1d format.
    """
    self.pwd = pwd
    self.delta_path = delta_path
    self.center_ra = center_ra
    self.z_cut_min = z_cut_min
    self.z_cut_max = z_cut_max
    self.dec_cut_min = dec_cut_min
    self.dec_cut_max = dec_cut_max
    self.ra_cut_min = ra_cut_min
    self.ra_cut_max = ra_cut_max
    self.degree = degree
    self.pk1d_type = pk1d_type

get_ra_dec

get_ra_dec(delta_path)

Obtain arrays of RA and DEC coordinates from a list or a name of a delta file in pickle, fits or ascii format

Source code in lelantos/cosmology.py
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
def get_ra_dec(self, delta_path):
    """Obtain arrays of RA and DEC coordinates from a list or a name of a delta file in pickle, fits or ascii format"""
    namefile = get_delta_list(delta_path)
    # namefile = preselect_deltas(namefile,
    #                             ramin=self.ra_cut_min,
    #                             ramax=self.ra_cut_max,
    #                             decmin=self.dec_cut_min,
    #                             decmax=self.dec_cut_max)
    (ra, dec, z, zqso, ids, sigmas, deltas) = get_deltas(
        namefile, center_ra=self.center_ra, pk1d_type=self.pk1d_type
    )
    pixel_coord = np.array(
        [
            [ra[i], dec[i], z[i][j], sigmas[i][j], deltas[i][j], zqso[i], ids[i]]
            for i in range(len(ra))
            for j in range(len(z[i]))
        ]
    )
    pixel_coord = pixel_coord[
        utils.cut_sky_catalog(
            pixel_coord[:, 0],
            pixel_coord[:, 1],
            pixel_coord[:, 2],
            ramin=self.ra_cut_min,
            ramax=self.ra_cut_max,
            decmin=self.dec_cut_min,
            decmax=self.dec_cut_max,
            zmin=self.z_cut_min,
            zmax=self.z_cut_max,
        )
    ]
    (redshift, redshift_qso, id, sigma, delta) = (
        pixel_coord[:, 2],
        pixel_coord[:, 5],
        pixel_coord[:, 6],
        pixel_coord[:, 3],
        pixel_coord[:, 4],
    )
    unique_coord = np.unique(pixel_coord[:, 0:2], axis=0)
    ra = unique_coord[:, 0]
    dec = unique_coord[:, 1]
    if self.degree:
        ra, dec = np.degrees(ra), np.degrees(dec)
    snr = np.abs((delta + 1) / sigma)
    return (ra, dec, redshift, redshift_qso, id, sigma, delta, snr)

get_ra_dec_comparison

get_ra_dec_comparison(comparison)

Read the plotting quantities for each comparison delta set.

Parameters:

Name Type Description Default
comparison list[str] | None

Comparison delta paths.

required

Returns:

Name Type Description
tuple

Per-comparison lists of ``(ra, dec, redshift, redshift_qso,

id, sigma, delta, snr)(all None ifcomparison`` is None).

Source code in lelantos/cosmology.py
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
def get_ra_dec_comparison(self, comparison):
    """Read the plotting quantities for each comparison delta set.

    Args:
        comparison (list[str] | None): Comparison delta paths.

    Returns:
        tuple: Per-comparison lists of ``(ra, dec, redshift, redshift_qso,
        id, sigma, delta, snr)`` (all None if ``comparison`` is None).
    """
    if comparison is None:
        return (None, None, None, None, None, None, None, None)
    (
        ra_comp,
        dec_comp,
        redshift_comp,
        redshift_qso_comp,
        id_comp,
        sigma_comp,
        delta_comp,
        snr_comp,
    ) = ([], [], [], [], [], [], [], [])
    for i in range(len(comparison)):
        (ra, dec, redshift, redshift_qso, id, sigma, delta, snr) = self.get_ra_dec(
            comparison[i]
        )
        ra_comp.append(ra)
        dec_comp.append(dec)
        redshift_comp.append(redshift)
        redshift_qso_comp.append(redshift_qso)
        id_comp.append(id)
        sigma_comp.append(sigma)
        delta_comp.append(delta)
        snr_comp.append(snr)
    return (
        ra_comp,
        dec_comp,
        redshift_comp,
        redshift_qso_comp,
        id_comp,
        sigma_comp,
        delta_comp,
        snr_comp,
    )

plot

plot(value_names, name, comparison=None, comparison_legend=None, histo=True, mean_z_dependence=True, z_dependence=True, ra_dec_plots=True, print_stats=False, **kwargs)

Produce the requested delta diagnostic plots for several quantities.

Parameters:

Name Type Description Default
value_names list[str]

Quantities to plot (delta, sigma, snr, redshift ...).

required
name str

Output figure base name.

required
comparison list[str]

Comparison delta paths.

None
comparison_legend list[str]

Legend labels.

None
histo bool

Draw histograms.

True
mean_z_dependence bool

Draw mean-vs-redshift plots.

True
z_dependence bool

Draw value-vs-redshift plots.

True
ra_dec_plots bool

Draw the RA/Dec and LOS-density plots.

True
print_stats bool

Print comparison statistics.

False
**kwargs

Styling options.

{}
Source code in lelantos/cosmology.py
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
def plot(
    self,
    value_names,
    name,
    comparison=None,
    comparison_legend=None,
    histo=True,
    mean_z_dependence=True,
    z_dependence=True,
    ra_dec_plots=True,
    print_stats=False,
    **kwargs,
):
    """Produce the requested delta diagnostic plots for several quantities.

    Args:
        value_names (list[str]): Quantities to plot (``delta``, ``sigma``,
            ``snr``, ``redshift`` ...).
        name (str): Output figure base name.
        comparison (list[str], optional): Comparison delta paths.
        comparison_legend (list[str], optional): Legend labels.
        histo (bool, optional): Draw histograms.
        mean_z_dependence (bool, optional): Draw mean-vs-redshift plots.
        z_dependence (bool, optional): Draw value-vs-redshift plots.
        ra_dec_plots (bool, optional): Draw the RA/Dec and LOS-density plots.
        print_stats (bool, optional): Print comparison statistics.
        **kwargs: Styling options.
    """
    style = utils.return_key(kwargs, "style", None)
    if style is not None:
        plt.style.use(style)

    (ra, dec, redshift, redshift_qso, id, sigma, delta, snr) = self.get_ra_dec(
        self.delta_path
    )
    (
        ra_comp,
        dec_comp,
        redshift_comp,
        redshift_qso_comp,
        id_comp,
        sigma_comp,
        delta_comp,
        snr_comp,
    ) = self.get_ra_dec_comparison(comparison)

    for value_name in value_names:
        value = locals()[value_name]
        comparison_value = locals()[value_name + "_comp"]
        lambda_rest = utils.return_key(kwargs, f"{value_name}_lambda_rest", False)
        if lambda_rest:
            kwargs[f"{value_name}_redshift_qso"] = redshift_qso
        if histo:
            utils.save_histo(
                self.pwd,
                value,
                value_name,
                name,
                comparison=comparison_value,
                comparison_legend=comparison_legend,
                **kwargs,
            )
        if (mean_z_dependence) & (value_name not in ["redshift", "ra", "dec"]):
            utils.save_mean_redshift_dependence(
                self.pwd,
                value,
                redshift,
                value_name,
                name,
                comparison=comparison_value,
                comparison_redshift=redshift_comp,
                comparison_legend=None,
                **kwargs,
            )

        if (z_dependence) & (value_name not in ["redshift", "ra", "dec"]):
            utils.save_redshift_dependence(
                self.pwd,
                value,
                redshift,
                value_name,
                name,
                comparison=comparison_value,
                comparison_redshift=redshift_comp,
                comparison_legend=None,
                **kwargs,
            )
    if ra_dec_plots:
        self.plot_ra_dec(
            ra, dec, name, comparison=None, comparison_legend=None, **kwargs
        )
    if (comparison is not None) & (print_stats):
        self.stat_comparison(
            redshift, redshift_comp, sigma, sigma_comp, delta, delta_comp
        )

plot_ra_dec

plot_ra_dec(ra, dec, name, comparison_ra=None, comparison_dec=None, comparison_legend=None, **kwargs)

Plot the RA/Dec diagram and the LOS-density-vs-RA curve.

Parameters:

Name Type Description Default
ra, dec array - like

Object sky angles.

required
name str

Output figure base name.

required
comparison_ra, comparison_dec list[array]

Comparison sky coordinates.

required
comparison_legend list[str]

Legend labels.

None
**kwargs

Styling options.

{}
Source code in lelantos/cosmology.py
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
def plot_ra_dec(
    self,
    ra,
    dec,
    name,
    comparison_ra=None,
    comparison_dec=None,
    comparison_legend=None,
    **kwargs,
):
    """Plot the RA/Dec diagram and the LOS-density-vs-RA curve.

    Args:
        ra, dec (array-like): Object sky angles.
        name (str): Output figure base name.
        comparison_ra, comparison_dec (list[array], optional): Comparison
            sky coordinates.
        comparison_legend (list[str], optional): Legend labels.
        **kwargs: Styling options.
    """
    utils.save_ra_dec(
        self.pwd,
        ra,
        dec,
        name,
        comparison_ra=comparison_ra,
        comparison_dec=comparison_dec,
        comparison_legend=comparison_legend,
        **kwargs,
    )

    DeltaAnalyzer.plot_los_density(self.pwd, ra, dec, name, **kwargs)

stat_comparison

stat_comparison(redshift, redshift_comp, sigma, sigma_comp, delta, delta_comp)

Print redshift-range, sigma and delta statistics for main vs comps.

Parameters:

Name Type Description Default
redshift, sigma, delta array - like

Main-dataset quantities.

required
redshift_comp, sigma_comp, delta_comp list[array]

Per-comparison quantities.

required
Source code in lelantos/cosmology.py
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
def stat_comparison(
    self, redshift, redshift_comp, sigma, sigma_comp, delta, delta_comp
):
    """Print redshift-range, sigma and delta statistics for main vs comps.

    Args:
        redshift, sigma, delta (array-like): Main-dataset quantities.
        redshift_comp, sigma_comp, delta_comp (list[array]): Per-comparison
            quantities.
    """
    print("Redshift interval =", np.max(redshift), np.min(redshift))
    for i in range(len(redshift_comp)):
        print(
            f"Redshift interval for comp {i} =",
            np.max(redshift_comp[i]),
            np.min(redshift_comp[i]),
        )
    print("Maximal sigma =", np.max(sigma))
    for i in range(len(sigma_comp)):
        print(f"Maximal sigma for comp {i} =", np.max(sigma_comp[i]))
    print("Mean sigma =", np.mean(sigma))
    for i in range(len(sigma_comp)):
        print(f"Mean sigma for comp {i} =", np.mean(sigma_comp[i]))
    print("Median sigma =", np.median(sigma))
    for i in range(len(sigma_comp)):
        print(f"Median sigma for comp {i} =", np.median(sigma_comp[i]))
    print("Mean delta =", np.mean(delta))
    for i in range(len(delta_comp)):
        print(f"Mean delta for comp {i} =", np.mean(delta_comp[i]))

plot_los_density staticmethod

plot_los_density(pwd, ra, dec, plot_name, **kwargs)

Plot the line-of-sight surface density as a function of RA.

Parameters:

Name Type Description Default
pwd str

Output directory.

required
ra, dec array - like

Object sky angles.

required
plot_name str

Output figure base name.

required
**kwargs

nb_interval (RA bins) and different_sign_region (split by Dec sign) options.

{}
Source code in lelantos/cosmology.py
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
@staticmethod
def plot_los_density(pwd, ra, dec, plot_name, **kwargs):
    """Plot the line-of-sight surface density as a function of RA.

    Args:
        pwd (str): Output directory.
        ra, dec (array-like): Object sky angles.
        plot_name (str): Output figure base name.
        **kwargs: ``nb_interval`` (RA bins) and ``different_sign_region``
            (split by Dec sign) options.
    """
    nb_interval = utils.return_key(kwargs, "nb_interval", 20)
    different_sign_region = utils.return_key(kwargs, "different_sign_region", False)

    ra_interval = np.linspace(np.min(ra), np.max(ra), nb_interval)
    ra_size = abs((np.max(ra) - np.min(ra)) / nb_interval)
    ra_array = []
    for i in range(len(ra_interval) - 1):
        ra_array.append((ra_interval[i] + ra_interval[i + 1]) / 2)
    ra_array = np.asarray(ra_array)
    density_array = np.zeros(ra_array.shape)
    density_array_plus = np.zeros(ra_array.shape)
    density_array_minus = np.zeros(ra_array.shape)
    for i in range(len(ra_interval) - 1):
        mask = (ra > ra_interval[i]) & (ra < ra_interval[i + 1])
        density_array[i] = len(ra[mask])
        density_array_plus[i] = len(ra[mask & (dec >= 0)])
        density_array_minus[i] = len(ra[mask & (dec < 0)])
    maxdec = np.max(dec)
    mindec = np.min(dec)
    plt.figure()
    plt.plot(ra_array, density_array / abs(ra_size * (maxdec - mindec)))
    plt.title("LOS density in function of RA")
    plt.grid()
    plt.savefig(os.path.join(pwd, f"{plot_name}_los_density.pdf"), format="pdf")
    if different_sign_region:
        plt.figure()
        plt.plot(ra_array, density_array_plus / abs(ra_size * maxdec))
        plt.title("LOS density in function of RA for DEC >= 0")
        plt.grid()
        plt.savefig(
            os.path.join(pwd, f"{plot_name}_los_density_dec_positive.pdf"),
            format="pdf",
        )
        plt.figure()
        plt.plot(ra_array, density_array_minus / abs(ra_size * mindec))
        plt.title("LOS density in function of RA for DEC < 0")
        plt.grid()
        plt.savefig(
            os.path.join(pwd, f"{plot_name}_los_density_dec_negative.pdf"),
            format="pdf",
        )

plot_delta_gaussian_fit staticmethod

plot_delta_gaussian_fit(pwd, delta, plot_name, **kwargs)

Plot the delta histogram with an overlaid Gaussian fit.

Parameters:

Name Type Description Default
pwd str

Output directory.

required
delta array - like

Delta values.

required
plot_name str

Output figure base name.

required
**kwargs

Histogram styling options.

{}
Source code in lelantos/cosmology.py
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
@staticmethod
def plot_delta_gaussian_fit(pwd, delta, plot_name, **kwargs):
    """Plot the delta histogram with an overlaid Gaussian fit.

    Args:
        pwd (str): Output directory.
        delta (array-like): Delta values.
        plot_name (str): Output figure base name.
        **kwargs: Histogram styling options.
    """
    (name, data, bins, patches) = utils.plot_histo(delta, "delta", "", **kwargs)
    bin_centers = np.array(
        [0.5 * (bins[i] + bins[i + 1]) for i in range(len(bins) - 1)]
    )
    fit_function = lambda x, A, mu, sigma: A * np.exp(
        -1.0 * (x - mu) ** 2 / (2 * sigma**2)
    )
    popt, pcov = curve_fit(
        fit_function, xdata=bin_centers, ydata=data, p0=[1, 0.0, 0.1]
    )
    x = np.linspace(min(bins), max(bins), 1000)
    y = fit_function(x, *popt)
    plt.plot(x, y, "r--", linewidth=2)
    mu, sigma = popt[1], popt[2]
    plt.text(0.8, 2 * np.max(data) / 6, "mu = " + str(round(mu, 8)))
    plt.text(0.8, 1.5 * np.max(data) / 6, "sigma = " + str(round(sigma, 8)))

    plt.savefig(
        os.path.join(pwd, f"{plot_name}_histo_delta_gaussian_fit.pdf"), format="pdf"
    )

get_delta_list

get_delta_list(delta_path)

List all delta-*.fits* files under one or several directories.

Parameters:

Name Type Description Default
delta_path str | list[str]

Directory, or list of directories, holding picca delta files.

required

Returns:

Type Description

numpy.ndarray | list: Sorted list of delta file paths.

Raises:

Type Description
KeyError

If no delta file is found.

Source code in lelantos/cosmology.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def get_delta_list(delta_path):
    """List all ``delta-*.fits*`` files under one or several directories.

    Args:
        delta_path (str | list[str]): Directory, or list of directories, holding
            picca delta files.

    Returns:
        numpy.ndarray | list: Sorted list of delta file paths.

    Raises:
        KeyError: If no delta file is found.
    """
    if type(delta_path) == str:
        delta_list = np.sort(glob.glob(os.path.join(delta_path, "delta-*.fits*")))
    elif type(delta_path) == list:
        delta_list = []
        for i in range(len(delta_path)):
            delta_list = delta_list + list(
                np.sort(glob.glob(os.path.join(delta_path[i], "delta-*.fits*")))
            )
    if len(delta_list) == 0:
        raise KeyError("No delta file was found")
    return delta_list

preselect_deltas

preselect_deltas(namefile, ramin=None, ramax=None, decmin=None, decmax=None, center_ra=True, pk1d_type=True)

Keep only the delta files overlapping a sky window.

Parameters:

Name Type Description Default
namefile list[str]

Delta file paths.

required
ramin, ramax, decmin, decmax float

Sky window bounds.

required
center_ra bool

Recenter RA around 0 before comparing.

True
pk1d_type bool

Whether the deltas are in pk1d format.

True

Returns:

Type Description

list[str]: The subset of files with at least one pixel in the window.

Raises:

Type Description
KeyError

If no file falls inside the window.

Source code in lelantos/cosmology.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def preselect_deltas(
    namefile,
    ramin=None,
    ramax=None,
    decmin=None,
    decmax=None,
    center_ra=True,
    pk1d_type=True,
):
    """Keep only the delta files overlapping a sky window.

    Args:
        namefile (list[str]): Delta file paths.
        ramin, ramax, decmin, decmax (float, optional): Sky window bounds.
        center_ra (bool, optional): Recenter RA around 0 before comparing.
        pk1d_type (bool, optional): Whether the deltas are in pk1d format.

    Returns:
        list[str]: The subset of files with at least one pixel in the window.

    Raises:
        KeyError: If no file falls inside the window.
    """
    subset_namefile = []
    if (ramin is None) & (ramax is None) & (decmin is None) & (decmax is None):
        return namefile
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=pk1d_type)
        delta_tomo.read()
        ra, dec, redshift, redshift_qso, id, sigma, delta = delta_tomo.return_params(
            center_ra=center_ra
        )
        mask = np.full(ra.shape, True)
        if ramin is not None:
            mask &= ra > ramin
        if ramax is not None:
            mask &= ra < ramax
        if decmin is not None:
            mask &= dec > decmin
        if ramin is not None:
            mask &= dec < decmax
        if len(mask[mask]) != 0:
            subset_namefile.append(namefile[i])
    print(len(subset_namefile))
    if len(subset_namefile) == 0:
        raise KeyError("Select window does not contain any delta files")
    return subset_namefile

get_deltas

get_deltas(namefile, center_ra=True, pk1d_type=True)

Extract delta properties

Source code in lelantos/cosmology.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def get_deltas(namefile, center_ra=True, pk1d_type=True):
    """Extract delta properties"""
    ras, decs, redshifts, redshift_qsos, ids, sigmas, deltas = (
        [],
        [],
        [],
        [],
        [],
        [],
        [],
    )
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=pk1d_type)
        delta_tomo.read()
        ra, dec, redshift, redshift_qso, id, sigma, delta = delta_tomo.return_params(
            center_ra=center_ra
        )
        ras.append(ra)
        decs.append(dec)
        redshift_qsos.append(redshift_qso)
        ids.append(id)
        redshifts = redshifts + redshift
        sigmas = sigmas + sigma
        deltas = deltas + delta
    return (
        np.concatenate(ras),
        np.concatenate(decs),
        redshifts,
        np.concatenate(redshift_qsos),
        np.concatenate(ids),
        sigmas,
        deltas,
    )

get_merged_multiple_exposure_deltas

get_merged_multiple_exposure_deltas(namefile)

Merge deltas with repeated observation

Source code in lelantos/cosmology.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def get_merged_multiple_exposure_deltas(namefile):
    """Merge deltas with repeated observation"""
    # Pack LOS by Id in the dict Deltas
    ra, dec, z, deltas, sigmas, zqso = [], [], [], [], [], []
    (Deltas, ids) = get_id_list(namefile)

    # For each pack of LOS
    for i in range(len(ids)):
        # Get the data
        zqso.append(tomographic_objects.Delta.z_qso(Deltas[ids[i]][0]))
        ra.append(tomographic_objects.Delta.ra(Deltas[ids[i]][0]))
        dec.append(tomographic_objects.Delta.dec(Deltas[ids[i]][0]))
        listsigmas, listz, listdelta = [], [], []
        for j in range(len(Deltas[ids[i]])):
            listsigmas.append(1 / np.sqrt(np.asarray(Deltas[ids[i]][j].ivar)))
            listdelta.append(Deltas[ids[i]][j].delta)
            listz.append(
                ((10 ** np.asarray(Deltas[ids[i]][j].log_lambda) / utils.lambdaLy) - 1)
            )

        (listz, listsigmas, listdelta) = delete_los_extrema(
            listz, listsigmas, listdelta
        )

        (listz, listsigmas, listdelta, lenlists) = delete_missing_pixels(
            listz, listsigmas, listdelta
        )

        # Weighted merging of the LOSs
        zmerged, sigmamerged, deltamerged = listz[0], [], []
        for k in range(len(listz[0])):
            sigma = 0
            delta = 0
            sumsigma = 0
            for m in range(len(listz)):
                sumsigma = sumsigma + 1 / (listsigmas[m][k] ** 2)
            for m in range(len(listz)):
                delta = delta + listdelta[m][k] / ((listsigmas[m][k] ** 2) * sumsigma)

                sigma = sigma + 1 / ((listsigmas[m][k] ** 2) * (sumsigma**2))
            sigma = np.sqrt(sigma / len(listz))
            sigmamerged.append(sigma)
            deltamerged.append(delta)
        deltas.append(deltamerged)
        z.append(zmerged)
        sigmas.append(sigmamerged)
    return (
        np.array(ra),
        np.array(dec),
        np.asarray(z),
        np.array(zqso),
        np.array(ids),
        np.asarray(sigmas),
        np.asarray(deltas),
    )

get_id_list

get_id_list(namefile)

Group delta objects by their primary key (line-of-sight id).

Parameters:

Name Type Description Default
namefile list[str]

Delta file paths.

required

Returns:

Name Type Description
tuple

(Deltas, ids) — a dict mapping each id to its list of delta

objects, and the list of unique ids.

Source code in lelantos/cosmology.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def get_id_list(namefile):
    """Group delta objects by their primary key (line-of-sight id).

    Args:
        namefile (list[str]): Delta file paths.

    Returns:
        tuple: ``(Deltas, ids)`` — a dict mapping each id to its list of delta
        objects, and the list of unique ids.
    """
    ids = []
    for i in range(len(namefile)):
        delta_tomo = tomographic_objects.Delta(name=namefile[i], pk1d_type=True)
        delta_tomo.read()
        id = []
        for i in range(len(delta_tomo.delta_array)):
            id.append(tomographic_objects.Delta.primary_key(delta_tomo.delta_array[i]))
        ids.append(id)
    ids = np.concatenate(ids)
    ids = list(set(ids))
    Deltas = {}
    for i in range(len(ids)):
        Deltas[ids[i]] = []
        for j in range(len(namefile)):
            delta_tomo = tomographic_objects.Delta(name=namefile[j], pk1d_type=True)
            delta_tomo.read()
            for k in range(len(delta_tomo.delta_array)):
                if (
                    tomographic_objects.Delta.primary_key(delta_tomo.delta_array[k])
                    == ids[i]
                ):
                    Deltas[ids[i]].append(delta_tomo.delta_array[k])
    return (Deltas, ids)

delete_los_extrema

delete_los_extrema(listz, listsigmas, listdelta)

Trim repeated lines of sight to their common redshift range.

Parameters:

Name Type Description Default
listz list[array]

Per-exposure redshift arrays of one LOS.

required
listsigmas list[array]

Matching sigma arrays.

required
listdelta list[array]

Matching delta arrays.

required

Returns:

Name Type Description
tuple

(listz, listsigmas, listdelta) trimmed to the shared z range.

Source code in lelantos/cosmology.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def delete_los_extrema(listz, listsigmas, listdelta):
    """Trim repeated lines of sight to their common redshift range.

    Args:
        listz (list[array]): Per-exposure redshift arrays of one LOS.
        listsigmas (list[array]): Matching sigma arrays.
        listdelta (list[array]): Matching delta arrays.

    Returns:
        tuple: ``(listz, listsigmas, listdelta)`` trimmed to the shared z range.
    """
    # Get the list of common elements in the pack to have minimum and maximum redshifts
    zmin, zmax = 0, 10**10
    zcommon = listz[0]
    for j in range(1, len(listz)):
        zcommon = list(set(zcommon).intersection(listz[j]))
    zmin = np.min(zcommon)
    zmax = np.max(zcommon)

    # Deleting pixels at the beginning and at the end of LOSs
    for j in range(len(listz)):
        lineToDeleteFirst = 0
        k = 0
        while listz[j][k] != zmin:
            lineToDeleteFirst = lineToDeleteFirst + 1
            k = k + 1
        lineToDeleteLast = 0
        k = -1
        while listz[j][k] != zmax:
            lineToDeleteLast = lineToDeleteLast + 1
            k = k - 1
        listz[j] = listz[j][lineToDeleteFirst : len(listz[j]) - lineToDeleteLast]
        listsigmas[j] = listsigmas[j][
            lineToDeleteFirst : len(listsigmas[j]) - lineToDeleteLast
        ]
        listdelta[j] = listdelta[j][
            lineToDeleteFirst : len(listdelta[j]) - lineToDeleteLast
        ]
    return (listz, listsigmas, listdelta)

delete_missing_pixels

delete_missing_pixels(listz, listsigmas, listdelta)

Align repeated lines of sight by dropping non-shared pixels.

Parameters:

Name Type Description Default
listz list[array]

Per-exposure redshift arrays of one LOS.

required
listsigmas list[array]

Matching sigma arrays.

required
listdelta list[array]

Matching delta arrays.

required

Returns:

Name Type Description
tuple

(listz, listsigmas, listdelta, lenlists) with all exposures

sharing the same pixels, plus their common lengths.

Source code in lelantos/cosmology.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
def delete_missing_pixels(listz, listsigmas, listdelta):
    """Align repeated lines of sight by dropping non-shared pixels.

    Args:
        listz (list[array]): Per-exposure redshift arrays of one LOS.
        listsigmas (list[array]): Matching sigma arrays.
        listdelta (list[array]): Matching delta arrays.

    Returns:
        tuple: ``(listz, listsigmas, listdelta, lenlists)`` with all exposures
        sharing the same pixels, plus their common lengths.
    """
    # Ensuring that all LOS have the same lenght
    lenlists = []
    for j in range(len(listz)):
        lenlists.append(len(listz[j]))

    # Selection of the pixels to delete in case of a missing pixel along one LOS + Deletion
    while np.max(lenlists) != np.min(lenlists):
        eltTodelete = [[] for j in range(len(listz))]
        mi = 10**10
        mins = []
        for j in range(len(lenlists)):
            if lenlists[j] < mi:
                mi = lenlists[j]
                mins = [j]
            elif lenlists[j] == mi:
                mins.append(j)
        for j in range(len(mins)):
            for k in range(len(listz)):
                for m in range(len(listz[k])):
                    if (k != mins[j]) & (
                        np.isin([listz[k][m]], listz[mins[j]]) == False
                    ):
                        eltTodelete[k].append(m)
        newlistz, newlistsigma, newlistdelta = (
            [[] for n in range(len(listz))],
            [[] for n in range(len(listz))],
            [[] for n in range(len(listz))],
        )
        for j in range(len(eltTodelete)):
            eltTodeletej = list(set(eltTodelete[j]))
            for k in range(len(listz[j])):
                if np.isin([k], eltTodeletej) == False:
                    newlistz[j].append(listz[j][k])
                    newlistsigma[j].append(listsigmas[j][k])
                    newlistdelta[j].append(listdelta[j][k])
        listz = newlistz
        listsigmas = newlistsigma
        listdelta = newlistdelta
        lenlists = []
        for j in range(len(listz)):
            lenlists.append(len(listz[j]))
        return (listz, listsigmas, listdelta, lenlists)

compute_shape_size_parallel

compute_shape_size_parallel(extremum_coord, number_chunks, overlaping, shape_sub_map)

Compute the full-map pixel shape and physical size for a tiled run.

Accounts for the pixels shared between overlapping chunks so the merged map has a consistent resolution.

Parameters:

Name Type Description Default
extremum_coord sequence

(Xmin, Xmax, Ymin, Ymax, Zmin, Zmax).

required
number_chunks tuple[int]

Chunk grid (nx, ny).

required
overlaping float

Chunk overlap (Mpc.h^-1).

required
shape_sub_map tuple[int]

Pixel shape of one sub-map.

required

Returns:

Name Type Description
tuple

(shape, size) of the full merged map.

Source code in lelantos/cosmology.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def compute_shape_size_parallel(
    extremum_coord, number_chunks, overlaping, shape_sub_map
):
    """Compute the full-map pixel shape and physical size for a tiled run.

    Accounts for the pixels shared between overlapping chunks so the merged map
    has a consistent resolution.

    Args:
        extremum_coord (sequence): ``(Xmin, Xmax, Ymin, Ymax, Zmin, Zmax)``.
        number_chunks (tuple[int]): Chunk grid ``(nx, ny)``.
        overlaping (float): Chunk overlap (Mpc.h^-1).
        shape_sub_map (tuple[int]): Pixel shape of one sub-map.

    Returns:
        tuple: ``(shape, size)`` of the full merged map.
    """
    if overlaping is None:
        overlaping = 0.0
    minx, maxx = extremum_coord[0], extremum_coord[1]
    miny, maxy = extremum_coord[2], extremum_coord[3]
    minz, maxz = extremum_coord[4], extremum_coord[5]
    intervalx = maxx - minx
    intervaly = maxy - miny
    intervalz = maxz - minz
    subIntervalx = intervalx / number_chunks[0]
    subIntervaly = intervaly / number_chunks[1]
    shape_x = number_chunks[0] * shape_sub_map[0]
    shape_y = number_chunks[1] * shape_sub_map[1]
    remove_shape_x, remove_shape_y = 0, 0
    for i in range(number_chunks[0]):
        for j in range(number_chunks[1]):
            if (i == number_chunks[0] - 1) & (i == 0):
                intervalxChunk = [i * subIntervalx, (i + 1) * subIntervalx]
            elif i == 0:
                intervalxChunk = [
                    i * subIntervalx,
                    (i + 1) * subIntervalx + overlaping,
                ]
            elif i == number_chunks[0] - 1:
                intervalxChunk = [i * subIntervalx - overlaping, intervalx]
            else:
                intervalxChunk = [
                    i * subIntervalx - overlaping,
                    (i + 1) * subIntervalx + overlaping,
                ]
            if (j == number_chunks[1] - 1) & (j == 0):
                intervalyChunk = [j * subIntervaly, (j + 1) * subIntervaly]
            elif j == 0:
                intervalyChunk = [
                    j * subIntervaly,
                    (j + 1) * subIntervaly + overlaping,
                ]
            elif j == number_chunks[1] - 1:
                intervalyChunk = [j * subIntervaly - overlaping, intervaly]
            else:
                intervalyChunk = [
                    j * subIntervaly - overlaping,
                    (j + 1) * subIntervaly + overlaping,
                ]
            size = (
                intervalxChunk[1] - intervalxChunk[0],
                intervalyChunk[1] - intervalyChunk[0],
                intervalz,
            )
            pixel_to_remove = np.around(
                utils.pixel_per_mpc(size, shape_sub_map) * overlaping, 0
            ).astype(int)
            if number_chunks[0] != 1:
                if (i == 0) | (i == number_chunks[0] - 1):
                    remove_shape_x = remove_shape_x + pixel_to_remove[0]
                else:
                    remove_shape_x = remove_shape_x + 2 * pixel_to_remove[0]
            if number_chunks[1] != 1:
                if (j == 0) | (j == number_chunks[1] - 1):
                    remove_shape_y = remove_shape_y + pixel_to_remove[1]
                else:
                    remove_shape_y = remove_shape_y + 2 * pixel_to_remove[1]
    shape_x = shape_x - remove_shape_x // number_chunks[1]
    shape_y = shape_y - remove_shape_y // number_chunks[0]

    size = (maxx - minx, maxy - miny, maxz - minz)
    shape = (shape_x, shape_y, shape_sub_map[2])
    return (shape, size)

compute_shape_size_parallel_from_interface

compute_shape_size_parallel_from_interface(ramin, ramax, decmin, decmax, zmin, zmax, Omega_m, coordinate_transform, number_chunks, overlaping, shape_sub_map, N_coord_edge=100)

Estimate the map shape/size from a footprint and chunking config.

Samples the edges of the (RA, Dec, z) footprint, converts them to cartesian coordinates, and feeds the bounding box to :func:compute_shape_size_parallel.

Parameters:

Name Type Description Default
ramin, ramax, decmin, decmax float

Angular footprint (degrees).

required
zmin, zmax float

Redshift window.

required
Omega_m float

Fiducial matter density.

required
coordinate_transform str

Sky<->cartesian transform mode.

required
number_chunks tuple[int]

Chunk grid.

required
overlaping float

Chunk overlap (Mpc.h^-1).

required
shape_sub_map tuple[int]

Pixel shape of one sub-map.

required
N_coord_edge int

Number of samples per footprint edge.

100

Returns:

Name Type Description
tuple

(shape, size) of the full merged map.

Source code in lelantos/cosmology.py
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
def compute_shape_size_parallel_from_interface(
    ramin,
    ramax,
    decmin,
    decmax,
    zmin,
    zmax,
    Omega_m,
    coordinate_transform,
    number_chunks,
    overlaping,
    shape_sub_map,
    N_coord_edge=100,
):
    """Estimate the map shape/size from a footprint and chunking config.

    Samples the edges of the (RA, Dec, z) footprint, converts them to cartesian
    coordinates, and feeds the bounding box to
    :func:`compute_shape_size_parallel`.

    Args:
        ramin, ramax, decmin, decmax (float): Angular footprint (degrees).
        zmin, zmax (float): Redshift window.
        Omega_m (float): Fiducial matter density.
        coordinate_transform (str): Sky<->cartesian transform mode.
        number_chunks (tuple[int]): Chunk grid.
        overlaping (float): Chunk overlap (Mpc.h^-1).
        shape_sub_map (tuple[int]): Pixel shape of one sub-map.
        N_coord_edge (int, optional): Number of samples per footprint edge.

    Returns:
        tuple: ``(shape, size)`` of the full merged map.
    """
    ra = np.linspace(ramin, ramax, N_coord_edge)
    dec = np.linspace(decmin, decmax, N_coord_edge)
    z = np.linspace(zmin, zmax, N_coord_edge)

    cube_edge_coord = np.concatenate(
        [
            np.array([[ra[i], decmin, zmin] for i in range(N_coord_edge)]),
            np.array([[ramin, dec[i], zmin] for i in range(N_coord_edge)]),
            np.array([[ramin, decmin, z[i]] for i in range(N_coord_edge)]),
            np.array([[ramax, dec[i], zmin] for i in range(N_coord_edge)]),
            np.array([[ramax, decmin, z[i]] for i in range(N_coord_edge)]),
            np.array([[ra[i], decmax, zmin] for i in range(N_coord_edge)]),
            np.array([[ramin, decmax, z[i]] for i in range(N_coord_edge)]),
            np.array([[ra[i], decmin, zmax] for i in range(N_coord_edge)]),
            np.array([[ramin, dec[i], zmax] for i in range(N_coord_edge)]),
            np.array([[ra[i], decmax, zmax] for i in range(N_coord_edge)]),
            np.array([[ramax, dec[i], zmax] for i in range(N_coord_edge)]),
            np.array([[ramax, decmax, z[i]] for i in range(N_coord_edge)]),
        ]
    )

    (rcomov, distang, _, _) = utils.get_cosmo_function(Omega_m)
    suplementary_parameters = utils.return_suplementary_parameters(
        coordinate_transform, zmin=zmin, zmax=zmax
    )

    cartesian_cube_edge_coord = np.zeros_like(cube_edge_coord)

    (
        cartesian_cube_edge_coord[:, 0],
        cartesian_cube_edge_coord[:, 1],
        cartesian_cube_edge_coord[:, 2],
    ) = utils.convert_sky_to_cartesian(
        np.radians(cube_edge_coord[:, 0]),
        np.radians(cube_edge_coord[:, 1]),
        cube_edge_coord[:, 2],
        coordinate_transform,
        rcomov=rcomov,
        distang=distang,
        suplementary_parameters=suplementary_parameters,
    )

    Xmin = np.min(cartesian_cube_edge_coord[:, 0])
    Xmax = np.max(cartesian_cube_edge_coord[:, 0])
    Ymin = np.min(cartesian_cube_edge_coord[:, 1])
    Ymax = np.max(cartesian_cube_edge_coord[:, 1])
    Zmin = np.min(cartesian_cube_edge_coord[:, 2])
    Zmax = np.max(cartesian_cube_edge_coord[:, 2])
    extremum_coord = [Xmin, Xmax, Ymin, Ymax, Zmin, Zmax]

    shape, size = compute_shape_size_parallel(
        extremum_coord,
        number_chunks,
        overlaping,
        shape_sub_map,
    )
    return shape, size