コード例 #1
0
    def _convert_clicked(self):
        self.add_log("===BEGIN===")
        try:
            errors = self._validate()

            if len(errors) == 0:
                conv, errors = self._get_conv(errors)

            if len(errors) == 0:
                lines = self._get_lines()
                if lines is None:
                    errors.append("Molecular lines not specified")

            if len(errors) == 0:
                fobj, log = conv.make_file_molecules(lines)

                self._report_conversion(fobj, log)

                if log.flag_ok:
                    fobj.save_as(self.w_out.value)
                    self.add_log("File '{}' generated successfully".format(
                        self.w_out.value))

            else:
                self.add_log_error(
                    "Cannot convert:\n  - " + ("\n  - ".join(errors)), True)

        except Exception as e:
            a99.get_python_logger().exception("Conversion failed")
            self.add_log_error("Conversion failed: {}".format(a99.str_exc(e)),
                               True)

        self.add_log("===END===")
コード例 #2
0
    def _populate(self):
        self._flag_populating = True
        try:
            f = self._f = pyfant.FileVald3()
            f.load(self.w_file.value)

            nr, nc = len(f), 3
            t = self.tableWidget
            a99.reset_table_widget(t, nr, nc)
            t.setHorizontalHeaderLabels(
                ["VALD3 species", "Number of spectral lines", "Atom/Molecule"])

            for i, species in enumerate(f):
                item = QTableWidgetItem(str(species))
                t.setItem(i, 0, item)
                item = QTableWidgetItem(str(len(species)))
                t.setItem(i, 1, item)
                item = QTableWidgetItem("Atom" if species.formula in
                                        pyfant.symbols else "Molecule")
                t.setItem(i, 2, item)

            t.resizeColumnsToContents()

        except Exception as e:
            self._f = None
            self.add_log_error(
                "Error reading contents of file '{}': '{}'".format(
                    self.w_file.value, a99.str_exc(e)), True)
            raise

        else:
            self.clear_log()

        finally:
            self._flag_populating = False
コード例 #3
0
    def _calculate(self):

        flag_fcf = self.checkbox_fcf.isChecked()

        if flag_fcf:
            if self.fcfs is None or len(self.fcfs) == 0:
                self.add_log_error("FCFs not available", True)

        try:

            l_text = []

            self.status("Calculating...")
            molconsts = copy.deepcopy(self.molconsts)
            molconsts.None_to_zero()
            for vl in range(10):
                for v2l in range(10):
                    l_text.extend(
                        a99.format_box("vl, v2l = ({}, {})".format(vl, v2l)))

                    factor = 1.
                    if flag_fcf:
                        try:
                            factor = self.fcfs[(vl, v2l)]
                        except KeyError:
                            l_text.append("Franck-Condon Factor not available")
                            continue

                    rows, header = [], None
                    for J in range(40):
                        mtools = pyfant.kovacs_toolbox(molconsts,
                                                       flag_normalize=True)
                        mtools.populate(vl, v2l, J)

                        if header is None:
                            branches = [key[3] for key in mtools.dict_sj]
                            header = ["J"] + branches + ["Sum"]

                        vv = mtools.dict_sj.values()
                        total = sum([
                            x * factor for x in vv
                            if x != pyfant.NO_LINE_STRENGTH
                        ])
                        rows.append([J + .5] + [
                            "{:.5e}".format(x * factor)
                            if x != pyfant.NO_LINE_STRENGTH else "-"
                            for x in vv
                        ] + ["{:.9g}".format(total)])

                    l_text.append(tabulate.tabulate(rows, header))
                    l_text.append("")

            text = "\n".join(l_text)
            self.textEdit.setPlainText(text)
            self.status("")
        except Exception as E:
            self.add_log_error(a99.str_exc(E), True)
            a99.get_python_logger().exception("Error calculating HLF")
