Ejemplo n.º 1
0
 def ImprLtxPresEjecMat(self, doc):
     #doc.append(u"\\subportadilla{Presupuestos Generales}{Presupuesto de ejecución material}" + '\n')
     chapter = pylatex_utils.Chapter(
         title=u'Presupuesto de ejecución material', numbering=False)
     chapter.append(pylatex.Command('cleardoublepage'))
     center = pylatex.Center()
     center.append(pylatex_utils.LargeCommand())
     center.append(pylatex.utils.bold(u'Presupuesto de Ejecución Material'))
     center.append(pylatex_utils.largeCommand())
     chapter.append(center)
     chapter.append(pylatex.VerticalSpace('2cm'))
     self.subcapitulos.ImprLtxResumen(chapter, "", False)
     chapter.append(
         pylatex.utils.bold(u'Presupuesto de Ejecución Material:'))
     chapter.append(pylatex.Command('dotfill'))
     chapter.append(pylatex.utils.bold(self.getLtxPriceString()))
     chapter.append(pylatex.VerticalSpace('0.5cm'))
     chapter.append(pylatex.NewLine())
     chapter.append(
         u'Asciende el presente presupuesto de ejecución material a la expresada cantidad de: '
     )
     chapter.append(
         pylatex_utils.textsc(
             basic_types.to_words(self.getRoundedPrice(), False) +
             ' euros.'))
     chapter.append(pylatex_utils.input('firmas'))
     doc.append(chapter)
Ejemplo n.º 2
0
def table() -> pylatex.Table:
    optics_single = optics.as_designed_single_channel()
    model_distortion = optics_single.rays_output.distortion.model()
    model_distortion_relative = optics_single.rays_output_relative.distortion.model(
    )

    def fmt_coeff(coeff: u.Quantity):
        return kgpy.format.quantity(
            a=coeff.value * u.dimensionless_unscaled,
            scientific_notation=True,
            digits_after_decimal=2,
        )

    result = pylatex.Table()
    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular('ll|rr')) as tabular:
            tabular.escape = False
            tabular.append(
                '\multicolumn{2}{l}{Coefficient} & $x\'$ & $y\'$\\\\')
            tabular.add_hline()
            for c, name in enumerate(model_distortion.x.coefficient_names):
                tabular.add_row([
                    f'{name}',
                    f'({model_distortion.x.coefficients[c].unit:latex_inline})',
                    fmt_coeff(
                        model_distortion_relative.x.coefficients[c].squeeze()),
                    fmt_coeff(
                        model_distortion_relative.y.coefficients[c].squeeze()),
                ])
    return result
Ejemplo n.º 3
0
def table() -> pylatex.Table:
    result = pylatex.Table(position='!htb')
    result._star_latex_name = True
    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular(table_spec='llll', )) as tabular:
            tabular.escape = False
            tabular.add_row(
                ['Parameter', 'Requirement', 'Science Driver', 'Capabilities'])
            tabular.add_hline()
            tabular.add_row([
                r'Spectral line',
                r'\OV',
                r'\EEs',
                r'\OVion, \MgXion, \HeIion, Figure~\ref{fig:bunch}',
            ])
            tabular.add_row([
                r'Spectral sampling',
                r'\spectralResolutionRequirement',
                r'Broadening from \MHD\ waves',
                r'\dispersionDoppler, Table~\ref{table:prescription}',
            ])
            tabular.add_row([
                r'Spatial resolution',
                r'\angularResolutionRequirement (\spatialResolutionRequirement)',
                r'\EEs',
                r'\spatialResolutionTotal, Table~\ref{table:errorBudget}',
            ])
            tabular.add_row([
                r'\SNRShort',
                r'\snrRequirement\ (\CHShort)',
                r'\MHD\ waves in \CHShort',
                r'\StackedCoronalHoleSNR\ ($\NumExpInStack \times \text{\detectorExposureLength}$ exp.), '
                r'Table~\ref{table:counts}',
            ])
            tabular.add_row([
                r'Cadence',
                r'\cadenceRequirement',
                r'Torsional waves',
                r'\detectorExposureLength\ eff., Section~\ref{subsec:SensitivityandCadence}',
            ])
            tabular.add_row([
                r'Observing time',
                r'\observingTimeRequirement',
                r'\EEs',
                r'\SI{270}{\second}, Section~\ref{sec:MissionProfile}',
            ])
            tabular.add_row([
                r'\FOV\ diameter',
                r'\fovRequirement',
                r'Span \QSShort, \ARShort, and limb',
                r'\fov, Table~\ref{table:prescription}',
            ])
    result.add_caption(
        pylatex.NoEscape(
            r"""\ESIS\ instrument requirements and capabilties. Note that MTF exceeds the Rayleigh criterion of 0.109."""
        ))
    result.append(kgpy.latex.Label('table:scireq'))
    return result
Ejemplo n.º 4
0
 def ImprLtxPresContrata(self, doc):
     #doc.append(u"\\subportadilla{Presupuestos Generales}{Presupuesto de ejecución por contrata}" + '\n')
     chapter = pylatex_utils.Chapter(
         title=u'Presupuesto de ejecución por contrata', numbering=False)
     chapter.append(pylatex.Command('cleardoublepage'))
     center = pylatex.Center()
     center.append(pylatex_utils.LargeCommand())
     center.append(
         pylatex.utils.bold(u'Presupuesto de Ejecución por Contrata'))
     center.append(pylatex_utils.largeCommand())
     chapter.append(center)
     chapter.append(pylatex.VerticalSpace('2cm'))
     self.percentages.printLtx(chapter, self.getRoundedPrice())
     chapter.append(pylatex_utils.input('firmas'))
     doc.append(chapter)
Ejemplo n.º 5
0
def _add_setup_notes(document: pylatex.Document, texts: dict,
                     images: dict) -> None:
    document.append(
        pylatex.Subsection(
            title=texts["setup"]["title"],
            label=False,
            numbering=False,
        ))
    document.append(texts["setup"]["text0"])
    document.append(_make_img(images["stage-setup"], width=0.8))

    document.append(texts["setup"]["text1"])
    document.append(
        pylatex.Center(data=[
            _make_img(
                images["transducer"], width=0.3, position="h", add_figure=True)
        ]))
Ejemplo n.º 6
0
    def add_table(self, table, header, caption=None):
        self.len_last_page += len(table)
        if self.len_last_page > 35:
            self.len_last_page = len(table)
            self.new_page()

        with self.doc.create(pylatex.Center()) as center, \
                center.create(
                    pylatex.LongTable("l|" + "|c" * (len(header) - 1))) \
                        as latex_table:
            latex_table.add_hline()
            latex_table.add_row(header)
            latex_table.add_hline()
            latex_table.end_table_header()

            latex_table.append(pylatex.NoEscape(str(table)))
            latex_table.add_hline()

            if caption is not None:
                caption = caption.replace("_", "\\_")
                self.doc.append(pylatex.NoEscape(caption))
Ejemplo n.º 7
0
def table() -> pylatex.Table:
    optics_all = esis.flight.optics.as_measured()
    detector = optics_all.detector
    result = pylatex.Table()
    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular('ccccc')) as tabular:
            tabular.escape = False
            tabular.add_row([
                r'Channel',
                r'Quad.',
                r'Gain',
                r'Read noise',
                r'Dark current',
            ])
            tabular.add_row([
                '', '', f'({detector.gain.unit:latex_inline})',
                f'({detector.readout_noise.unit:latex_inline})',
                f'({detector.dark_current.unit:latex_inline})'
            ])
            tabular.add_hline()
            for i in range(detector.gain.shape[0]):
                for j in range(detector.gain.shape[1]):
                    if j == 0:
                        channel_name_i = optics_all.channel_name[i]
                        serial_number_i = f'({detector.serial_number[i]})'
                    else:
                        channel_name_i = ''
                        serial_number_i = ''
                    tabular.add_row([
                        f'{channel_name_i} {serial_number_i}',
                        j + 1,
                        detector.gain[i, j].value,
                        detector.readout_noise[i, j].value,
                        f'{detector.dark_current[i, j].value:0.3f}',
                    ])
                tabular.add_hline()
    result.add_caption(pylatex.NoEscape(r'\ESIS\ camera properties'))
    result.append(kgpy.latex.Label('tabel:cameraProperties'))
    return result
Ejemplo n.º 8
0
def table_old() -> pylatex.Table:
    result = pylatex.Table()
    result._star_latex_name = True
    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular('llrr')) as tabular:
            tabular.escape = False
            tabular.add_row(
                [r'Element', r'Parameter', r'Requirement', r'Measured'])
            tabular.add_hline()
            tabular.add_row(
                [r'Primary', r'RMS slope error ($\mu$rad)', r'$<1.0$', r''])
            tabular.add_row([r'', r'Integration length (mm)', r'4.0', r''])
            tabular.add_row([r'', r'Sample length (mm)', r'2.0', r''])
            tabular.add_hline()
            tabular.add_row(
                [r'Primary', r'RMS roughness (nm)', r'$<2.5$', r''])
            tabular.add_row([r'', r'Periods (mm)', r'0.1-6', r''])
            tabular.add_hline()
            tabular.add_row(
                [r'Grating', r'RMS slope error ($\mu$rad)', r'$<3.0$', r''])
            tabular.add_row([
                r'', r'Integration length (mm)', r'2 \roy{why fewer sigfigs?}',
                r''
            ])
            tabular.add_row([r'', r'Sample length (mm)', r'1', r''])
            tabular.add_hline()
            tabular.add_row(
                [r'Grating', r'RMS roughness (nm)', r'$<2.3$', r''])
            tabular.add_row([r'', r'Periods (mm)', r'0.02-2', r''])
            tabular.add_hline()
    result.add_caption(
        pylatex.NoEscape(r"""
Figure and surface roughness requirements compared to metrology for the \ESIS\ optics.
Slope error (both the numerical estimates and the measurements) is worked out with integration length and sample length 
defined per ISO 10110."""))
    result.append(kgpy.latex.Label('table:error'))
    return result
