コード例 #1
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
    def find_Fin_roots(self, cfins, internal=False):
        """
        Returns the roots of a list of parameterised Fin as a list of python
        complex or mpmath.mpc types. There are additional advanced parameters
        supplied via the Tool yaml file.

        Parameters
        ----------
        cfins : list of cFinMatSympypolyk
            List of parameterised Fin.

        Returns
        -------
        all_roots : list of float or mpmath.mpc
        """
        self.log.write_call(
            "find_Fin_roots(" + str(map(lambda x: x.fitInfo[0], cfins)) + ")",
            internal)

        all_roots = MCSMatFit.RootsList()
        if len(cfins) > 0:
            with th.fropen(self.param_file_path) as f:
                config = yaml.load(f.read())
                p = config["find_Fin_roots"]
                self.log.write_parameters(p)
                self.all_roots_loaded = True
                for cfin in cfins:
                    if all_roots.asymcalc is not None:
                        assert all_roots.asymcalc == cfin.asymcalc
                    all_roots.asymcalc = cfin.asymcalc
                    roots = self._get_roots(p, cfin, all_roots.asymcalc)
                    all_roots.append(roots)
                    all_roots.n_list.append(cfin.fitInfo[0])
        self.log.write_call_end("find_Fin_roots")
        return all_roots
コード例 #2
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
 def _get_line(self, str_real, str_imag, str_Vdk, str_SM, trunc_Vdk,
               sig_digits, col_delim, col_start_delim, has_final_col_delim,
               use_energies):
     strip_zeros, min_fixed, max_fixed, show_zero_exponent, ztol = \
             self._get_table_format_parameters()
     if trunc_Vdk:
         num = int(str_Vdk.split('-')[1])
         if use_energies:
             # 50% chance digit loss when converting from k to E. However,
             # since the Vdk is the higher end of a precision range and that
             # we use the relative diff from cfsteps from the final two Ms
             # by default we ignore this
             with th.fropen(self.param_file_path) as f:
                 config = yaml.load(f.read())
                 p = config["create_formatted_QI_tables"]
                 conv_dps_mod = p["conversion_dps_mod"]
                 num += conv_dps_mod
         if sig_digits is None or num < sig_digits:
             sig_digits = num
     if trunc_Vdk or sig_digits is not None:
         str_real = nw.num_str_real(str_real, sig_digits, strip_zeros,
                                    min_fixed, max_fixed,
                                    show_zero_exponent, ztol)
         str_imag = nw.num_str_real(str_imag, sig_digits, strip_zeros,
                                    min_fixed, max_fixed,
                                    show_zero_exponent, ztol)
     line = self._get_cell(str_real, col_delim, col_start_delim)
     line += self._get_cell(str_imag, col_delim, col_start_delim)
     line += self._get_cell(str_Vdk, col_delim, col_start_delim)
     line += self._get_cell(str_SM, col_delim, col_start_delim,
                            has_final_col_delim)
     return line
コード例 #3
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
 def _load_coeff(self, Npts, path, type_str):
     coeffs = []
     for i in range(psm.get_num_coeff_for_Npts(Npts)):
         coeff_path = self._get_coeff_path(path, type_str, i)
         if not os.path.isfile(coeff_path):
             return None
         try:
             if nw.mode == nw.mode_python:
                 coeff = np.asmatrix(
                     np.loadtxt(coeff_path,
                                dtype=np.complex128,
                                delimiter=","))
                 coeffs.append(coeff)
             else:
                 with th.fropen(coeff_path) as f:
                     s1 = f.read()
                     l1 = s1.split("\n")
                     l2 = [self._split_mp_rows(s) for s in l1]
                     l3 = [
                         map(lambda s: self._fix_mp_mat_str(s), l)
                         for l in l2
                     ]
                     coeff = nw.mpmath.matrix(l3)
                     coeffs.append(coeff)
         except Exception as inst:
             self.log.write_err(str(inst))
             raise
     return coeffs