コード例 #4
0
    def _on_run_traprb(self):
        if self._id_system is None:
            return

        row = self._f.get_conn().execute("select * from system where id = ?",
                                         (self._id_system, )).fetchone()

        string = pyfant.molconsts_to_system_str(row, SYSTEMSTYLE)

        n = len(self._data)
        beware = "" if n == 0 else \
            "\n\n**Attention**: {} existing FCF{} for this system will be deleted!".\
                format(n, "" if n == 1 else "s")

        msg = "TRAPRB will be executed to calculate the Franck-Condon factors for system '{}'." \
              "{}\n\nDo you wish to continue?".format(string, beware)

        r = QMessageBox.question(self, "Calculate FCFs", msg,
                                 QMessageBox.Yes | QMessageBox.No,
                                 QMessageBox.Yes if n == 0 else QMessageBox.No)

        if r == QMessageBox.Yes:
            r, form = self._show_traprb_parameters_form(r)

            if r == QDialog.Accepted:
                kwargs = form.get_kwargs()

                mc = pyfant.MolConsts()

                try:
                    mc.populate_all_using_system_row(self._f, row)

                    # TODO maybe intermediate review stage, i.e., allow the user to see the FCFs before inserting

                    traprb = pyfant.run_traprb(mc, None, None, **kwargs)

                    traprb.load_result()
                    output = traprb.result["output"]

                    pyfant.insert_fcfs(self._f,
                                       self._id_system,
                                       output.fcfs,
                                       flag_replace=True)

                    self._populate()

                    n = len(output.fcfs)
                    self.add_log(
                        "{} FCF{} successfully inserted".format(
                            n, "" if n == 1 else "s"), True)
                except Exception as e:
                    self.add_log_error(
                        "Error calculating FCFs: '{}'".format(a99.str_exc(e)),
                        True, e)
コード例 #5
0
 def _calculate(self):
     f = pyfant.FileTRAPRBInput()
     try:
         f.from_molconsts(self.molconsts, maxv=self.spinBox_vmax.value())
     except Exception as e:
         self.add_log_error(
             "Could not generate TRAPRB input: {}".format(a99.str_exc(e)),
             True, e)
     else:
         text = f.dumps()
         self.textEdit.setPlainText(text)
コード例 #6
0
ファイル: fileplezlinelist.py プロジェクト: trevisanj/pyfant
    def _do_load_h(self, h, filename):
        r = 0  # counts rows of file
        ii = 0
        species = None
        flag_break = False

        try:
            while True:
                s = h.readline().strip()
                if len(s) == 0:
                    break

                # linelistCN1214V130710.dat
                #
                # Mol vup vlow JLow branch gf       wavenumber  exc (eV) transition (V=violet, R=red)
                # 0   1   2    3    5      6        7
                #---BEGIN SAMPLE---
                #CN1 11 03 034 +  R1   0.4853E-07  40369.070  1.020 V
                #CN1 11 03 035 +  R1   0.5286E-07  40359.670  1.036 V
                #CN1 11 03 036 +  R1   0.5757E-07  40349.879  1.052 V
                #---END SAMPLE---

                tmp = s.split()
                species = self.molecules[tmp[0]]

                line = PlezMolecularLine()

                line.Jl = None
                line.vl = int(tmp[1])
                line.v2l = int(tmp[2])
                line.J2l = float(tmp[3])
                line.lambda_ = 1 / float(
                    tmp[7]) * 1e8  # we assume the wavenumber is in 1/cm
                line.branch = tmp[5]

                species.lines.append(line)

                r += 1
                ii += 1
                if ii == _PROGRESS_INDICATOR_PERIOD:
                    # a99.get_python_logger().info(
                    #      "Loading '{}': {}".format(filename, a99.format_progress(r, num_lines)))
                    ii = 0

        except Exception as e:
            raise RuntimeError("Error around %d%s row of file '%s': \"%s\"" %
                               (r + 1, a99.ordinal_suffix(r + 1), filename,
                                a99.str_exc(e))) from e