Ejemplo n.º 9
0
def table(doc: kgpy.latex.Document) -> pylatex.Table:
    requirements = esis.optics.design.requirements()
    optics_single = optics.as_designed_single_channel()
    opt = esis.optics.design.final(**optics.error_kwargs)

    wavelength = optics_single.bunch.wavelength
    index_o5 = np.nonzero(optics_single.bunch.ion == 'o_5')[0][0]
    wavelength_o5 = wavelength[index_o5]
    # opt = esis.optics.design.final(
    #     pupil_samples=101,
    #     # pupil_is_stratified_random=True,
    #     field_samples=11,
    #     all_channels=False,
    # )

    # psf_diffraction = opt.system.psf_diffraction

    # plt.figure()
    # plt.imshow(psf_diffraction.data[5,~0,..., 0].T, aspect='auto')
    #
    # print('position', psf_diffraction.grid.position)
    # print('position', psf_diffraction.grid.position.points.x.shape)
    # print('position', psf_diffraction.grid.position.points.y.shape)

    # opt.psf_diffraction
    opt.mtf_diffraction
    plt.show()

    # rays_grating = opt.system.raytrace[opt.system.surfaces_all.flat_local.index(opt.grating.surface)]
    # rays_grating.pupil_hist2d(bins=100)
    # plt.show()

    frequency_requirement = 1 / requirements.resolution_angular

    def calc_mtf(optics: esis.optics.Optics):
        rays = optics.rays_output
        mtf, frequency = rays.mtf(
            bins=200,
            frequency_min=frequency_requirement,
        )
        print('mtf', mtf.mean())
        print('frequency', frequency)
        mtf = np.take(a=mtf, indices=[index_o5], axis=rays.axis.wavelength)
        print('mtf', mtf.mean())
        mtf = np.mean(
            mtf.value, axis=rays.axis.field_xy, keepdims=True,
            where=mtf != 0) << mtf.unit
        print('mtf', mtf.mean())
        frequency = frequency.take(indices=[index_o5],
                                   axis=rays.axis.wavelength)
        frequency = np.mean(frequency, axis=rays.axis.field_xy, keepdims=True)

        plt.figure()
        plt.imshow(mtf.squeeze().T)

        with astropy.visualization.quantity_support():
            plt.figure()
            plt.plot(
                frequency.x.take(indices=0, axis=rays.axis.pupil_x).squeeze(),
                mtf.take(indices=0, axis=rays.axis.pupil_x).squeeze())
            plt.plot(
                frequency.y.take(indices=0, axis=rays.axis.pupil_y).squeeze(),
                mtf.take(indices=0, axis=rays.axis.pupil_y).squeeze())

        mtf = np.take(a=mtf, indices=[0], axis=rays.axis.pupil_x)
        print('mtf', mtf.mean())
        index_frequency_requirement = np.argmax(frequency.y.take(
            indices=[0], axis=rays.axis.pupil_x) >= frequency_requirement,
                                                axis=rays.axis.pupil_y)
        index_frequency_requirement = np.expand_dims(
            index_frequency_requirement, axis=rays.axis.pupil_y)
        print('index frequency requirement', index_frequency_requirement.shape)
        # mtf = np.take(a=mtf, indices=[index_frequency_requirement], axis=rays.axis.pupil_y)
        mtf = np.take_along_axis(mtf,
                                 indices=index_frequency_requirement,
                                 axis=rays.axis.pupil_y)
        print('mtf', mtf.mean())
        print('mtf.shape', mtf.shape)
        return mtf.squeeze()

    mtf_nominal = calc_mtf(opt)

    accumulator = dict(mtf=1 * u.dimensionless_unscaled, )

    def add_mtf(
        tabular: pylatex.Tabular,
        name_major: str = '',
        name_minor: str = '',
        value_str: str = '',
        mtf: u.Quantity = 0 * u.dimensionless_unscaled,
    ):
        accumulator['mtf'] *= mtf

        tabular.add_row([
            name_major,
            name_minor,
            value_str,
            f'',
            f'',
            f'{mtf.value:0.3f}',
        ])

    def add_optics(
            tabular: pylatex.Tabular,
            optics: typ.Union[esis.optics.Optics,
                              typ.Tuple[esis.optics.Optics,
                                        esis.optics.Optics]],
            name_major: str = '',
            name_minor: str = '',
            value: typ.Optional[typ.Union[u.Quantity,
                                          typ.Tuple[u.Quantity,
                                                    u.Quantity]]] = None,
            value_format_kwargs: typ.Optional[typ.Dict[str, typ.Any]] = None,
            remove_nominal_mtf: bool = True):

        if value_format_kwargs is None:
            value_format_kwargs = dict(
                digits_after_decimal=3,
                scientific_notation=False,
            )

        if not isinstance(optics, esis.optics.Optics):
            optics_min, optics_max = optics

            mtf_min, mtf_max = calc_mtf(optics_min), calc_mtf(optics_max)

            if mtf_max < mtf_min:
                mtf = mtf_max
            else:
                mtf = mtf_min

            if value is not None:
                value_min, value_max = value
                if value_max == -value_min:
                    value_str = f'$\\pm${kgpy.format.quantity(value_max, **value_format_kwargs)}'
                else:
                    raise NotImplementedError
            else:
                value_str = ''

        else:
            mtf = calc_mtf(optics)
            if value is not None:
                value_str = f'{kgpy.format.quantity(value, **value_format_kwargs)}'
            else:
                value_str = ''

        if remove_nominal_mtf:
            mtf = mtf / mtf_nominal

        add_mtf(
            tabular=tabular,
            name_major=name_major,
            name_minor=name_minor,
            value_str=value_str,
            mtf=mtf,
        )

    opt = esis.optics.design.final(**optics.error_kwargs)
    # print(calc_mtf(opt_err))

    # rays_err = opt_err.rays_output
    # # rays_err.position.z = np.broadcast_to(rays_err.wavelength, rays_err.position.shape, subok=True).copy()
    # # rays_err.position = rays_err.distortion.model(inverse=True)(rays_err.position).to(u.arcsec)
    #
    # mtf, frequency = rays_err.mtf(
    #     bins=200,
    #     frequency_min=frequency_requirement,
    # )
    #
    # index_freq = np.argmax(frequency.y == frequency_requirement)
    # print('index_freq', index_freq)
    #
    # mtf[mtf == 0] = np.nan
    # mtf = np.nanmean(mtf, axis=(rays_err.axis.field_x, rays_err.axis.field_y))[..., 0, 0]
    # print('mtf', mtf[0, index_freq])
    #
    # print(mtf.shape)
    #
    # plt.figure()
    # plt.imshow(mtf.T)
    # # plt.show()
    #
    # with astropy.visualization.quantity_support():
    #     plt.figure()
    #     plt.plot(frequency.x, mtf[0])
    #     plt.plot(frequency.y, mtf[..., 0])
    #
    # plt.show()

    units_psf = u.pix
    plate_scale = optics_single.plate_scale
    focal_length_effective = optics_single.magnification.y * optics_single.primary.focal_length

    opt = esis.optics.design.final(**optics.error_kwargs)
    system_psf = np.nanmean(opt.rays_output.spot_size_rms[..., 0, :])

    frequency_mtf_arcsec = 0.5 * u.cycle / u.arcsec
    frequency_mtf = frequency_mtf_arcsec * plate_scale.y / u.cycle

    def to_mtf(psf_size: u.Quantity):
        psf_size = psf_size / np.sqrt(2)
        alpha = 1 / (2 * psf_size**2)
        return np.exp(-(np.pi * frequency_mtf)**2 / alpha)
        # return np.exp(-(2 * np.pi * frequency_mtf * psf_size) ** 2)

    def to_pix(value: u.Quantity):
        return value / (optics_single.detector.pixel_width / u.pix)

    def from_pix(value: u.Quantity):
        return value * (optics_single.detector.pixel_width / u.pix)

    primary_slope_error = optics_single.primary.slope_error.value
    primary_slope_error_psf = focal_length_effective * np.tan(
        2 * primary_slope_error)
    primary_slope_error_psf /= optics_single.detector.pixel_width / u.pix

    opt_primary_decenter_x_max = optics.error_primary_decenter_x_max()
    opt_primary_decenter_x_min = optics.error_primary_decenter_x_min()
    opt_primary_decenter_y_max = optics.error_primary_decenter_y_max()
    opt_primary_decenter_y_min = optics.error_primary_decenter_y_min()

    distance_grating_to_detector = (
        optics_single.detector.transform.translation_eff -
        optics_single.grating.transform.translation_eff).length
    grating_slope_error = optics_single.grating.slope_error.value
    grating_slope_error_psf = distance_grating_to_detector * np.tan(
        2 * grating_slope_error)
    grating_slope_error_psf /= optics_single.detector.pixel_width / u.pix

    opt_grating_translation_x_min = optics.error_grating_translation_x_min()
    opt_grating_translation_x_max = optics.error_grating_translation_x_max()
    opt_grating_translation_y_min = optics.error_grating_translation_y_min()
    opt_grating_translation_y_max = optics.error_grating_translation_y_max()
    opt_grating_translation_z_min = optics.error_grating_translation_z_min()
    opt_grating_translation_z_max = optics.error_grating_translation_z_max()
    opt_grating_roll_min = optics.error_grating_roll_min()
    opt_grating_roll_max = optics.error_grating_roll_max()
    opt_grating_radius_min = optics.error_grating_radius_min()
    opt_grating_radius_max = optics.error_grating_radius_max()
    opt_grating_ruling_density_min = optics.error_grating_ruling_density_min()
    opt_grating_ruling_density_max = optics.error_grating_ruling_density_max()
    opt_grating_ruling_spacing_linear_min = optics.error_grating_ruling_spacing_linear_min(
    )
    opt_grating_ruling_spacing_linear_max = optics.error_grating_ruling_spacing_linear_max(
    )
    opt_grating_ruling_spacing_quadratic_min = optics.error_grating_ruling_spacing_quadratic_min(
    )
    opt_grating_ruling_spacing_quadratic_max = optics.error_grating_ruling_spacing_quadratic_max(
    )

    opt_detector_translation_x_min = optics.error_detector_translation_x_min()
    opt_detector_translation_x_max = optics.error_detector_translation_x_max()
    opt_detector_translation_y_min = optics.error_detector_translation_y_min()
    opt_detector_translation_y_max = optics.error_detector_translation_y_max()
    opt_detector_translation_z_min = optics.error_detector_translation_z_min()
    opt_detector_translation_z_max = optics.error_detector_translation_z_max()

    rays = opt.system.rays_input.copy()
    rays.position = np.broadcast_to(rays.position,
                                    opt.rays_output.position.shape,
                                    subok=True).copy()
    rays.position[~opt.rays_output.mask] = np.nan
    rays_min = np.nanmin(rays.position,
                         axis=(rays.axis.pupil_x, rays.axis.pupil_y))
    rays_max = np.nanmax(rays.position,
                         axis=(rays.axis.pupil_x, rays.axis.pupil_y))
    rays_range = np.nanmean(rays_max - rays_min)
    detector_x = np.linspace(-1, 1, 100) / 2 * u.pix
    diffraction_intensity = np.sinc(rays_range.x / wavelength_o5 * u.rad *
                                    np.sin(detector_x * opt.plate_scale.x))**2
    model = astropy.modeling.fitting.LevMarLSQFitter()(
        model=astropy.modeling.models.Gaussian1D(),
        x=detector_x,
        y=diffraction_intensity,
    )
    diffraction_limit = np.sqrt(2) * model.stddev.quantity

    accumulator = dict(
        psf_size_squared=0 * u.pix**2,
        mtf=1 * u.dimensionless_unscaled,
        mtf_actual=1 * u.dimensionless_unscaled,
    )

    def add_row_basic(
        tabular: pylatex.Tabular,
        optics: typ.Union[esis.optics.Optics, typ.Tuple[esis.optics.Optics,
                                                        esis.optics.Optics]],
        name_major: str = '',
        name_minor: str = '',
        value_str: str = '',
        psf_size: u.Quantity = 0 * u.um,
        mtf_actual: u.Quantity = 1.0 * u.dimensionless_unscaled,
    ):

        mtf = to_mtf(psf_size)

        tabular.add_row([
            name_major,
            name_minor,
            value_str,
            f'{psf_size.to(u.pix).value:0.2f}',
            f'{(psf_size * optics.plate_scale.y).to(u.arcsec).value:0.2f}',
            f'{mtf.value:0.3f}',
            f'{mtf_actual.value:0.3f}',
        ])

        accumulator['psf_size_squared'] += np.square(psf_size)
        accumulator['mtf_actual'] *= mtf_actual
        accumulator['mtf'] *= mtf

    def add_row(
        tabular: pylatex.Tabular,
        optics: typ.Union[esis.optics.Optics, typ.Tuple[esis.optics.Optics,
                                                        esis.optics.Optics]],
        name_major: str = '',
        name_minor: str = '',
        value: typ.Optional[typ.Union[u.Quantity,
                                      typ.Tuple[u.Quantity,
                                                u.Quantity]]] = None,
        digits_after_decimal: int = 3,
        scientific_notation: bool = False,
        remove_nominal_psf: bool = True,
    ):
        format_kwargs = dict(
            digits_after_decimal=digits_after_decimal,
            scientific_notation=scientific_notation,
        )

        if not isinstance(optics, esis.optics.Optics):
            optics_min, optics_max = optics

            psf_size_min = np.nanmean(
                optics_min.rays_output.spot_size_rms[..., 0, :])
            psf_size_max = np.nanmean(
                optics_max.rays_output.spot_size_rms[..., 0, :])

            if psf_size_max > psf_size_min:
                optics = optics_max
            else:
                optics = optics_min

            if value is not None:
                value_min, value_max = value
                if value_max == -value_min:
                    value_str = f'$\\pm${kgpy.format.quantity(value_max, **format_kwargs)}'
                else:
                    raise NotImplementedError
            else:
                value_str = ''

        else:
            if value is not None:
                value_str = f'{kgpy.format.quantity(value, **format_kwargs)}'
            else:
                value_str = ''

        psf_size = np.nanmean(optics.rays_output.spot_size_rms[..., 0, :])
        mtf_actual = calc_mtf(optics)
        print('mtf actual', mtf_actual)
        if remove_nominal_psf:
            psf_size = np.nan_to_num(
                np.sqrt(np.square(psf_size) - np.square(system_psf)))
            mtf_actual = mtf_actual / mtf_nominal

        add_row_basic(
            tabular=tabular,
            optics=optics,
            name_major=name_major,
            name_minor=name_minor,
            value_str=value_str,
            psf_size=psf_size,
            mtf_actual=mtf_actual,
        )

    def ptp_to_rms(value: u.Quantity) -> u.Quantity:
        return value / np.sqrt(8)

    result = pylatex.Table()
    result._star_latex_name = True
    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular('ll|rrrrr')) as tabular:
            tabular.escape = False
            tabular.add_row([
                r'Element',
                r'',
                r'Tolerance',
                f'$\\sigma$ ({units_psf:latex_inline})',
                f'$\\sigma$ ({u.arcsec:latex_inline})',
                r'\MTF\ from $\sigma$',
                r'\MTF\ actual ',
            ])
            tabular.add_hline()
            add_row(
                tabular=tabular,
                optics=opt,
                name_major='System',
                name_minor='Aberration',
                remove_nominal_psf=False,
            )
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_minor='Diffraction',
                psf_size=diffraction_limit,
            )
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_minor='Thermal drift',
                psf_size=ptp_to_rms(opt.sparcs.pointing_drift /
                                    opt.plate_scale.x *
                                    opt.detector.exposure_length),
            )
            tabular.add_hline()
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_major='Primary',
                name_minor='RMS Slope error',
                value_str=
                f'{kgpy.format.quantity(primary_slope_error, digits_after_decimal=1)}',
                psf_size=primary_slope_error_psf,
                mtf_actual=opt.primary.mtf_degradation_factor,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_primary_decenter_x_min,
                    opt_primary_decenter_x_max,
                ),
                name_minor='Translation $x$',
                value=(
                    -opt_primary_decenter_x_min.primary.translation_error.
                    value.xy.length,
                    opt_primary_decenter_x_max.primary.translation_error.value.
                    xy.length,
                ),
                digits_after_decimal=0,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_primary_decenter_y_min,
                    opt_primary_decenter_y_max,
                ),
                name_minor='Translation $y$',
                value=(
                    -opt_primary_decenter_y_min.primary.translation_error.
                    value.xy.length,
                    opt_primary_decenter_y_max.primary.translation_error.value.
                    xy.length,
                ),
                digits_after_decimal=0,
            )
            tabular.add_hline()
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_major='Grating',
                name_minor='RMS Slope error',
                value_str=
                f'{kgpy.format.quantity(grating_slope_error, digits_after_decimal=1)}',
                psf_size=grating_slope_error_psf,
                mtf_actual=opt.grating.mtf_degradation_factor,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_translation_x_min,
                    opt_grating_translation_x_max,
                ),
                name_minor='Translation $x$',
                value=(
                    -opt_grating_translation_x_min.grating.translation_error.
                    value.xy.length,
                    opt_grating_translation_x_max.grating.translation_error.
                    value.xy.length,
                ),
                digits_after_decimal=0,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_translation_y_min,
                    opt_grating_translation_y_max,
                ),
                name_minor='Translation $y$',
                value=(
                    -opt_grating_translation_y_min.grating.translation_error.
                    value.xy.length,
                    opt_grating_translation_y_max.grating.translation_error.
                    value.xy.length,
                ),
                digits_after_decimal=0,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_translation_z_min,
                    opt_grating_translation_z_max,
                ),
                name_minor='Translation $z$',
                value=(
                    opt_grating_translation_z_min.grating.translation_error.z,
                    opt_grating_translation_z_max.grating.translation_error.z,
                ),
                digits_after_decimal=3,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_roll_min,
                    opt_grating_roll_max,
                ),
                name_minor='Roll',
                value=(
                    opt_grating_roll_min.grating.roll_error,
                    opt_grating_roll_max.grating.roll_error,
                ),
                digits_after_decimal=3,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_radius_min,
                    opt_grating_radius_max,
                ),
                name_minor='Radius',
                value=(
                    opt_grating_radius_min.grating.tangential_radius_error,
                    opt_grating_radius_max.grating.tangential_radius_error,
                ),
                digits_after_decimal=1,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_ruling_density_min,
                    opt_grating_ruling_density_max,
                ),
                name_minor='Ruling density',
                value=(
                    opt_grating_ruling_density_min.grating.
                    ruling_density_error,
                    opt_grating_ruling_density_max.grating.
                    ruling_density_error,
                ),
                digits_after_decimal=1,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_ruling_spacing_linear_min,
                    opt_grating_ruling_spacing_linear_max,
                ),
                name_minor='Linear coeff.',
                value=(
                    opt_grating_ruling_spacing_linear_min.grating.
                    ruling_spacing_coeff_linear_error,
                    opt_grating_ruling_spacing_linear_max.grating.
                    ruling_spacing_coeff_linear_error,
                ),
                digits_after_decimal=1,
                scientific_notation=True,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_grating_ruling_spacing_quadratic_min,
                    opt_grating_ruling_spacing_quadratic_max,
                ),
                name_minor='Quadratic coeff.',
                value=(
                    opt_grating_ruling_spacing_quadratic_min.grating.
                    ruling_spacing_coeff_quadratic_error,
                    opt_grating_ruling_spacing_quadratic_max.grating.
                    ruling_spacing_coeff_quadratic_error,
                ),
                digits_after_decimal=1,
                scientific_notation=True,
            )
            tabular.add_hline()
            add_row(
                tabular=tabular,
                optics=(
                    opt_detector_translation_x_min,
                    opt_detector_translation_x_max,
                ),
                name_major='Detector',
                name_minor='Translation $x$',
                value=(
                    -opt_detector_translation_x_min.detector.translation_error.
                    value.xy.length,
                    opt_detector_translation_x_max.detector.translation_error.
                    value.xy.length,
                ),
                digits_after_decimal=0,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_detector_translation_y_min,
                    opt_detector_translation_y_max,
                ),
                name_minor='Translation $y$',
                value=(
                    -opt_detector_translation_y_min.detector.translation_error.
                    value.xy.length,
                    opt_detector_translation_y_max.detector.translation_error.
                    value.xy.length,
                ),
                digits_after_decimal=0,
            )
            add_row(
                tabular=tabular,
                optics=(
                    opt_detector_translation_z_min,
                    opt_detector_translation_z_max,
                ),
                name_minor='Translation $z$',
                value=(
                    opt_detector_translation_z_min.detector.translation_error.
                    z,
                    opt_detector_translation_z_max.detector.translation_error.
                    z,
                ),
                digits_after_decimal=2,
            )
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_minor='Charge diffusion',
                psf_size=to_pix(opt.detector.charge_diffusion),
            )
            tabular.add_hline()
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_major=r'\SPARCSShort',
                name_minor='Pointing jitter',
                value_str=
                f'$\\pm${kgpy.format.quantity(opt.sparcs.pointing_jitter / 2, digits_after_decimal=2)}',
                psf_size=ptp_to_rms(opt.sparcs.pointing_jitter /
                                    opt.plate_scale.x),
            )
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_minor='Pointing drift',
                value_str=f'{kgpy.format.quantity(opt.sparcs.pointing_drift)}',
                psf_size=ptp_to_rms(opt.sparcs.pointing_drift /
                                    opt.plate_scale.x *
                                    opt.detector.exposure_length),
            )
            pointing = 10 * u.arcmin
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_minor='Roll jitter',
                value_str=
                f'$\\pm${kgpy.format.quantity(opt.sparcs.rlg_jitter / 2, digits_after_decimal=0)}',
                psf_size=ptp_to_rms(2 * np.sin(opt.sparcs.rlg_jitter / 2) *
                                    pointing / opt.plate_scale.x),
            )
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_minor='Roll drift',
                value_str=f'{kgpy.format.quantity(opt.sparcs.rlg_drift)}',
                psf_size=ptp_to_rms(2 * np.sin(
                    opt.sparcs.rlg_drift * opt.detector.exposure_length / 2) *
                                    pointing / opt.plate_scale.x),
            )
            tabular.add_hline()
            tabular.add_hline()
            psf_size_total = np.sqrt(accumulator['psf_size_squared'])
            doc.set_variable_quantity(
                name='spatialResolutionTotal',
                value=2 * psf_size_total * opt.plate_scale.x,
                digits_after_decimal=2,
            )
            add_row_basic(
                tabular=tabular,
                optics=opt,
                name_major='Total',
                psf_size=psf_size_total,
                mtf_actual=accumulator['mtf_actual'],
            )
    result.add_caption(
        pylatex.NoEscape(f"""
Imaging error budget and tolerance analysis results. 
\\MTF\\ is given at {kgpy.format.quantity(frequency_mtf_arcsec, digits_after_decimal=1)}."""
                         ))
    result.append(kgpy.latex.Label('table:errorBudget'))
    return result
