Example #1
0
 def test_cubeit_k(self, m_cubeit):
     from_name = 'temp_fromlist.txt'
     m_context = Mock(__enter__=Mock(return_value=from_name),
                      __exit__=Mock())
     m_temp = MagicMock(return_value=m_context)
     with patch('kalasiris.k_funcs.isis.fromlist.temp', m_temp):
         isis.cubeit_k(['a.cub', 'b.cub', 'c.cub'], to='stacked.cub')
         m_temp.assert_called_with(['a.cub', 'b.cub', 'c.cub'])
         self.assertEqual(m_cubeit.call_args_list,
                          [call(fromlist=from_name, to='stacked.cub')])
Example #2
0
 def test_cubeit_k_files(self):
     a_cube = 'test_cubeit_a.cub'
     isis.makecube(to=a_cube, value=1, samples=2, lines=2, bands=1)
     b_cube = 'test_cubeit_b.cub'
     isis.makecube(to=b_cube, value=1, samples=2, lines=2, bands=1)
     c_cube = 'test_cubeit_c.cub'
     isis.makecube(to=c_cube, value=1, samples=2, lines=2, bands=1)
     s_cube = 'test_cubeit_stacked.cub'
     isis.cubeit_k([a_cube, b_cube, c_cube], to=s_cube)
     for f in (a_cube, b_cube, c_cube, s_cube):
         os.unlink(f)
     with contextlib.suppress(FileNotFoundError):
         Path('print.prt').unlink()
Example #3
0
def HiColorNorm(cubes: list,
                output,
                conf: dict,
                make_unfiltered=True,
                db_list=None,
                keep=False):
    logger.info(f"HiColorNorm start: {cubes}")

    # GetConfigurationParameters()
    conf_check(conf)

    cubes = list(map(ColorCube, cubes, repeat(db_list)))
    cubes.sort()

    outcub_path = set_outpath(output, cubes)

    temp_token = datetime.now().strftime("HiColorNorm-%y%m%d%H%M%S")
    out_p = Path(outcub_path)

    furrow_flag = FurrowCheck(cubes)

    to_del = isis.PathSet()

    for i, _ in enumerate(cubes):
        cubes[i].set_crop_lines(conf)

    for i, c in enumerate(cubes):
        # Protect the processing from erroneous/spurious pixels
        mask_list = list()
        for b in (1, 2, 3):
            tmp_p = to_del.add(
                c.path.with_suffix(f".{temp_token}.temp{b}.cub"))
            isis.mask(
                f"{c.path}+{b}",
                mask=f"{c.path}+{b}",
                to=tmp_p,
                minimum=0.0,
                maximum=2.0,
                preserve="INSIDE",
            )
            mask_list.append(tmp_p)

        c.final_path = c.path.with_suffix(f".HiColorNorm.cub")
        isis.cubeit_k(mask_list, to=c.final_path)

        (cubes[i].mask_path["IR"],
         cubes[i].crop_path["IR"]) = per_color(c, temp_token, "IR", keep=keep)
        (cubes[i].mask_path["BG"],
         cubes[i].crop_path["BG"]) = per_color(c, temp_token, "BG", keep=keep)

    ir_ratio_stddev = per_band(cubes,
                               out_p,
                               temp_token,
                               "IR",
                               furrow_flag,
                               make_unfiltered,
                               keep=keep)
    bg_ratio_stddev = per_band(cubes,
                               out_p,
                               temp_token,
                               "BG",
                               furrow_flag,
                               make_unfiltered,
                               keep=keep)

    if conf["HiColorNorm"]["HiColorNorm_Make_Stitch"]:
        # listpath = to_del.add(c.path.with_suffix(f'.{temp_token}.list.txt'))
        # listpath.write_text(
        #   '\n'.join(str(c.final_path) for c in cubes) + '\n')

        with isis.fromlist.temp([str(c.final_path) for c in cubes]) as f:
            isis.hiccdstitch(fromlist=f, to=out_p)

        for c in cubes:
            to_del.add(c.final_path)

    if not keep:
        to_del.unlink()
        for c in cubes:
            for cc in ("IR", "BG"):
                c.mask_path[cc].unlink()
                c.crop_path[cc].unlink()
                c.nrm_path[cc].unlink()

    logger.info(f"HiColorNorm done.")
    return ir_ratio_stddev, bg_ratio_stddev