コード例 #4
0
def get_tool(toolid,
             data,
             archive_root=None,
             param_file_path=None,
             silent=False):
    """
    Initialises and returns a Tool.

    Parameters
    ----------
    toolid : int 
        Specification of the Tool. Available options are reskit.chart and
        reskit.mcsmatfit.
    data
        Tool data. This is the data container to be used by the Tool.
    archive_root : str, optional
        Specification of the location into which reskit will write its results.
    param_file_path : str, optional
        Location of an existing yaml file containing overrides for the more
        advanced routine parameters.
    silent : bool, optional
        Switch determining whether to suppress output to console.

    Returns
    -------
    tool : Tool
    """
    if safe_mode:
        nw.lockType()
    if toolid == chart:
        import chart as mod
        tool = mod.Chart
    elif toolid == mcsmatfit:
        import mcsmatfit as mod
        tool = mod.MCSMatFit
    else:
        raise Exception(reskit_err_str_unrecog_module)
    if archive_root is not None:
        data_root = archive_root + os.sep + data.get_source_str() + os.sep
        data_root += nw.getConfigString() + os.sep + data.get_hist_str(
        ) + os.sep
        archive_root = data_root + mod.toolName + os.sep
        if not os.path.isdir(data_root):
            os.makedirs(data_root)
            with th.fwopen(data_root + filename_checkdata) as f:
                th.fw(f, data.get_check_str())
        else:
            if os.path.isfile(data_root + filename_checkdata):
                with th.fropen(data_root + filename_checkdata) as f:
                    if str(f.read()) != str(data.get_check_str()):
                        raise Exception(reskit_err_str_bad_data_root)
            else:
                s = reskit_err_str_missing_check_data_1 + data_root
                s += reskit_err_str_missing_check_data_2
                raise Exception(s)
        if not os.path.isdir(archive_root):
            os.makedirs(archive_root)

    return tool(data, archive_root, param_file_path, silent)
コード例 #5
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
 def _fix_numpy_file(self, file_name):
     f1 = th.fropen(file_name)
     f2 = th.fwopen(file_name + "_temp")
     for line in f1:
         th.fw(f2, line.replace("+-", '-').replace("\r\n", '\n'))
     f1.close()
     f2.close()
     os.remove(file_name)
     os.rename(file_name + "_temp", file_name)
コード例 #6
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
    def _get_formatted_lines(self,
                             subdir,
                             orig_file_name,
                             use_energies,
                             trunc_Vdk,
                             sig_digits,
                             row_delim=None,
                             row_start_delim=None,
                             col_delim="$$",
                             col_start_delim=None,
                             has_final_col_delim=True):
        desc = ""
        new_lines = []
        file_path = subdir + os.sep + orig_file_name
        with th.fropen(file_path) as f:
            new_line = ""
            for i, l in enumerate(f):
                if i == 0:
                    desc = l.strip()
                elif "=" in l:
                    num_str = l.split('=')[1].strip()
                    if num_str[0] == "+":
                        num_str = num_str[1:]

                    if QI_file_real in l:
                        str_real = num_str
                    elif QI_file_imag in l:
                        str_imag = num_str
                    elif QI_file_Vdk in l:
                        num_str = nw.num_str_real(num_str, 1, True, 1, 1,
                                                  False)
                        str_Vdk = num_str.replace(".0", "")
                    elif QI_file_SM in l:
                        str_SM = num_str

                        # Info for new line complete. Construct it:
                        new_line = ""
                        if row_start_delim is not None:
                            new_line = row_start_delim
                        new_line += self._get_line(str_real, str_imag, str_Vdk,
                                                   str_SM, trunc_Vdk,
                                                   sig_digits, col_delim,
                                                   col_start_delim,
                                                   has_final_col_delim,
                                                   use_energies)
                        if row_delim is not None:
                            new_line += row_delim
                            new_lines.append(new_line)
                        else:
                            new_lines.append(new_line.split("$$"))

        return desc, new_lines