Ejemplo n.º 10
0
def generate(data, doc):
    parties = data['parties']
    resources = data['resources']

    doc.append(
        pl.Center(data=pl.LargeText('RIPE NCC Resource Transfer Agreement')))
    doc.append(pl.NoEscape(r"\hrule height .1mm"))
    doc.append(pl.NoEscape(r"\vspace{.5cm}"))

    doc.append(pl.utils.bold(genlib.gen_party(parties['offering'])))
    doc.append('\n(Offering Party)')

    doc.append('\n\nAnd:\n\n')
    doc.append(pl.utils.bold(genlib.gen_party(parties['recieving'])))
    doc.append('\n(Recieving Party)\n\n')

    doc.append('Jointly mentioned as "Both Parties"\n\nWhereas\n\n')
    doc.append(
        'I. Both Parties have entered into either a Standard Service Agreement with the RIPE NCC or an End User Assignment Agreement with a sponsoring LIR (both or either agreement hereafter referred to as "Basic Agreement")\n\n'
    )
    doc.append(
        'II. The Offering Party has requested the registration of Internet number resources from the RIPE NCC and the RIPE NCC has registered Internet number resources to the Offering Party including the resources listed below (hereafter referred to as "Internet Number Resources"):\n\n'
    )

    # table here
    with doc.create(pl.Tabular('| p{6cm} | p{4cm} |')) as table:
        table.add_hline()
        table.add_row(("Resource", "Type"))
        table.add_hline()

        for r in resources:
            table.add_row((r['content'], r['type']))
            table.add_hline()

    doc.append('\n\n')

    doc.append('''
    III. Both Parties have agreed to transfer the registration of the Internet Number Resources from the Offering Party to the Receiving Party.

    IV. The Receiving Party acknowledges and agrees to use them according to the relevant RIPE Policies.

    Both Parties:

    1. Request that the RIPE NCC undertake the appropriate actions so that the registration of the Internet Number Resources is transferred from the Offering Party to the Receiving Party and all relevant information is accordingly updated in the RIPE Registry.

    2. Acknowledge, confirm and agree the following:

    2.1 The terms and conditions of this transfer may be the subject of a separate agreement of which the RIPE NCC is not part. The RIPE NCC shall not be responsible and cannot be held liable for this transfer, or for its non-fulfillment due to any reason derived from a dispute or a disagreement between the Offering Party and the Receiving Party.

    2.2 Both Parties acknowledge that due to this transfer, all rights and obligations with regards to the registration of the relevant Internet Number Resources that arise from the Basic Agreement will be also transferred from the Offering Party to the Receiving Party and will be part of the Receiving Party’s Basic Agreement.

    2.3 Any other rights and obligations that arise from the Basic Agreement, including any other rights to any other Internet number resources registered to the Offering Party by the RIPE NCC, are not affected by this transfer.

    2.4 In the event that a provision in a separate agreement is in conflict with a provision in this Transfer Agreement or the Basic Agreement, the provision in this Transfer Agreement and the Basic Agreement shall prevail.

    2.5 The RIPE NCC shall not be responsible and cannot be held liable for this transfer, or for the non-fulfillment of this transfer due to restrictions from RIPE Policies.

    2.6 If any of the information and/or documentation provided in connection with this request is subsequently found by the RIPE NCC to be substantially incorrect, falsified or misleading, the RIPE NCC reserves the right to revert all changes made to the RIPE Registry accordingly. This applies equally to all information and documentation provided to the RIPE NCC by Both Parties with regards to this request.

    2.7 The RIPE NCC shall not be responsible and cannot be held liable for any direct and/or indirect damages, including damages to Both Parties’ business, loss of profit damages to third parties caused due to compliance with this request or the ongoing maintenance of the relevant RIPE Registry records in accordance with this request.

    2.8 Both Parties shall indemnify the RIPE NCC against any and all third party claims filed against the RIPE NCC in relation to compliance with this request.\n\n
    ''')

    doc.append(
        'Thus agreed by persons authorised to represent both parties:\n\n')
    genlib.append_sigblock(doc, parties['offering'], parties['recieving'])