Example #4
0
def HiBeautify(cube_paths: list,
               conf: dict,
               out_irb="_IRB.cub",
               out_rgb="_RGB.cub",
               keep=False):
    logger.info(f"HiBeautify start: {', '.join(map(str, cube_paths))}")

    # GetConfigurationParameters()
    cubes = list(map(hcn.ColorCube, cube_paths))
    cubes.sort()

    irb_out_p = hcn.set_outpath(out_irb, cubes)
    rgb_out_p = hcn.set_outpath(out_rgb, cubes)

    temp_token = datetime.now().strftime("HiBeautify-%y%m%d%H%M%S")
    to_del = isis.PathSet()

    # Create an IRB mosaic from the HiColorNorm halves.

    # If a half is missing, we create a mosaic with the proper width and place
    # the half in it at the proper location.
    # Logic ofr image_midpoint and total_width come from original HiColorInit
    # irbmerged_p = to_del.add(out_p.with_suffix(f'.{temp_token}_IRB.cub'))
    image_midpoint = int((2000 / cubes[0].red_bin) + 1)
    outsample = image_midpoint
    if cubes[0].ccdnumber == "4":
        outsample = 1
    total_width = int(2 * cubes[0].samps - (48 / cubes[0].red_bin))

    isis.handmos(
        cubes[0].path,
        mosaic=irb_out_p,
        outline=1,
        outsample=outsample,
        outband=1,
        create="Y",
        nlines=cubes[0].lines,
        nsamp=total_width,
        nbands=3,
    )

    if len(cubes) == 1:
        logger.info("Warning, missing one half!")
    else:
        logger.info("Using both halves")
        isis.handmos(
            cubes[1].path,
            mosaic=irb_out_p,
            outline=1,
            outsample=image_midpoint,
            outband=1,
        )

    # Nothing is actually done to the pixels here regarding the FrostStats, so
    # I'm just going to skip them here.
    #
    # # Determine if Frost/ICE may be present using FrostStats module.
    # frost = None
    # if args.frost:
    #     frost = True
    #     logging.info('Frost override: disabling auto-detection and using '
    #                  'the frost/ice color stretch')
    # if args.nofrost:
    #     frost = False
    #     logging.info('Frost override: disable auto-detection and not using '
    #                  'the frost/ice color stretch')
    # if frost is None:
    #     pass
    #     # get frost stats

    # Subtract the unaltered RED band from the high pass filtered BG for
    # synthetic blue.
    logger.info("Creating synthetic B, subtracting RED from BG")
    rgbsynthb_p = to_del.add(irb_out_p.with_suffix(f".{temp_token}_B.cub"))
    isis.algebra(
        f"{irb_out_p}+3",
        from2=f"{irb_out_p}+2",
        op="subtract",
        to=rgbsynthb_p,
        A=conf["Beautify"]["Synthetic_A_Coefficient"],
        B=conf["Beautify"]["Synthetic_B_Coefficient"],
    )

    # Adjust the BandBin group
    isis.editlab(rgbsynthb_p,
                 grpname="BandBin",
                 keyword="Name",
                 value="Synthetic Blue")
    isis.editlab(rgbsynthb_p, grpname="BandBin", keyword="Center", value="0")
    isis.editlab(rgbsynthb_p, grpname="BandBin", keyword="Width", value="0")

    # HiBeautify gathers and writes a bunch of statistics to PVL that is
    # important to the HiRISE GDS, but not relevant to just producing pixels
    # so I'm omitting it.
    #
    # # Determine the min and max DN values of each band (RED, IR, BG, B) we're
    # # working with.
    # (upper, lower) = conf['Beautify']['Stretch_Exclude_Lines']
    # if upper == 0 and lower == 0:
    #     synthbcrp_p = rgbsynthb_p
    #     irbmrgcrp_p = irbmerged_p
    # else:
    #     synthbcrp_p = to_del.add(
    #           out_p.with_suffix(f'.{temp_token}_Bx.cub'))
    #     irbmrgcrp_p = to_del.add(
    #           out_p.with_suffix(f'.{temp_token}_IRBx.cub'))
    #
    #     for (f, t) in ((rgbsynthb_p, synthbcrp_p),
    #                    (irbmerged_p, irbmrgcrp_p)):
    #         logging.info(isis.crop(f, to=t, propspice=False,
    #                                line=(1 + upper),
    #                                nlines=(
    #                                   cubes[0].lines - lower + upper)).args)
    #
    # stats = dict()
    # stats['B'] = Get_MinMax(synthbcrp_p,
    #                         conf['Beautify']['Stretch_Reduction_Factor'],
    #                         temp_token, keep=keep)
    #
    # for band in cubes[0].band.keys():
    #     stats[band] = Get_MinMax('{}+{}'.format(str(irbmrgcrp_p),
    #                                             cubes[0].band[band]),
    #                              conf['Beautify']['Stretch_Reduction_Factor'],
    #                              temp_token, keep=keep)

    # Create an RGB cube using the RED from the IRB mosaic,
    # the BG from the IRB mosaic and the synthetic B that we just made.
    isis.cubeit_k([f"{irb_out_p}+2", f"{irb_out_p}+3", rgbsynthb_p],
                  to=rgb_out_p)

    if not keep:
        to_del.unlink()

    return