コード例 #7
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
 def _load_roots(self, Npts, ris):
     if self.archive_root is not None:
         root_path = self._find_compatible_root_dir(Npts, ris)
         if root_path is not None:
             try:
                 with th.fropen(root_path) as f:
                     fndStart = False
                     roots = []
                     for l in f:
                         if not fndStart:
                             if "---" in l:
                                 fndStart = True
                             continue
                         elif "complete" not in l:
                             roots.append(nw.complex(l.split()[0]))
                     if "complete" not in l:
                         self.log.write_err("Incomplete root file")
                         return None
                     self.log.write_msg("Roots loaded from: " + root_path)
                     return roots
             except Exception as inst:
                 self.log.write_err(str(inst))
                 raise
     return None
コード例 #8
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
    def find_stable_Smat_poles(self, cfins_or_roots):
        """
        Finds the S-matrix poles by identifying stable roots. The input can be
        either a list of roots or the Fin themselves. There are additional
        advanced parameters supplied via the Tool yaml file.

        Parameters
        ----------
        cfins_or_roots : list of either cFinMatSympypolyk or list of floats
            As returned from either get_elastic_Fins or find_Fin_roots.

        Returns
        -------
        pole_dat : list of lists.
            List of poles and their calculated quality indicators.
        amalg_pole_dat : list of lists.
            List of poles that had been combined according to the amalgamation
            threshold specified in the paramFile.
        """
        try:
            param_str = str(map(lambda x: x.fitInfo[0], cfins_or_roots))
        except AttributeError:
            param_str = str(cfins_or_roots.n_list)

        self.log.write_call("find_stable_Smat_poles(" + param_str + ")")
        if len(cfins_or_roots) > 0:
            try:
                cfins_or_roots.n_list  # Test for the parameter type.
                all_roots = cfins_or_roots
            except AttributeError:
                all_roots = self.find_Fin_roots(cfins_or_roots, True)
            if len(all_roots) > 0:
                with th.fropen(self.param_file_path) as f:
                    config = yaml.load(f.read())
                    p = config["find_stable_Smat_poles"]
                    self.log.write_parameters(p)
                    if "root_filt" in p:
                        pp = p["root_filt"]
                        all_roots = self._filterRoots(all_roots,
                                                      nw.complex(pp["point"]),
                                                      nw.complex(pp["atol"]))
                    pp = p["stelempy"]
                    # Default to precision limit of input data:
                    end_rtol = pow(10, -nw.dps)
                    try:
                        end_rtol = float(pp["end_rtol"])
                    except TypeError:
                        pass

                    ztol = float(pp["ztol"])
                    ratcmp = sp.num.RationalCompare1(ztol=ztol)
                    poleData = sp.calculate_convergence_groups_range(
                        all_roots, ratcmp, float(pp["start_rtol"]), end_rtol,
                        int(pp["cfsteps"]))
                    self.log.write_msg("Convergence groups calculated")
                    self._save_pole_data(all_roots.n_list, poleData,
                                         all_roots.asymcalc, p)

                    amalg_ratcmp = None
                    amalg_rtol = float(pp["amalg_rtol"])
                    if amalg_rtol != 0.:
                        amalg_ratcmp = sp.num.RationalCompare1(
                            amalg_rtol, ztol)
                    pole_dat = sp.calculate_QIs_from_range(
                        poleData, amalg_ratcmp)
                    self.log.write_msg("QIs calculated")
                    self._save_QI_data(all_roots.n_list, pole_dat,
                                       all_roots.asymcalc)
                    self.log.write_call_end("find_stable_Smat_poles")
                    return pole_dat
        self.log.write_call_end("find_stable_Smat_poles")
        return None, None
コード例 #9
0
ファイル: __init__.py プロジェクト: petersbingham/reskit
 def _get_table_format_parameters(self):
     with th.fropen(self.param_file_path) as f:
         config = yaml.load(f.read())
         p = config["create_formatted_QI_tables"]["num_format"]
         return p["strip_zeros"], p["min_fixed"], p["max_fixed"], \
                p["show_zero_exponent"], float(p["ztol"])