Ejemplo n.º 11
0
  def finalize(self):
    doc = util.create_doc(f"Rotated Correlators and Effective Energies: {self.task_name} - {self.ensemble_name}")

    for operator_basis in self.operator_bases:
      logfile = self.logfile(repr(operator_basis))
      rotation_log = sigmond_info.sigmond_log.RotationLog(logfile)
      if rotation_log.failed:
        logging.warning(f"Rotation {operator_basis.name} failed")
        continue

      corr_plotsdir = self.correlator_plotdir(operator_basis)
      energy_plotsdir = self.energy_plotdir(operator_basis)
      util.dirGrace2pdf(corr_plotsdir)
      util.dirGrace2pdf(energy_plotsdir)

      data_files = self.data_handler.getRotatedDataFiles(operator_basis)
      obs_handler, _ = util.get_obs_handlers(data_files, self.bins_info, self.sampling_info)

      with doc.create(pylatex.Section(f"{operator_basis.channel!s} - {operator_basis.name}")):
        with doc.create(pylatex.Subsection("Rotation Info")):
          with doc.create(pylatex.Center()) as centered:
            with centered.create(
                pylatex.LongTabu("X[c]|X[c]|X[c]|X[c]|X[c]|X[3,c]|X[3,c]|X[3,c]|X[3,c]|X[3,c]",
                                 to=r"\linewidth")) as param_table:
              header_row = [
                  pylatex.NoEscape(r"$N_{op}$"),
                  pylatex.NoEscape(r"$N_{\text{d}}$"),
                  pylatex.NoEscape(r"$\tau_N$"),
                  pylatex.NoEscape(r"$\tau_0$"),
                  pylatex.NoEscape(r"$\tau_D$"),
                  pylatex.NoEscape(r"$\xi_{cn}$ (max)"),
                  pylatex.NoEscape(r"$\xi_{cn}^C$ (input)"),
                  pylatex.NoEscape(r"$\xi_{cn}^C$ (retain)"),
                  pylatex.NoEscape(r"$\xi_{cn}^G$ (input)"),
                  pylatex.NoEscape(r"$\xi_{cn}^G$ (retain)"),
              ]
              param_table.add_row(header_row, mapper=[pylatex.utils.bold])
              param_table.add_hline()
              param_table.end_table_header()
              value_row = [
                  operator_basis.num_operators,
                  operator_basis.num_operators - rotation_log.number_levels,
                  operator_basis.pivot_info.norm_time,
                  operator_basis.pivot_info.metric_time,
                  operator_basis.pivot_info.diagonalize_time,
                  operator_basis.pivot_info.max_condition_number,
                  rotation_log.metric_condition(False),
                  rotation_log.metric_condition(True),
                  rotation_log.matrix_condition(False),
                  rotation_log.matrix_condition(True),
              ]
              param_table.add_row(value_row)

          doc.append(pylatex.NoEscape(r"\textbf{Metric Null Space Check:} " + \
                                      rotation_log.metric_null_space_message))

          with doc.create(pylatex.Subsubsection("Input Operators")):
            with doc.create(pylatex.Center()) as centered:
              with centered.create(
                  pylatex.LongTabu("X[2,c] X[c] X[c]", row_height=1.5)) as op_table:
                header_row = [
                    "Operator",
                    pylatex.NoEscape(r"$\delta C(\tau_0)$"),
                    pylatex.NoEscape(r"$\delta C(\tau_D)$")
                ]
                op_table.add_row(header_row, mapper=[pylatex.utils.bold])
                op_table.add_hline()
                op_table.end_table_header()
                for op, errors in rotation_log.diagonal_correlator_errors.items():
                  row = [
                      op,
                      errors.metric,
                      errors.matrix,
                  ]
                  op_table.add_row
                  op_table.add_row(row)

          with doc.create(pylatex.Subsubsection("Diagonal Deviations From Zero")):
            with doc.create(pylatex.Center()) as centered:
              with centered.create(
                  pylatex.LongTabu("X[c] X[4,c] X[3,c] X[3,c] X[3,c] X[3,c] X[2,c]")) as deviation_table:
                header_row = [
                    "time",
                    pylatex.NoEscape(r"$\delta 0_{max}$"),
                    pylatex.NoEscape(r"$\% > 1 \sigma$"),
                    pylatex.NoEscape(r"$\% > 2 \sigma$"),
                    pylatex.NoEscape(r"$\% > 3 \sigma$"),
                    pylatex.NoEscape(r"$\% > 4 \sigma$"),
                    "Status",
                ]
                deviation_table.add_row(header_row, mapper=[pylatex.utils.bold])
                deviation_table.add_hline()
                deviation_table.end_table_header()
                for time, deviation in rotation_log.deviations_from_zero.items():
                  row = [
                      time,
                      deviation.max,
                      deviation.one,
                      deviation.two,
                      deviation.three,
                      deviation.four,
                      deviation.status,
                  ]
                  deviation_table.add_row(row)

        doc.append(pylatex.NoEscape(r"\newpage"))

        operators = self.data_handler.getRotatedOperators(operator_basis)
        with doc.create(pylatex.Subsection("Correlators/Effective Energies")):
          for operator in operators:
            with doc.create(pylatex.Subsubsection(str(operator))):
              corr = sigmond.CorrelatorInfo(operator.operator_info, operator.operator_info)
              util.add_correlator(doc, self, corr, operator_basis, obs_handler)

    results_dir = self.results_dir
    os.makedirs(results_dir, exist_ok=True)
    filename = os.path.join(results_dir, self.task_name)
    util.compile_pdf(doc, filename, self.latex_compiler)