コード例 #7
0
    def _file_changed(self):

        f = None
        try:
            f = self._load_lines()

        except Exception as e:
            self._flines = None
            self._speciess = []
            msg = "Error reading contents of file '{}': '{}'".format(
                self.w_file.value, a99.str_exc(e))
            self.add_log_error(msg, True)
            a99.get_python_logger().exception(msg)

        # Tries to restore iso without much compromise
        self._set_species(self.w_conv.f.obj["species"])
        self.w_conv.f.obj["species"] = self._get_species()

        self.w_file.flag_valid = f is not None
        self.changed.emit()
コード例 #8
0
    def _do_load_h(self, h, filename, num_lines=0):
        r = 0  # counts rows of file
        ii = 0
        try:
            self.lines = []
            while True:
                s = h.readline().strip("\n")
                if len(s) == 0:
                    break
                """
                KuruczMolLineOld1 = namedtuple("KuruczMolLineOld1",
                              ["lambda_", "J2l", "Jl", "state2l", "v2l", "spin2l", "statel", "vl",
                               "spinl", ])

                """

                line = KuruczMolLineOld1(
                    float(s[0:9]),
                    float(s[9:15]),
                    float(s[15:21]),
                    s[22:23],
                    int(s[23:25]),
                    int(s[26:27]),
                    s[28:29],
                    int(s[29:31]),
                    int(s[32:33]),
                )

                self.lines.append(line)
                r += 1
                ii += 1
                if ii == _PROGRESS_INDICATOR_PERIOD:
                    a99.get_python_logger().info("Loading '{}': {}".format(
                        filename, a99.format_progress(r, num_lines)))
                    ii = 0

        except Exception as e:
            raise RuntimeError("Error around %d%s row of file '%s': \"%s\"" %
                               (r + 1, a99.ordinal_suffix(r + 1), filename,
                                a99.str_exc(e))) from e
コード例 #9
0
    def _do_load_h(self, h, filename, num_lines=0):
        r = 0  # counts rows of file
        ii = 0
        try:
            self.lines = []
            while True:
                s = h.readline().strip("\n")
                if len(s) == 0:
                    break

                line = KuruczMolLineOld(
                    float(s[0:10]),
                    float(s[10:15]),
                    float(s[15:20]),
                    int(s[20:22]),
                    int(s[22:24]),
                    s[24:25],
                    int(s[25:27]),
                    s[27:28],
                    int(s[28:29]),
                    s[32:33],
                    int(s[33:35]),
                    s[35:36],
                    int(s[36:37]),
                )

                self.lines.append(line)
                r += 1
                ii += 1
                if ii == _PROGRESS_INDICATOR_PERIOD:
                    a99.get_python_logger().info("Loading '{}': {}".format(
                        filename, a99.format_progress(r, num_lines)))
                    ii = 0

        except Exception as e:
            raise RuntimeError("Error around %d%s row of file '%s': \"%s\"" %
                               (r + 1, a99.ordinal_suffix(r + 1), filename,
                                a99.str_exc(e))) from e
コード例 #10
0
ファイル: __init__.py プロジェクト: trevisanj/pyfant
import a99
import logging

# Tests importing packages robobrowser and bs4, requirements for downloaders
flag_ok = True
try:
    from robobrowser import RoboBrowser
    del RoboBrowser
except ImportError as e:
    flag_ok = False
    logging.warning("failed to import package robobrowser.Robobrowser: '{}', "
                    "f311.filetypes.downloaders will not be available".format(
                        a99.str_exc(e)))

if flag_ok:
    try:
        import bs4
        del bs4
    except ImportError as e:
        flag_ok = False
        logging.warning(
            "failed to import package bs4 (Beautiful Soup 4): '{}', "
            "f311.filetypes.downloaders will not be available".format(
                a99.str_exc(e)))

del a99, logging

if flag_ok:
    from .downhitran import *
    from .downnist import *