Ejemplo n.º 12
0
def generate(data, doc):
    parties = data['parties']

    doc.append(pl.Center(data=pl.LargeText('Sponsorship Agreement')))
    doc.append(pl.NoEscape(r"\hrule height .1mm"))
    doc.append(pl.NoEscape(r"\vspace{.5cm}"))

    doc.append(pl.NoEscape(genlib.gen_party_flat(parties['lir'], 'LIR')))
    doc.append('\n\nand\n\n')
    doc.append(
        pl.NoEscape(genlib.gen_party_flat(parties['enduser'], 'End User')))

    with doc.create(pl.Section('Article 1 - Definitions')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
\textbf{Agreement}: this Independent Assignment Request and Maintenance Agreement. \\

\textbf{Administration Fee}: fee to be paid by the End User to the LIR for the administrative costs of this Agreement and for handling the initial request for Assignment. \\

\textbf{Assignment}: act by which the RIPE NCC enables the End User to use Independent Internet Number Resources for its internal use. This may involve the publication in the RIPE Database of the End User as the assignee of the respective Internet Number Resources. \\

\textbf{End User}: natural person or legal entity that has entered into this Agreement in order to receive Internet Number Resources for internal purposes. \\

\textbf{Local Internet Registry (LIR)}: a registry in the RIPE NCC service region that receives allocations for Internet Number Resources from an Internet Number Registry for the purpose of assignment to End Users. \\

\textbf{Maintenance Fee}: periodical fee to be paid by the End User to the LIR for handling requests for Assignment and for maintaining Assignments made during the term of the Agreement. \\

\textbf{Independent Internet Number Resources}: Internet Number Resources (Autonomous System (AS) Number, Provider Independent (PI) IPv4 and IPv6), Internet Exchange Point (IXP) and anycasting assignments directly from the RIPE NCC. \\

\textbf{Reverse DNS Delegation}: Reverse Domain Name System (DNS) delegations allow applications to map to a domain name from an IP address. Reverse delegation is achieved by use of the special domain names in-addr.arpa (IPv4) and ipv6.arpa (IPv6). \\

\textbf{RIPE Database}: database operated by the RIPE NCC. The RIPE Database provides a mechanism for finding contact and registration information for networks in the RIPE NCC service region. The RIPE Database contains IP addresses, Autonomous System (AS) Numbers and organisations or customers that are associated with these resources, and related Points of Contact (POC). \\

\textbf{RIPE NCC}: Réseaux IP Européens Network Coordination Centre (RIPE NCC) is a membership association under Dutch law, established in Amsterdam, the Netherlands. The RIPE NCC has, as an Internet Number Registry, the authority to delegate Internet Number Resources in its service region. The RIPE NCC allocates Internet Number Resources to LIRs. In addition, the RIPE NCC assigns Independent Internet Number Resources to End Users for their internal use in accordance with the applicable RIPE policies for assignment of Independent Internet Number Resources to End Users. \\

\textbf{RIPE Policy}: policy relating to Internet Number Resources developed, adopted and published by the RIPE NCC in accordance with the policy process described in the document "Policy Development Process in RIPE", available on http://www.ripe.net. \\
        '''))

    with doc.create(pl.Section('Article 2 - General Provisions')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
2.1 The Agreement shall come into effect upon receipt by the LIR of a hard copy of the Agreement duly signed by (an authorised representative of) the End User together with an extract from the Commercial Trade Register or equivalent document proving the registration of the End User's business with their national authorities. In the event the End User's business has not been incorporated and has not been registered with the Commercial Trade Register, the End User shall send the LIR a photocopy of a valid identity card.\\

2.2 Upon receipt of the signed Agreement and documents as specified in paragraph 2.1, the LIR shall send the End User an invoice for payment of the following Administration Fee: '''
                        + data['admin_fee'] + r'''.\\

2.3 The LIR reserves the right to amend and/or supplement the terms of this Agreement. The LIR shall notify the End User and the RIPE NCC of changes in the terms of the Agreement at least one month prior to any such amendment or supplement coming into effect.\\
        '''))

    with doc.create(
            pl.Section('Article 3 - Request for Assignment')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
3.1 The End User may request an Assignment using the instructions on the LIR website. Upon receipt of the request, the LIR shall submit a request form via the LIR Portal, to the RIPE NCC.\\

3.2 The LIR may suspend the initial request for an Assignment until it has received the Administration Fee as specified in paragraph 2.2 and the Maintenance Fee as specified in paragraph 4.2 for the calendar year in which the Agreement enters into force.\\

3.3 The Assignment is made by the RIPE NCC. The RIPE NCC requires the following conditions to be met before assigning Independent Internet Number Resources:\\

1. the LIR has submitted a request form to the RIPE NCC;\\

2. the RIPE NCC has established that the request complies with the current RIPE policies for Assignment to End Users.\\

\indent
Current documents are available at: http://www.ripe.net/ripe/docs.\\
\indent
Amendments to RIPE policies are published on http://www.ripe.net.\\
        '''))

    with doc.create(
            pl.Section('Article 4 - Maintenance; Conditions for Maintenance')
    ) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(
                r'''
4.1 Subject to the provisions of this Article, the LIR shall maintain the Assignments made by the RIPE NCC upon requests made by the LIR pursuant to this Agreement.\\

4.2 The End User shall pay a periodical Maintenance Fee. The first Maintenance Fee shall be '''
                + data['admin_fee'] +
                r'''. The LIR may amend the Maintenance Fee during the term of the Agreement with such amendment to be published at the LIR's website two months prior to the amendment taking effect.\\

4.3 The End User understands and agrees that the LIR can only maintain the Assignments as long as the assigned Independent Internet Number Resources are used in accordance with RIPE policies as relevant to End Users. More specifically, the LIR shall maintain the Assignments subject to the following conditions:\\

a. The End User shall use the Independent Internet Number Resources assigned to it for internal purposes within its own network only.\\

b. The End User understands and agrees that the Assignment does not confer upon the End User any proprietary or transferable rights in respect of the Independent Internet Number Resources. The End User shall not assign, delegate, sub-delegate or otherwise allow third parties to use the Independent Internet Number Resources assigned to it pursuant to requests made by the LIR pursuant to this Agreement.\\

c. The End User shall use the assigned Independent Internet Number Resources solely for the purpose as specified in the request on the basis of which the Independent Internet Number Resources have been assigned.\\

d. The End User shall comply with the current RIPE policies relevant to End Users, published at www.ripe.net, current documents available in the RIPE Document Store and as may be amended from time to time by the RIPE community in accordance with the RIPE policy process.\\

e. The End User during the term of the Agreement shall provide the LIR with correct and up-to-date information for recording of the Assignment in the RIPE Database.\\

f. The End User shall respond to correspondence by the LIR and the RIPE NCC with regard to Assignments made pursuant to requests under this Agreement and directed at the address as last notified to the LIR by the End User.\\

4.4 The End User understands and agrees that the RIPE NCC may revoke Assignments if the End User does not use the assigned Independent Internet Number Resources in accordance with RIPE policies as relevant to End Users and as further specified in paragraph 4.3.\\
        '''))

    with doc.create(pl.Section('Article 5 - Payment')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
5.1 The End User shall pay the Administration Fee and Maintenance Fee within 30 days of date of invoice, failing which the End User shall be in default, with no notice of default being required.\\

5.2 With effect from the day on which the End User defaults on its payment obligations, the End User shall owe the LIR the statutory rate of interest (highest commercial level) on the amounts unpaid. In addition, the End User shall reimburse the LIR for the extra-judicial collection costs, without prejudice to any other of the LIR's rights, which it may invoke against the End User in connection with the latter's failure to effect (timely) payment.\\
        '''))

    with doc.create(pl.Section('Article 6 - Liability')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
6.1 The LIR does not warrant that the requested Independent Internet Number Resources will be assigned upon request.\\

6.2 The LIR does not warrant that assigned Independent Internet Number Resources will be routable on any part of the Internet.\\

6.3 The End User shall be liable for all aspects of the use of the Independent Internet Number Resources assigned to it and all that ensues from its use of the Independent Internet Number Resources.\\

6.4 The LIR excludes all liability for any direct or indirect damages, including damages to the End User's business, loss of profit, damages to third parties, personal injury or damages to property, except in cases involving wilful misconduct or gross negligence on the part of the LIR or its management.\\

6.5 The LIR shall, in all cases, not be liable for damages caused by a failure by the RIPE NCC to make the Independent Internet Number Resources available (on time), or for damages in any way connected with the use of the Independent Internet Number Resources.\\

6.6 The LIR shall, in all cases, not be liable for non-performance or damages if such is not due to the LIR's fault nor for the account of the LIR pursuant to the law, a juridical act or generally accepted principles.\\

6.7 The End User shall indemnify the LIR against any and all third party claims filed against the LIR in relation to the End User's use of the Independent Internet Number Resources assigned to it pursuant to this Agreement.\\

6.8 In all cases, the LIR's liability shall be limited to a maximum amount equivalent to the aggregate payments received by the LIR pursuant to this Agreement.\\
        '''))

    with doc.create(pl.Section('Article 7 - Term and Termination')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
7.1 The Agreement shall be entered into for an indefinite period of time, until terminated in accordance with this Article 7.\\

7.2 The End User shall be entitled to terminate the Agreement with a notice period of one month. Notice shall be in writing and sent to the LIR by electronic or regular mail.\\

7.3 The LIR shall be entitled to terminate the Agreement with a notice period of three months. Notice shall be in writing and sent to the End User by electronic or regular mail.\\

7.4 In addition, the LIR shall be entitled to terminate the Agreement forthwith with immediate effect by means of a notice sent to the End User by registered mail, without being liable to pay damages to the End User and without prejudice to the LIR's right to claim (additional) damages from the End User if:\\

1. the End User does not comply with (any of) the provisions of paragraph 4.3 (a), (b), (c) or (d).\\

2. the End User fails to fulfil any obligation arising from this Agreement other than those mentioned in paragraph 4.3 (a), (b), (c) and (d), and fails to rectify such failure within 14 days of receipt of notice of said failure.\\

3. the End User fails to observe any rule of applicable law, which should be adhered to by the End User and which, in the opinion of the LIR, is of such a nature as to justify immediate termination.\\

4. an application has been or is filed for the End User's bankruptcy or for a suspension of payments (moratorium).\\

5. the End User goes into liquidation or becomes insolvent.\\

7.5 Termination shall not affect Administrative or Maintenance Fees that have become due or have been paid prior to the date of termination.\\

7.6 Upon termination, the LIR shall ask the RIPE NCC to delete the RIPE Database record for the Independent Internet Number Resources assigned pursuant to this agreement and ask the RIPE NCC to take measures to revoke the Reverse DNS for the respective Independent Internet Number Resources. The End User furthermore understands and accepts that the LIR and the RIPE NCC may take any other measures necessary to enable the Independent Internet Number Resources to become eligible for re-assignment to other End Users.\\

7.7 Upon termination, and except for replacement of an agreement by another agreement for the same Independent Internet Number Resources as meant in paragraph 7.9, the End User shall no longer be entitled to and shall refrain from use of the Independent Internet Number Resources and the Independent Internet Number Resources may be re-assigned by the RIPE NCC to other End Users. The End User understands and accepts that it has not and undertakes not to make any claim as against the LIR or the RIPE NCC for the continued use of the Independent Internet Number Resources.\\

7.8 The Agreement shall automatically expire on the date at which the LIR is declared bankrupt, the LIR has been liquidated or the Standard Service Agreement between the LIR and the RIPE NCC pursuant to which Independent Internet Number Resources have been assigned by the RIPE NCC to the End User has been terminated.\\

7.9 After termination of this Agreement in accordance with paragraph 7.2 or 7.3 or expiry as specified in paragraph 7.8, the End User may seek to extend the right to use for the same Independent Internet Number Resources by entering into an End User Assignment Agreement with the RIPE NCC or by applying for Assignment pursuant to a Independent Assignment Request and Maintenance Agreement with another LIR. The End User understands and agrees that the Independent Internet Number Resources may be re-assigned by the RIPE NCC to another End User if the End User does not seek to extend the right to use within three months of the termination of the Agreement.\\
        '''))

    with doc.create(pl.Section('Article 8 - Governing Law')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
This Agreement shall be exclusively governed by the laws of the country of establishment of the LIR.\\
'''))

    with doc.create(
            pl.Section('Article 9 - Third Party Rights RIPE NCC')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
The rights and actions granted to the RIPE NCC under paragraphs 4.4, 7.7, 7.8, 7.9 and 10.2 are being granted irrevocably and for the sole benefit of the RIPE NCC and without the RIPE NCC being due any consideration.\\
'''))

    with doc.create(pl.Section('Article 10 - Miscellaneous')) as section:
        section.append(pl.NoEscape(r'\noindent'))
        section.append(
            pl.NoEscape(r'''
10.1 Without the LIR's prior written consent, the End User shall not be permitted to assign any rights or obligations arising from the Agreement.\\

10.2 The LIR shall submit to the RIPE NCC copies of this Agreement and the documents submitted by the End User pursuant to this Agreement for the purpose of verifying the status of the Independent Internet Number Resources and compliance with the applicable RIPE policies.\\

10.3 The End User shall notify the LIR immediately of any change of address or billing details. Until such notification, the last notified address and billing details shall be presumed to be correct.\\

10.4 Unless provided otherwise, the LIR may send notifications under this Agreement to the last notified email and mail address of the End User.\\

10.5 If any provision contained in this Agreement is held to be invalid by a court of law, this shall not in any way affect the validity of the remaining provisions.\\

Thus agreed and signed in duplicate by persons authorised to represent both parties:\\
'''))
        genlib.append_sigblock(section, parties['lir'], parties['enduser'])
Ejemplo n.º 13
0
def add_correlator(doc, task_handler, correlator, name, obs_handler):

    operator_src = operator_info.operator.Operator(correlator.getSource())
    subtractvev = task_handler.subtractvev and operator_src.channel.vev
    if correlator.isSinkSourceSame():
        left_pdf_file = task_handler.correlator_plotfile(
            correlator, name, extension=PlotExtension.pdf)
        right_pdf_file = task_handler.energy_plotfile(
            operator_src, name, extension=PlotExtension.pdf)

    else:
        left_pdf_file = task_handler.correlator_plotfile(
            correlator,
            name,
            complex_arg=sigmond.ComplexArg.RealPart,
            extension=PlotExtension.pdf)
        right_pdf_file = task_handler.correlator_plotfile(
            correlator,
            name,
            complex_arg=sigmond.ComplexArg.ImaginaryPart,
            extension=PlotExtension.pdf)

    if correlator.isSinkSourceSame():
        left_estimates = sigmond.getCorrelatorEstimates(
            obs_handler, correlator, task_handler.hermitian, subtractvev,
            sigmond.ComplexArg.RealPart, task_handler.sampling_mode)
        right_estimates = sigmond.getEffectiveEnergy(
            obs_handler, correlator, task_handler.hermitian, subtractvev,
            sigmond.ComplexArg.RealPart, task_handler.sampling_mode,
            task_handler.plot_info.timestep,
            task_handler.plot_info.eff_energy_type.value, 0.)
    else:
        left_estimates = sigmond.getCorrelatorEstimates(
            obs_handler, correlator, task_handler.hermitian, subtractvev,
            sigmond.ComplexArg.RealPart, task_handler.sampling_mode)
        right_estimates = sigmond.getCorrelatorEstimates(
            obs_handler, correlator, task_handler.hermitian, subtractvev,
            sigmond.ComplexArg.ImaginaryPart, task_handler.sampling_mode)

    if correlator.isSinkSourceSame():
        doc.append(pylatex.NoEscape(rf"Score: {score(left_estimates)}"))

    with doc.create(pylatex.Figure(position='H')):
        with doc.create(
                pylatex.SubFigure(
                    position='b',
                    width=pylatex.NoEscape(r'0.5\linewidth'))) as left_fig:
            add_image(left_fig,
                      task_handler.results_dir,
                      left_pdf_file,
                      width="1.0")
        with doc.create(
                pylatex.SubFigure(
                    position='b',
                    width=pylatex.NoEscape(r'0.5\linewidth'))) as right_fig:
            add_image(right_fig,
                      task_handler.results_dir,
                      right_pdf_file,
                      width="1.0")

    if correlator.isSinkSourceSame():
        header_row = [
            pylatex.NoEscape(r"$t$"),
            pylatex.NoEscape(r"$C(t)$"),
            pylatex.NoEscape(r"$\delta C(t)$"),
        ]
        if task_handler.plot_info.eff_energy_type.value < 2:
            header_row.extend([
                pylatex.NoEscape(
                    rf"$a_t E_{{\rm eff}} (t + {task_handler.plot_info.timestep}/2)$"
                ),
                pylatex.NoEscape(
                    rf"$\delta a_t E_{{\rm eff}} (t + {task_handler.plot_info.timestep}/2)$"
                ),
            ])
        else:
            header_row.extend([
                pylatex.NoEscape(r"$a_t E_{\rm eff} (t)$"),
                pylatex.NoEscape(r"$\delta a_t E_{\rm eff} (t)$"),
            ])

    else:
        header_row = [
            pylatex.NoEscape(r"$t$"),
            pylatex.NoEscape(r"$Re C(t)$"),
            pylatex.NoEscape(r"$\delta Re C(t)$"),
            pylatex.NoEscape(r"$Im C(t)$"),
            pylatex.NoEscape(r"$\delta Im C(t)$")
        ]

    with doc.create(pylatex.Center()) as centered:
        with centered.create(
                pylatex.LongTabu("X[c] X[2,c] X[2,c] X[2,c] X[2,c]",
                                 to=r"\linewidth")) as data_table:
            data_table.add_row(header_row, mapper=[pylatex.utils.bold])
            data_table.add_hline()
            data_table.end_table_header()
            for t in sorted(left_estimates.keys()):
                left_value = left_estimates[t].getFullEstimate()
                left_error = left_estimates[t].getSymmetricError()
                left_est = nice_value(left_value, left_error)
                left_rel_error = round(left_estimates[t].getRelativeError(), 4)
                t_right = t
                if correlator.isSinkSourceSame(
                ) and task_handler.plot_info.eff_energy_type.value < 2:
                    t_right = t + 0.5 * task_handler.plot_info.timestep

                if t_right in right_estimates:
                    right_value = right_estimates[t_right].getFullEstimate()
                    right_error = right_estimates[t_right].getSymmetricError()
                    right_est = nice_value(right_value, right_error)
                    right_rel_error = round(
                        right_estimates[t_right].getRelativeError(), 4)
                else:
                    right_est = ""
                    right_rel_error = ""

                row = [
                    int(t), left_est, left_rel_error, right_est,
                    right_rel_error
                ]
                data_table.add_row(row)

    doc.append(pylatex.NoEscape(r"\newpage"))