コード例 #11
0
    def _do_load_h(self, h, filename, num_lines=0):
        r = 0  # counts rows of file
        ii = 0
        try:
            self.lines = []
            while True:
                s = h.readline().strip("\n")
                if len(s) == 0:
                    break

                # Kurucz: "negative energies are predicted or extrapolated"
                # (http: // kurucz.harvard.edu / linelists.html)
                E2l = float(s[22:32])
                if E2l < 0:
                    E2l = -E2l
                El = float(s[37:48])
                if El < 0:
                    El = -El

                try:
                    spin2l = int(s[57:58])
                except ValueError:
                    spin2l = 0

                try:
                    spinl = int(s[65:66])
                except ValueError:
                    spinl = 0

                line = KuruczMolLine(
                    float(s[0:10]) * 10,
                    float(s[10:17]),
                    float(s[17:22]),
                    E2l,
                    float(s[32:37]),
                    El,
                    int(s[48:50]),
                    int(s[50:52]),
                    s[53:54],
                    int(s[54:56]),
                    s[56:57],
                    spin2l,
                    s[61:62],
                    int(s[62:64]),
                    s[64:65],
                    spinl,
                    int(s[68:70]),
                )

                self.lines.append(line)
                r += 1
                ii += 1
                if ii == _PROGRESS_INDICATOR_PERIOD:
                    a99.get_python_logger().info("Loading '{}': {}".format(
                        filename, a99.format_progress(r, num_lines)))
                    ii = 0

        except Exception as e:
            # f = type(e)(("Error around %d%s row of file '%s'" %
            #              (r + 1, a99.ordinal_suffix(r + 1), filename)) + ": " + str(
            #     e)).with_traceback(sys.exc_info()[2])
            raise RuntimeError("Error around %d%s row of file '%s': \"%s\"" %
                               (r + 1, a99.ordinal_suffix(r + 1), filename,
                                a99.str_exc(e))) from e
コード例 #12
0
ファイル: fileplezlinelist.py プロジェクト: trevisanj/pyfant
    def _do_load_h(self, h, filename):
        r = 0  # counts rows of file
        ii = 0

        expr_branch = re.compile(
            "[PQRS]\d*")  # regular expression to find the branch

        # states
        EXP_SPECIES = 0  # expecting species definition
        EXP_NAME = 1  # expecting name of species
        EXP_ANY = 2

        state = EXP_SPECIES
        is_atom = None
        species = None
        flag_break = False

        try:
            while True:
                s = h.readline().strip()
                if len(s) == 0:
                    flag_break = True

                if not flag_break:
                    if s[0] == "'":
                        if state == EXP_SPECIES or state == EXP_ANY:
                            # New species to come

                            # Determine whether atom or molecule
                            atnumber = int(s[1:s.index(".")])
                            is_atom = atnumber <= 92

                            state = EXP_NAME

                        elif EXP_NAME:
                            name = s.strip("'")
                            species = self.atoms[
                                name] if is_atom else self.molecules[name]

                            a99.get_python_logger().info(
                                "Loading '{}': species '{}'".format(
                                    filename, name))

                            state = EXP_ANY

                    else:
                        if state != EXP_ANY:
                            raise RuntimeError("Not expecting line right now")
                        # It is a line

                        # Read 6 numeric values then something between quotes
                        line = PlezAtomicLine(
                        ) if is_atom else PlezMolecularLine()

                        line.lambda_, line.chiex, line.loggf, line.gu, line.fdamp, line.raddmp = \
                            [float(x) for x in s[:s.index("'")].split()]

                        if not is_atom:
                            # Get the branch

                            tmp = s[s.index("'"):].strip("'").split()
                            _branch = tmp[0]

                            line.branch = expr_branch.search(_branch).group()
                            line.Jl = float(tmp[2])
                            line.vl = int(tmp[1])
                            line.v2l = int(tmp[6])
                            line.J2l = float(tmp[7])

                        species.lines.append(line)

                if flag_break:
                    break

                r += 1
                ii += 1
                if ii == _PROGRESS_INDICATOR_PERIOD:
                    # a99.get_python_logger().info(
                    #      "Loading '{}': {}".format(filename, a99.format_progress(r, num_lines)))
                    ii = 0

        except Exception as e:
            raise RuntimeError("Error around %d%s row of file '%s': \"%s\"" %
                               (r + 1, a99.ordinal_suffix(r + 1), filename,
                                a99.str_exc(e))) from e