Ejemplo n.º 14
0
def print_as_latext(dest=None, section_filter=None):
    import pylatex
    if dest is None:
        dest = sys.argv[1] if len(sys.argv) == 2 else 'judo'
    if dest.endswith(".pdf"):
        dest = dest[:-4]

    if section_filter is None:
        section_filter = sys.argv[1].replace('.', "/") if len(
            sys.argv) == 2 else 'judo'

    geometry_options = {
        "tmargin": "0.5cm",
        "lmargin": "1cm",
        "bmargin": "1.5cm"
    }
    doc = pylatex.Document(geometry_options=geometry_options,
                           document_options=['a4paper'])
    doc.preamble.append(pylatex.Command('title', ))
    doc.preamble.append(pylatex.Command('date', pylatex.NoEscape(r'')))

    with doc.create(pylatex.Center()) as centered:
        centered.append(
            pylatex.utils.bold(
                f'Glossaire de {section_filter if section_filter else "judo/jujutsu"}'
            ))

    with doc.create(pylatex.LongTable('rlll')) as table:
        for jp, techniques in sorted(name_to_technique.items()):
            comment, tr = jp_to_desc(jp)

            def do_first():
                table.add_empty_row()
                table.add_row((pylatex.MultiColumn(
                    3,
                    align='l',
                    data=[
                        pylatex.utils.bold(jp.replace("`", "") + " " + tr),
                        pylatex.NoEscape("~"), comment
                    ]), ""))

            if jp in names_renamed:
                comment = "voir " + names_renamed[jp] + "."
                do_first()
                continue

            first = True
            for technique in sorted(techniques):
                if section_filter and not "/".join(
                        group_for_technique[technique]).startswith(
                            section_filter):
                    continue

                if first:
                    do_first()
                    first = False

                tech_name, section, tech_fr = tech_to_glossary(technique)

                if section_filter and section.startswith(section_filter):
                    section = section[len(section_filter) + 1:]

                table.add_row(("", tech_name, tech_fr, section))

    r1 = doc.generate_pdf(dest, clean_tex=True)
    r2 = doc.generate_pdf(dest, clean_tex=False, clean=False)
    r3 = doc.generate_pdf(dest, clean_tex=False, clean=False)
Ejemplo n.º 15
0
    def _add_fits(self,
                  doc,
                  fit_log,
                  fit_name,
                  operator_set,
                  ratio,
                  gap=False,
                  const=False):
        with doc.create(pylatex.Center()) as centered:
            if gap and const and util.ERR_PREC <= 4:
                cols = "X[c] X[c] X[4,c] X[4,c] X[4,c] X[4,c] X[2,c] X[2,c] X[2,c] X[c]"
            elif (gap or const) and util.ERR_PREC <= 4:
                cols = "X[c] X[c] X[4,c] X[4,c] X[4,c] X[2,c] X[2,c] X[2,c] X[c]"
            else:
                cols = "X[c] X[c] X[4,c] X[4,c] X[2,c] X[2,c] X[2,c] X[c]"
            with centered.create(pylatex.LongTabu(
                    cols, to=r"\linewidth")) as fit_table:
                if ratio:
                    energy_header = r"$a_t \Delta E_{\rm fit}$"
                else:
                    energy_header = r"$a_t E_{\rm fit}$"
                header_row = [
                    pylatex.NoEscape(r"$t_{\rm min}$"),
                    pylatex.NoEscape(r"$t_{\rm max}$"),
                    pylatex.NoEscape(energy_header),
                    "A",
                    pylatex.NoEscape(r"$\chi^2 / \text{dof}$"),
                    pylatex.NoEscape(r"$p$-value"),
                    pylatex.NoEscape(r"$t_{\rm exc}$"),
                    pylatex.NoEscape(r"$\sigma_{\rm cut}$"),
                ]
                if const and util.ERR_PREC <= 4:
                    header_row.insert(4, pylatex.NoEscape(r"const"))
                if gap and util.ERR_PREC <= 4:
                    header_row.insert(4, pylatex.NoEscape(r"$a \Delta$"))

                fit_table.add_row(header_row, mapper=[pylatex.utils.bold])
                fit_table.add_hline()
                fit_table.end_table_header()
                for fit_info, fit_result in fit_log.fits.items():
                    value_row = [
                        fit_info.tmin,
                        fit_info.tmax,
                        fit_result.energy,
                        fit_result.amplitude,
                        round(fit_result.chisq, 2),
                        round(fit_result.quality, 2),
                        fit_info.exclude_times,
                        round(fit_info.noise_cutoff, 1),
                    ]
                    if const and util.ERR_PREC <= 4:
                        value_row.insert(4, fit_result.const)
                    if gap and util.ERR_PREC <= 4:
                        value_row.insert(4, fit_result.gap)
                    fit_table.add_row(value_row)

        if self.fit_plots:
            for fit_info1, fit_info2 in zip(*[iter(fit_log.fits.keys())] * 2):
                fit_plot1 = self.fit_plotfile(operator_set,
                                              fit_name,
                                              fit_info1,
                                              extension=util.PlotExtension.pdf)
                fit_plot2 = self.fit_plotfile(operator_set,
                                              fit_name,
                                              fit_info2,
                                              extension=util.PlotExtension.pdf)

                with doc.create(pylatex.Figure(position='H')) as fig:
                    with doc.create(
                            pylatex.SubFigure(position='b',
                                              width=pylatex.NoEscape(
                                                  r'0.5\linewidth'))) as fig1:
                        caption = f"{fit_info1.model.short_name}, $t_{{\\rm fit}} = {fit_info1.tmin}, {fit_info1.tmax}$"
                        if fit_info1.ratio:
                            caption += " Ratio"
                        if fit_info1.exclude_times:
                            caption += f" $t_{{\\rm exc}}$ = {fit_info1.exclude_times}"
                        if fit_info1.noise_cutoff:
                            caption += f" $\sigma_{{\\rm cut}} = {fit_info1.noise_cutoff}$"
                        util.add_image(fig1,
                                       self.results_dir,
                                       fit_plot1,
                                       width="1.0",
                                       caption=caption)
                    with doc.create(
                            pylatex.SubFigure(position='b',
                                              width=pylatex.NoEscape(
                                                  r'0.5\linewidth'))) as fig2:
                        caption = f"{fit_info2.model.short_name}, $t_{{\\rm fit}} = {fit_info2.tmin}, {fit_info2.tmax}$"
                        if fit_info1.ratio:
                            caption += " Ratio"
                        if fit_info2.exclude_times:
                            caption += f" $t_{{\\rm exc}}$ = {fit_info2.exclude_times}"
                        if fit_info2.noise_cutoff:
                            caption += f" $\sigma_{{\\rm cut}} = {fit_info2.noise_cutoff}$"
                        util.add_image(fig2,
                                       self.results_dir,
                                       fit_plot2,
                                       width="1.0",
                                       caption=caption)

            if len(fit_log.fits) % 2 != 0:
                fit_info = list(fit_log.fits.keys())[-1]
                fit_plot = self.fit_plotfile(operator_set,
                                             fit_name,
                                             fit_info,
                                             extension=util.PlotExtension.pdf)
                with doc.create(pylatex.Figure(position='H')) as fig:
                    caption = f"{fit_info.model.short_name}, $t_{{\\rm fit}} = {fit_info.tmin}, {fit_info.tmax}$"
                    if fit_info.ratio:
                        caption += " Ratio"
                    if fit_info.exclude_times:
                        caption += f" $t_{{\\rm exc}}$ = {fit_info.exclude_times}"
                    if fit_info.noise_cutoff:
                        caption += f" $\sigma_{{\\rm cut}} = {fit_info.noise_cutoff}$"
                    util.add_image(fig,
                                   self.results_dir,
                                   fit_plot,
                                   width="0.5",
                                   caption=caption)

        doc.append(pylatex.NoEscape(r"\newpage"))
Ejemplo n.º 16
0
def table() -> pylatex.Table:
    optics_single = optics.as_designed_single_channel()
    optics_all = esis.flight.optics.as_measured()
    primary = optics_single.primary
    grating = optics_single.grating
    unit_length_integration = u.mm
    unit_length_sample = u.mm
    unit_slope_error = u.urad
    unit_ripple_period = u.mm
    unit_ripple = u.nm
    unit_microroughness_period = u.um
    unit_microroughness = u.nm
    result = pylatex.Table()
    result._star_latex_name = True
    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular('llrr')) as tabular:
            tabular.escape = False
            tabular.add_row([
                r'Element',
                r'Parameter',
                r'Requirement',
                r'Measured',
            ])
            tabular.add_hline()
            tabular.add_row([
                r'Primary',
                f'RMS slope error ({unit_slope_error:latex_inline})',
                f'{optics_single.primary.slope_error.value.to(unit_slope_error).value:0.1f}',
                f'{optics_all.primary.slope_error.value.to(unit_slope_error).value:0.1f}',
            ])
            tabular.add_row([
                r'',
                f'\\quad Integration length = {primary.slope_error.length_integration.to(unit_length_integration).value:0.1f}\,{unit_length_integration:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_row([
                r'',
                f'\\quad Sample length = {primary.slope_error.length_sample.to(unit_length_sample).value:0.1f}\,{unit_length_sample:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_row([
                r'',
                f'RMS roughness ({unit_ripple:latex_inline})',
                f'{optics_single.primary.ripple.value.to(unit_ripple).value:0.1f}',
                f'{optics_all.primary.ripple.value.to(unit_ripple).value:0.1f}',
            ])
            tabular.add_row([
                r'',
                f'\quad Periods = ${primary.ripple.periods_min.to(unit_ripple_period).value:0.2f}-{primary.ripple.periods_max.to(unit_ripple_period).value:0.1f}$\\,{unit_ripple_period:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_row([
                r'',
                f'RMS microroughness ({unit_microroughness:latex_inline})',
                f'{optics_single.primary.microroughness.value.to(unit_ripple).value:0.1f}',
                f'{optics_all.primary.microroughness.value.to(unit_ripple).value:0.1f}',
            ])
            tabular.add_row([
                r'',
                f'\quad Periods = ${primary.microroughness.periods_min.to(unit_microroughness_period).value:0.2f}-{primary.microroughness.periods_max.to(unit_microroughness_period).value:0.1f}$\\,{unit_microroughness_period:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_hline()
            tabular.add_row([
                r'Grating',
                f'RMS slope error ({unit_slope_error:latex_inline})',
                f'{optics_single.grating.slope_error.value.to(unit_slope_error).value:0.1f}',
                f'{optics_all.grating.slope_error.value.to(unit_slope_error).value.mean():0.1f}',
            ])
            tabular.add_row([
                r'',
                f'\\quad Integration length = {grating.slope_error.length_integration.to(unit_length_integration).value:0.1f}\,{unit_length_integration:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_row([
                r'',
                f'\\quad Sample length = {grating.slope_error.length_sample.to(unit_length_sample).value:0.1f}\,{unit_length_sample:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_row([
                r'',
                f'RMS roughness ({unit_ripple:latex_inline})',
                f'{optics_single.grating.ripple.value.to(unit_ripple).value:0.1f}',
                f'{optics_all.grating.ripple.value.to(unit_ripple).value.mean():0.1f}',
            ])
            tabular.add_row([
                r'',
                f'\quad Periods = ${grating.ripple.periods_min.to(unit_ripple_period).value:0.2f}-{grating.ripple.periods_max.to(unit_ripple_period).value:0.1f}$\\,{unit_ripple_period:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_row([
                r'',
                f'RMS microroughness ({unit_microroughness:latex_inline})',
                f'{optics_single.grating.microroughness.value.to(unit_ripple).value:0.1f}',
                f'{optics_all.grating.microroughness.value.to(unit_ripple).value.mean():0.1f}',
            ])
            tabular.add_row([
                r'',
                f'\quad Periods = ${grating.microroughness.periods_min.to(unit_microroughness_period).value:0.2f}-{grating.microroughness.periods_max.to(unit_microroughness_period).value:0.1f}$\\,{unit_microroughness_period:latex_inline}',
                r'',
                r'',
            ])
            tabular.add_hline()

    result.add_caption(
        pylatex.NoEscape(r"""
Figure and surface roughness requirements compared to metrology for the \ESIS\ optics.
Slope error (both the numerical estimates and the measurements) is worked out with integration length and sample length 
defined per ISO 10110."""))
    result.append(kgpy.latex.Label('table:error'))
    return result
Ejemplo n.º 17
0
def table(doc: kgpy.latex.Document) -> pylatex.Table:
    result = pylatex.Table()

    optics_single = optics.as_designed_single_channel()
    wavelength = optics_single.bunch.wavelength
    index_o5 = np.nonzero(optics_single.bunch.ion == 'o_5')[0][0]
    wavelength_o5 = wavelength[index_o5]
    index_mg10_2 = np.nonzero(optics_single.bunch.ion == 'mg_10')[0][1]
    wavelength_mg10_2 = wavelength[index_mg10_2]

    intensity_o5 = [334.97, 285.77, 1018.65, 519.534
                    ] * u.erg / u.cm**2 / u.sr / u.s
    intensity_mg10 = [51.43, 2.62, 397.64, 239.249
                      ] * u.erg / u.cm**2 / u.sr / u.s

    energy_o5 = wavelength_o5.to(u.erg, equivalencies=u.spectral()) / u.photon
    energy_mg10 = wavelength_mg10_2.to(u.erg,
                                       equivalencies=u.spectral()) / u.photon

    optics_single_measured = optics.as_measured_single_channel()
    rays = optics_single_measured.rays_output

    area = rays.intensity.copy()
    area[~rays.mask] = np.nan
    area = np.nansum(
        area, (rays.axis.pupil_x, rays.axis.pupil_y, rays.axis.velocity_los),
        keepdims=True)
    area[area == 0] = np.nan
    area = np.nanmean(area, (rays.axis.field_x, rays.axis.field_y)).squeeze()
    area_o5 = area[0]
    area_mg10 = area[2]

    pixel_subtent = (optics_single.plate_scale.x *
                     optics_single.plate_scale.y * u.pix * u.pix).to(u.sr)
    time_integration = optics_single.detector.exposure_length

    counts_o5 = (intensity_o5 * area_o5 * pixel_subtent * time_integration /
                 energy_o5).to(u.photon)
    counts_mg10 = (intensity_mg10 * area_mg10 * pixel_subtent *
                   time_integration / energy_mg10).to(u.photon)
    counts_total = counts_o5 + counts_mg10

    stack_num = 12
    counts_total_stacked = counts_total * stack_num

    noise_shot = np.sqrt(counts_total.value) * counts_total.unit
    noise_shot_stacked = np.sqrt(
        counts_total_stacked.value) * counts_total.unit

    noise_read = optics_single_measured.detector.readout_noise.mean()
    noise_read = noise_read * optics_single_measured.detector.gain.mean()
    noise_read_o5 = (noise_read / (energy_o5 / (3.6 * u.eV / u.electron))).to(
        u.photon)
    noise_read_o5_stacked = stack_num * noise_read_o5

    noise_total = np.sqrt(np.square(noise_shot) + np.square(noise_read_o5))
    noise_total_stacked = np.sqrt(
        np.square(noise_shot_stacked) + np.square(noise_read_o5_stacked))

    snr = counts_total / noise_total
    snr_stacked = counts_total_stacked / noise_total_stacked

    label = f'1 $\\times$ {kgpy.format.quantity(time_integration, digits_after_decimal=0)} exp.'
    label_stacked = f'{stack_num} $\\times$ {kgpy.format.quantity(time_integration, digits_after_decimal=0)} exp.'

    doc.set_variable(
        name='NumExpInStack',
        value=str(stack_num),
    )

    doc.set_variable_quantity(
        name='StackedCoronalHoleSNR',
        value=snr_stacked[np.argmin(intensity_o5)],
        digits_after_decimal=1,
    )

    with result.create(pylatex.Center()) as centering:
        with centering.create(pylatex.Tabular('lrrrr')) as tabular:
            tabular.escape = False
            tabular.add_row([r'Source', r'\VR', r'\VR', r'\VR', r'\CDS'])
            tabular.add_row(r'Solar context', r'\QSShort', r'\CHShort',
                            r'\ARShort', r'\ARShort')
            tabular.add_hline()
            tabular.add_hline()
            tabular.append(f'\\multicolumn{{5}}{{c}}{{{label}}}\\\\')
            tabular.add_row([
                r'\OV',
            ] + [f'{c:0.0f}' for c in counts_o5.value])
            tabular.add_row([
                r'\MgXdim',
            ] + [f'{c:0.0f}' for c in counts_mg10.value])
            tabular.add_hline()
            tabular.add_row([
                r'Total',
            ] + [f'{c:0.0f}' for c in counts_total.value])
            tabular.add_row([
                r'Shot noise',
            ] + [f'{c:0.1f}' for c in noise_shot.value])
            tabular.add_row([
                r'Read noise',
            ] + 4 * [f'{noise_read_o5.value:0.1f}'])
            tabular.add_row([
                r'\SNRShort',
            ] + [f'{c:0.1f}' for c in snr.value])
            tabular.add_hline()
            tabular.add_hline()
            tabular.append(f'\\multicolumn{{5}}{{c}}{{{label_stacked}}}\\\\')
            tabular.add_row([
                'Total',
            ] + [f'{c:0.0f}' for c in counts_total_stacked.value])
            tabular.add_row([
                r'\SNRShort',
            ] + [f'{c:0.1f}' for c in snr_stacked.value])
            tabular.add_hline()
            tabular.add_hline()

    result.add_caption(
        pylatex.NoEscape(r"""
Estimated signal statistics per channel (in photon counts) for \ESIS\ lines in \CH, \QS, and \AR.
Note that the \SNR\ estimates are lower bounds since charge diffusion decreases the shot noise."""
                         ))
    result.append(kgpy.latex.Label('table:counts'))
    return result