Search in sources :

Example 1 with MoleculeDataModel

use of de.unijena.cheminf.mortar.model.data.MoleculeDataModel in project MORTAR by FelixBaensch.

the class MainViewController method importMoleculeFile.

// 
/**
 * Loads molecule file and opens molecules tab
 *
 * @param aParentStage Stage
 */
private void importMoleculeFile(Stage aParentStage) {
    if (this.moleculeDataModelList.size() > 0) {
        if (!this.isFragmentationStopAndDataLossConfirmed()) {
            return;
        }
    }
    Importer tmpImporter = new Importer(this.settingsContainer);
    File tmpFile = tmpImporter.loadFile(aParentStage);
    if (Objects.isNull(tmpFile)) {
        return;
    }
    if (this.isFragmentationRunning) {
        this.interruptFragmentation();
    }
    if (this.isImportRunningProperty.get()) {
        this.interruptImport();
    }
    if (this.isExportRunningProperty.get()) {
        this.interruptExport();
    }
    this.clearGuiAndCollections();
    this.importTask = new Task<>() {

        @Override
        protected IAtomContainerSet call() throws Exception {
            IAtomContainerSet tmpSet = tmpImporter.importMoleculeFile(tmpFile);
            return tmpSet;
        }
    };
    this.importTask.setOnSucceeded(event -> {
        // note: setOnSucceeded() takes place in the JavaFX GUI thread again but still runLater() is necessary to wait
        // for the thread to be free for the update
        Platform.runLater(() -> {
            IAtomContainerSet tmpAtomContainerSet = null;
            try {
                tmpAtomContainerSet = importTask.get();
            } catch (InterruptedException | ExecutionException anException) {
                MainViewController.LOGGER.log(Level.SEVERE, anException.toString(), anException);
                GuiUtil.guiExceptionAlert(Message.get("Error.ExceptionAlert.Title"), Message.get("Importer.FileImportExceptionAlert.Header"), Message.get("Importer.FileImportExceptionAlert.Text") + "\n" + FileUtil.getAppDirPath() + File.separator + BasicDefinitions.LOG_FILES_DIRECTORY + File.separator, anException);
                this.updateStatusBar(this.importerThread, Message.get("Status.importFailed"));
            }
            if (tmpAtomContainerSet == null || tmpAtomContainerSet.isEmpty()) {
                return;
            }
            this.mainView.getMainMenuBar().getExportMenu().setDisable(true);
            this.primaryStage.setTitle(Message.get("Title.text") + " - " + tmpImporter.getFileName() + " - " + tmpAtomContainerSet.getAtomContainerCount() + " molecules");
            int tmpExceptionCount = 0;
            for (IAtomContainer tmpAtomContainer : tmpAtomContainerSet.atomContainers()) {
                // returns null if no SMILES code could be created
                String tmpSmiles = ChemUtil.createUniqueSmiles(tmpAtomContainer);
                if (tmpSmiles == null) {
                    tmpExceptionCount++;
                    continue;
                }
                MoleculeDataModel tmpMoleculeDataModel;
                if (this.settingsContainer.getKeepAtomContainerInDataModelSetting()) {
                    tmpMoleculeDataModel = new MoleculeDataModel(tmpAtomContainer);
                } else {
                    tmpMoleculeDataModel = new MoleculeDataModel(tmpSmiles, tmpAtomContainer.getTitle(), tmpAtomContainer.getProperties());
                }
                tmpMoleculeDataModel.setName(tmpAtomContainer.getProperty(Importer.MOLECULE_NAME_PROPERTY_KEY));
                this.moleculeDataModelList.add(tmpMoleculeDataModel);
            }
            MainViewController.LOGGER.log(Level.INFO, "Imported " + tmpAtomContainerSet.getAtomContainerCount() + " molecules from file: " + tmpImporter.getFileName() + " " + tmpExceptionCount + " molecules could not be parsed into the internal data model.");
            this.updateStatusBar(this.importerThread, Message.get("Status.loaded"));
            this.isImportRunningProperty.setValue(false);
            this.openMoleculesTab();
        });
    });
    this.importTask.setOnCancelled(event -> {
        this.updateStatusBar(this.importerThread, Message.get("Status.canceled"));
        this.isImportRunningProperty.setValue(false);
    });
    this.importTask.setOnFailed(event -> {
        this.updateStatusBar(this.importerThread, Message.get("Status.importFailed"));
        this.isImportRunningProperty.setValue(false);
        LogUtil.getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), event.getSource().getException());
    });
    this.importerThread = new Thread(importTask);
    this.importerThread.setName(ThreadType.IMPORT_THREAD.getThreadName());
    this.importerThread.setUncaughtExceptionHandler(LogUtil.getUncaughtExceptionHandler());
    this.importerThread.setDaemon(false);
    // magic number
    this.importerThread.setPriority(Thread.currentThread().getPriority() - 2);
    this.isImportRunningProperty.setValue(true);
    this.updateStatusBar(this.importerThread, Message.get("Status.loading"));
    this.importerThread.start();
}
Also used : IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) ExecutionException(java.util.concurrent.ExecutionException) IAtomContainerSet(org.openscience.cdk.interfaces.IAtomContainerSet) MoleculeDataModel(de.unijena.cheminf.mortar.model.data.MoleculeDataModel) ExecutionException(java.util.concurrent.ExecutionException) File(java.io.File) Importer(de.unijena.cheminf.mortar.model.io.Importer)

Example 2 with MoleculeDataModel

use of de.unijena.cheminf.mortar.model.data.MoleculeDataModel in project MORTAR by FelixBaensch.

the class MainViewController method addFragmentationResultTabs.

// 
/**
 * Adds a tab for fragments and a tab for items (results of fragmentation)
 *
 * @param aFragmentationName
 */
private void addFragmentationResultTabs(String aFragmentationName) {
    // fragments tab
    FragmentsDataTableView tmpFragmentsDataTableView = new FragmentsDataTableView();
    GridTabForTableView tmpFragmentsTab = new GridTabForTableView(Message.get("MainTabPane.fragmentsTab.title") + " - " + aFragmentationName, TabNames.Fragments.name(), tmpFragmentsDataTableView);
    this.mainTabPane.getTabs().add(tmpFragmentsTab);
    ObservableList<MoleculeDataModel> tmpList = FXCollections.observableArrayList(this.mapOfFragmentDataModelLists.get(aFragmentationName));
    tmpFragmentsDataTableView.setItemsList(tmpList);
    int tmpRowsPerPage = this.settingsContainer.getRowsPerPageSetting();
    int tmpPageCount = tmpList.size() / tmpRowsPerPage;
    if (tmpList.size() % tmpRowsPerPage > 0) {
        tmpPageCount++;
    }
    Pagination tmpPagination = new Pagination(tmpPageCount, 0);
    tmpPagination.setPageFactory((pageIndex) -> tmpFragmentsDataTableView.createFragmentsTableViewPage(pageIndex, this.settingsContainer));
    VBox.setVgrow(tmpPagination, Priority.ALWAYS);
    HBox.setHgrow(tmpPagination, Priority.ALWAYS);
    tmpFragmentsTab.addPaginationToGridPane(tmpPagination, 0, 0, 2, 2);
    Button tmpExportCsvButton = new Button(Message.get("MainTabPane.fragments.buttonCSV.txt"));
    tmpExportCsvButton.setTooltip(new Tooltip(Message.get("MainTabPane.fragments.buttonCSV.tooltip")));
    Button tmpExportPdfButton = new Button(Message.get("MainTabPane.fragments.buttonPDF.txt"));
    tmpExportPdfButton.setTooltip(new Tooltip(Message.get("MainTabPane.fragments.buttonPDF.tooltip")));
    Button tmpCancelExportButton = new Button(Message.get("MainTabPane.fragments.buttonCancelExport.txt"));
    tmpCancelExportButton.setTooltip(new Tooltip(Message.get("MainTabPane.fragments.buttonCancelExport.tooltip")));
    tmpCancelExportButton.visibleProperty().bind(this.isExportRunningProperty);
    ButtonBar tmpButtonBarFragments = new ButtonBar();
    tmpButtonBarFragments.setPadding(new Insets(0, 0, 0, 0));
    tmpExportCsvButton.setPrefWidth(GuiDefinitions.GUI_BUTTON_WIDTH_VALUE);
    tmpExportCsvButton.setPrefHeight(GuiDefinitions.GUI_BUTTON_HEIGHT_VALUE);
    tmpExportPdfButton.setPrefWidth(GuiDefinitions.GUI_BUTTON_WIDTH_VALUE);
    tmpExportPdfButton.setPrefHeight(GuiDefinitions.GUI_BUTTON_HEIGHT_VALUE);
    tmpCancelExportButton.setPrefWidth(GuiDefinitions.GUI_BUTTON_WIDTH_VALUE);
    tmpCancelExportButton.setPrefHeight(GuiDefinitions.GUI_BUTTON_HEIGHT_VALUE);
    tmpButtonBarFragments.getButtons().addAll(tmpExportCsvButton, tmpExportPdfButton, tmpCancelExportButton);
    tmpFragmentsTab.addNodeToGridPane(tmpButtonBarFragments, 0, 1, 1, 1);
    tmpExportPdfButton.setOnAction(event -> this.exportFile(Exporter.ExportTypes.FRAGMENT_PDF_FILE));
    tmpExportCsvButton.setOnAction(event -> this.exportFile(Exporter.ExportTypes.FRAGMENT_CSV_FILE));
    tmpCancelExportButton.setOnAction(event -> this.interruptExport());
    tmpFragmentsDataTableView.setOnSort((EventHandler<SortEvent<TableView>>) event -> {
        GuiUtil.sortTableViewGlobally(event, tmpPagination, tmpRowsPerPage);
    });
    tmpFragmentsDataTableView.addTableViewHeightListener(this.settingsContainer);
    tmpFragmentsDataTableView.getCopyMenuItem().setOnAction(event -> GuiUtil.copySelectedTableViewCellsToClipboard(tmpFragmentsDataTableView));
    tmpFragmentsDataTableView.setOnKeyPressed(event -> {
        if (GuiDefinitions.KEY_CODE_COPY.match(event)) {
            GuiUtil.copySelectedTableViewCellsToClipboard(tmpFragmentsDataTableView);
        }
    });
    // itemization tab
    // tmpAmount is the number of fragments appearing in the molecule with the highest number of fragments
    int tmpAmount = 0;
    for (int i = 0; i < this.moleculeDataModelList.size(); i++) {
        if (!this.moleculeDataModelList.get(i).hasMoleculeUndergoneSpecificFragmentation(aFragmentationName)) {
            continue;
        }
        HashMap<String, Integer> tmpCurrentFragmentsMap = this.moleculeDataModelList.get(i).getFragmentFrequencyOfSpecificAlgorithm(aFragmentationName);
        if (tmpCurrentFragmentsMap == null) {
            // redundant, see if clause above
            continue;
        }
        int tmpNrOfFragmentsOfCurrentMolecule = tmpCurrentFragmentsMap.size();
        tmpAmount = Math.max(tmpAmount, tmpNrOfFragmentsOfCurrentMolecule);
    }
    ItemizationDataTableView tmpItemizationDataTableView = new ItemizationDataTableView(tmpAmount, aFragmentationName);
    tmpItemizationDataTableView.setItemsList(this.moleculeDataModelList);
    GridTabForTableView tmpItemizationTab = new GridTabForTableView(Message.get("MainTabPane.itemizationTab.title") + " - " + aFragmentationName, TabNames.Itemization.name(), tmpItemizationDataTableView);
    this.mainTabPane.getTabs().add(tmpItemizationTab);
    tmpPageCount = this.moleculeDataModelList.size() / tmpRowsPerPage;
    if (this.moleculeDataModelList.size() % tmpRowsPerPage > 0) {
        tmpPageCount++;
    }
    Pagination tmpPaginationItems = new Pagination(tmpPageCount, 0);
    tmpPaginationItems.setPageFactory((pageIndex) -> tmpItemizationDataTableView.createItemizationTableViewPage(pageIndex, this.settingsContainer));
    VBox.setVgrow(tmpPaginationItems, Priority.ALWAYS);
    HBox.setHgrow(tmpPaginationItems, Priority.ALWAYS);
    tmpItemizationTab.addPaginationToGridPane(tmpPaginationItems, 0, 0, 2, 2);
    Button tmpItemizationTabExportPDfButton = new Button(Message.get("MainTabPane.itemizationTab.pdfButton.txt"));
    tmpItemizationTabExportPDfButton.setTooltip(new Tooltip(Message.get("MainTabPane.itemizationTab.pdfButton.tooltip")));
    Button tmpItemizationExportCsvButton = new Button(Message.get("MainTabPane.itemizationTab.csvButton.txt"));
    tmpItemizationExportCsvButton.setTooltip(new Tooltip(Message.get("MainTabPane.itemizationTab.csvButton.tooltip")));
    ButtonBar tmpButtonBarItemization = new ButtonBar();
    tmpButtonBarItemization.setPadding(new Insets(0, 0, 0, 0));
    tmpItemizationExportCsvButton.setPrefWidth(GuiDefinitions.GUI_BUTTON_WIDTH_VALUE);
    tmpItemizationExportCsvButton.setPrefHeight(GuiDefinitions.GUI_BUTTON_HEIGHT_VALUE);
    tmpItemizationTabExportPDfButton.setPrefWidth(GuiDefinitions.GUI_BUTTON_WIDTH_VALUE);
    tmpItemizationTabExportPDfButton.setPrefHeight(GuiDefinitions.GUI_BUTTON_HEIGHT_VALUE);
    tmpButtonBarItemization.getButtons().addAll(tmpItemizationExportCsvButton, tmpItemizationTabExportPDfButton, tmpCancelExportButton);
    tmpItemizationTab.addNodeToGridPane(tmpButtonBarItemization, 0, 1, 1, 1);
    tmpItemizationExportCsvButton.setOnAction(event -> this.exportFile(Exporter.ExportTypes.ITEM_CSV_FILE));
    tmpItemizationTabExportPDfButton.setOnAction(event -> this.exportFile(Exporter.ExportTypes.ITEM_PDF_FILE));
    tmpItemizationDataTableView.setOnSort((EventHandler<SortEvent<TableView>>) event -> {
        GuiUtil.sortTableViewGlobally(event, tmpPaginationItems, tmpRowsPerPage);
    });
    tmpItemizationDataTableView.addTableViewHeightListener(this.settingsContainer);
    tmpItemizationDataTableView.getCopyMenuItem().setOnAction(event -> GuiUtil.copySelectedTableViewCellsToClipboard(tmpItemizationDataTableView));
    tmpItemizationDataTableView.setOnKeyPressed(event -> {
        if (GuiDefinitions.KEY_CODE_COPY.match(event)) {
            GuiUtil.copySelectedTableViewCellsToClipboard(tmpItemizationDataTableView);
        }
    });
    // 
    this.mainTabPane.getSelectionModel().select(tmpFragmentsTab);
}
Also used : EventHandler(javafx.event.EventHandler) Button(javafx.scene.control.Button) MainView(de.unijena.cheminf.mortar.gui.views.MainView) SettingsContainer(de.unijena.cheminf.mortar.model.settings.SettingsContainer) VBox(javafx.scene.layout.VBox) FragmentsDataTableView(de.unijena.cheminf.mortar.gui.views.FragmentsDataTableView) Task(javafx.concurrent.Task) IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) TabPane(javafx.scene.control.TabPane) BasicDefinitions(de.unijena.cheminf.mortar.model.util.BasicDefinitions) WindowEvent(javafx.stage.WindowEvent) Message(de.unijena.cheminf.mortar.message.Message) TableView(javafx.scene.control.TableView) Alert(javafx.scene.control.Alert) HBox(javafx.scene.layout.HBox) ButtonBar(javafx.scene.control.ButtonBar) Set(java.util.Set) KeyEvent(javafx.scene.input.KeyEvent) Observable(javafx.beans.Observable) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Importer(de.unijena.cheminf.mortar.model.io.Importer) MoleculesDataTableView(de.unijena.cheminf.mortar.gui.views.MoleculesDataTableView) Platform(javafx.application.Platform) IAtomContainerSet(org.openscience.cdk.interfaces.IAtomContainerSet) Objects(java.util.Objects) Priority(javafx.scene.layout.Priority) BooleanProperty(javafx.beans.property.BooleanProperty) List(java.util.List) FragmentationService(de.unijena.cheminf.mortar.model.fragmentation.FragmentationService) ObservableList(javafx.collections.ObservableList) FileUtil(de.unijena.cheminf.mortar.model.util.FileUtil) Pagination(javafx.scene.control.Pagination) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Scene(javafx.scene.Scene) MoleculeDataModel(de.unijena.cheminf.mortar.model.data.MoleculeDataModel) RadioMenuItem(javafx.scene.control.RadioMenuItem) FragmentDataModel(de.unijena.cheminf.mortar.model.data.FragmentDataModel) ItemizationDataTableView(de.unijena.cheminf.mortar.gui.views.ItemizationDataTableView) ButtonType(javafx.scene.control.ButtonType) FXCollections(javafx.collections.FXCollections) HashMap(java.util.HashMap) IDataTableView(de.unijena.cheminf.mortar.gui.views.IDataTableView) Level(java.util.logging.Level) GridTabForTableView(de.unijena.cheminf.mortar.gui.panes.GridTabForTableView) Insets(javafx.geometry.Insets) ChemFileTypes(de.unijena.cheminf.mortar.model.io.ChemFileTypes) Tooltip(javafx.scene.control.Tooltip) ChemUtil(de.unijena.cheminf.mortar.model.util.ChemUtil) KeyCode(javafx.scene.input.KeyCode) GuiUtil(de.unijena.cheminf.mortar.gui.util.GuiUtil) Label(javafx.scene.control.Label) GuiDefinitions(de.unijena.cheminf.mortar.gui.util.GuiDefinitions) LogUtil(de.unijena.cheminf.mortar.model.util.LogUtil) File(java.io.File) EventType(javafx.event.EventType) ExecutionException(java.util.concurrent.ExecutionException) ToggleGroup(javafx.scene.control.ToggleGroup) SimpleBooleanProperty(javafx.beans.property.SimpleBooleanProperty) SortEvent(javafx.scene.control.SortEvent) Stage(javafx.stage.Stage) Tab(javafx.scene.control.Tab) IMoleculeFragmenter(de.unijena.cheminf.mortar.model.fragmentation.algorithm.IMoleculeFragmenter) Image(javafx.scene.image.Image) Exporter(de.unijena.cheminf.mortar.model.io.Exporter) InputStream(java.io.InputStream) ButtonBar(javafx.scene.control.ButtonBar) Insets(javafx.geometry.Insets) Tooltip(javafx.scene.control.Tooltip) FragmentsDataTableView(de.unijena.cheminf.mortar.gui.views.FragmentsDataTableView) Pagination(javafx.scene.control.Pagination) SortEvent(javafx.scene.control.SortEvent) GridTabForTableView(de.unijena.cheminf.mortar.gui.panes.GridTabForTableView) Button(javafx.scene.control.Button) MoleculeDataModel(de.unijena.cheminf.mortar.model.data.MoleculeDataModel) ItemizationDataTableView(de.unijena.cheminf.mortar.gui.views.ItemizationDataTableView)

Example 3 with MoleculeDataModel

use of de.unijena.cheminf.mortar.model.data.MoleculeDataModel in project MORTAR by FelixBaensch.

the class GuiUtil method setImageStructureHeight.

// 
/**
 * Sets the height for structure images to each MoleculeDataModel object of the items list of the tableView.
 * If image height is too small it will be set to GuiDefinitions.GUI_STRUCTURE_IMAGE_MIN_HEIGHT (50.0)
 *
 * @param aTableView TableView
 * @param aHeight double
 * @param aSettingsContainer SettingsContainer
 */
public static void setImageStructureHeight(TableView aTableView, double aHeight, SettingsContainer aSettingsContainer) {
    double tmpHeight = (aHeight - GuiDefinitions.GUI_TABLE_VIEW_HEADER_HEIGHT - GuiDefinitions.GUI_PAGINATION_CONTROL_PANEL_HEIGHT) / aSettingsContainer.getRowsPerPageSetting();
    if (aTableView.getClass().equals(ItemizationDataTableView.class)) {
        tmpHeight = (aHeight - 2 * GuiDefinitions.GUI_TABLE_VIEW_HEADER_HEIGHT - GuiDefinitions.GUI_PAGINATION_CONTROL_PANEL_HEIGHT) / aSettingsContainer.getRowsPerPageSetting();
    }
    if (tmpHeight < GuiDefinitions.GUI_STRUCTURE_IMAGE_MIN_HEIGHT) {
        tmpHeight = GuiDefinitions.GUI_STRUCTURE_IMAGE_MIN_HEIGHT;
    }
    if (aTableView.getClass().equals(ItemizationDataTableView.class)) {
        for (MoleculeDataModel tmpMoleculeDataModel : ((IDataTableView) aTableView).getItemsList()) {
            tmpMoleculeDataModel.setStructureImageHeight(tmpHeight);
            String tmpFragmentationName = ((ItemizationDataTableView) aTableView).getFragmentationName();
            if (!tmpMoleculeDataModel.hasMoleculeUndergoneSpecificFragmentation(tmpFragmentationName)) {
                continue;
            }
            for (FragmentDataModel tmpFragmentDataModel : tmpMoleculeDataModel.getFragmentsOfSpecificAlgorithm(tmpFragmentationName)) {
                tmpFragmentDataModel.setStructureImageHeight(tmpHeight);
            }
        }
    } else {
        for (MoleculeDataModel tmpMoleculeDataModel : ((IDataTableView) aTableView).getItemsList()) {
            tmpMoleculeDataModel.setStructureImageHeight(tmpHeight);
        }
    }
}
Also used : FragmentDataModel(de.unijena.cheminf.mortar.model.data.FragmentDataModel) MoleculeDataModel(de.unijena.cheminf.mortar.model.data.MoleculeDataModel) ItemizationDataTableView(de.unijena.cheminf.mortar.gui.views.ItemizationDataTableView) IDataTableView(de.unijena.cheminf.mortar.gui.views.IDataTableView)

Example 4 with MoleculeDataModel

use of de.unijena.cheminf.mortar.model.data.MoleculeDataModel in project MORTAR by FelixBaensch.

the class Exporter method createFragmentationTabPDBFiles.

// 
/**
 * Opens a directory chooser and exports the chemical data of the given fragments as PDB files to an empty folder
 * generated at the chosen path. The molecular formula of each fragment is used as name for the associated file. In
 * case no 3D information are being held in a fragment atom container, the respective PDB files are created using 2D
 * information equally setting each z coordinate to 0. If no 2D information are available, it can be chosen to
 * either generate (pseudo-) 2D atom coordinates (originally intended for layout
 * purposes) or to export without specifying the atom coordinates (x, y, z = 0) via the last parameter.
 *
 * @param aDirectory             directory to save fragments
 * @param aFragmentDataModelList list of FragmentDataModel instances
 * @param generate2DCoordinates  boolean value whether to generate 2D coordinates
 * @author Samuel Behr
 */
private List<String> createFragmentationTabPDBFiles(File aDirectory, List<MoleculeDataModel> aFragmentDataModelList, boolean generate2DCoordinates) {
    if (aFragmentDataModelList == null) {
        return null;
    }
    try {
        if (aDirectory != null && aDirectory.isDirectory()) {
            List<String> tmpFailedExportFragments = new LinkedList<>();
            String tmpPDBFilesDirectoryPathName = aDirectory + File.separator + FRAGMENTS_EXPORT_DIRECTORY_NAME + "_" + FileUtil.getTimeStampFileNameExtension();
            String tmpFinalPDBFilesDirectoryPathName = FileUtil.getNonExistingFilePath(tmpPDBFilesDirectoryPathName, File.separator);
            File tmpPDBFilesDirectory = Files.createDirectory(Paths.get(tmpFinalPDBFilesDirectoryPathName)).toFile();
            int tmpExportedFragmentsCounter = 0;
            int tmpFailedFragmentExportCounter = 0;
            // iterating through the fragments held by the list of fragments
            for (MoleculeDataModel tmpFragmentDataModel : aFragmentDataModelList) {
                if (Thread.currentThread().isInterrupted()) {
                    return null;
                }
                IAtomContainer tmpFragment;
                try {
                    tmpFragment = tmpFragmentDataModel.getAtomContainer();
                } catch (CDKException anException) {
                    Exporter.LOGGER.log(Level.SEVERE, anException.toString() + "_" + tmpFragmentDataModel.getName(), anException);
                    tmpFailedExportFragments.add(tmpFragmentDataModel.getUniqueSmiles());
                    tmpFailedFragmentExportCounter++;
                    continue;
                }
                IAtomContainer tmpFragmentClone = null;
                boolean tmpPoint3dAvailable = ChemUtil.has3DCoordinates(tmpFragmentDataModel);
                boolean tmpPoint2dAvailable = ChemUtil.has2DCoordinates(tmpFragmentDataModel);
                // checking whether 3D information are available
                if (!tmpPoint3dAvailable) {
                    tmpFragmentClone = this.handleFragmentWithNo3dInformationAvailable(tmpFragment, tmpPoint2dAvailable, generate2DCoordinates);
                }
                // generating file
                String tmpMolecularFormula = ChemUtil.generateMolecularFormula(tmpFragment);
                String tmpPDBFilePathName = FileUtil.getNonExistingFilePath(tmpPDBFilesDirectory + File.separator + tmpMolecularFormula, ".pdb");
                File tmpPDBFile = new File(tmpPDBFilePathName);
                // writing to file
                try (PDBWriter tmpPDBWriter = new PDBWriter(new FileOutputStream(tmpPDBFile))) {
                    if (tmpPoint3dAvailable) {
                        tmpPDBWriter.writeMolecule(tmpFragment);
                    } else {
                        tmpPDBWriter.writeMolecule(tmpFragmentClone);
                    }
                    tmpExportedFragmentsCounter++;
                } catch (CDKException anException) {
                    Exporter.LOGGER.log(Level.SEVERE, anException.toString(), anException);
                    tmpFailedExportFragments.add(tmpFragmentDataModel.getUniqueSmiles());
                    tmpFailedFragmentExportCounter++;
                }
            }
            Exporter.LOGGER.log(Level.INFO, String.format("Exported %d fragments as PDB files " + "(export of %d fragments failed). Folder name: %s", tmpExportedFragmentsCounter, tmpFailedFragmentExportCounter, tmpPDBFilesDirectory.getName()));
            return tmpFailedExportFragments;
        }
    } catch (NullPointerException | IOException | IllegalArgumentException anException) {
        Exporter.LOGGER.log(Level.SEVERE, anException.toString(), anException);
        return null;
    }
    return null;
}
Also used : IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) CDKException(org.openscience.cdk.exception.CDKException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) FileOutputStream(java.io.FileOutputStream) PDBWriter(org.openscience.cdk.io.PDBWriter) MoleculeDataModel(de.unijena.cheminf.mortar.model.data.MoleculeDataModel) File(java.io.File)

Example 5 with MoleculeDataModel

use of de.unijena.cheminf.mortar.model.data.MoleculeDataModel in project MORTAR by FelixBaensch.

the class Exporter method createFragmentationTabPdfFile.

// 
/**
 * Exports the fragmentation results as they are displayed on the fragments tab as a PDF file. Opens a file chooser
 * dialog for the user to determine a directory and file for the exported data.
 *
 * @param aFragmentDataModelList a list of FragmentDataModel instances to export
 * @param aMoleculeDataModelList a list MoleculeDataModel needed for the fragmentation report at the head of the exported document
 * @param aFragmentationName     fragmentation name to be displayed in the header of the PDF file
 * @return PDF file which contains the results of the fragmentation
 * @throws FileNotFoundException
 * @throws DocumentException
 * @author Betül Sevindik
 */
private List<String> createFragmentationTabPdfFile(File aPdfFile, List<MoleculeDataModel> aFragmentDataModelList, ObservableList<MoleculeDataModel> aMoleculeDataModelList, String aFragmentationName) throws FileNotFoundException, DocumentException {
    if (aPdfFile == null || aFragmentDataModelList == null || aMoleculeDataModelList == null || aFragmentationName == null) {
        return null;
    }
    List<String> tmpFailedExportFragments = new LinkedList<>();
    this.document = new Document(PageSize.A4);
    this.document.setPageSize(this.document.getPageSize().rotate());
    PdfWriter.getInstance(this.document, new FileOutputStream(aPdfFile.getPath()));
    this.document.open();
    // relative sizes
    float[] tmpCellLength = { 70f, 120f, 50f, 50f, 55f, 55f };
    PdfPTable tmpFragmentationTable = new PdfPTable(tmpCellLength);
    PdfPCell tmpSmilesStringCell = new PdfPCell(new Paragraph(Message.get("Exporter.fragmentationTab.pdfCellHeader.smiles"), fontFactory));
    PdfPCell tmpFrequencyCell = new PdfPCell(new Paragraph(Message.get("Exporter.fragmentationTab.pdfCellHeader.frequency"), this.fontFactory));
    PdfPCell tmpPercentageCell = new PdfPCell(new Paragraph(Message.get("Exporter.fragmentationTab.pdfCellHeader.percentage"), this.fontFactory));
    PdfPCell tmpMolFrequencyCell = new PdfPCell(new Paragraph(Message.get("Exporter.fragmentationTab.pdfCellHeader.moleculeFrequency"), this.fontFactory));
    PdfPCell tmpMolPercentageCell = new PdfPCell(new Paragraph(Message.get("Exporter.fragmentationTab.pdfCellHeader.moleculePercentage"), this.fontFactory));
    PdfPCell tmpFragmentCell = new PdfPCell(new Paragraph(Message.get("Exporter.fragmentationTab.pdfCellHeader.fragment"), this.fontFactory));
    Chunk tmpHeader = new Chunk(Message.get("Exporter.fragmentationTab.pdfCellHeader.header"), FontFactory.getFont(FontFactory.TIMES_ROMAN, 18, Font.UNDERLINE));
    Paragraph tmpSpace = new Paragraph(" ");
    tmpFragmentationTable.addCell(tmpFragmentCell);
    tmpFragmentationTable.addCell(tmpSmilesStringCell);
    tmpFragmentationTable.addCell(tmpFrequencyCell);
    tmpFragmentationTable.addCell(tmpPercentageCell);
    tmpFragmentationTable.addCell(tmpMolFrequencyCell);
    tmpFragmentationTable.addCell(tmpMolPercentageCell);
    for (MoleculeDataModel tmpModel : aFragmentDataModelList) {
        if (Thread.currentThread().isInterrupted()) {
            return null;
        }
        FragmentDataModel tmpFragmentDataModel = (FragmentDataModel) tmpModel;
        int tmpAbsoluteFrequency = tmpFragmentDataModel.getAbsoluteFrequency();
        String tmpStringAbsoluteFrequency = String.format("%d", tmpAbsoluteFrequency);
        double tmpAbsolutePercentage = tmpFragmentDataModel.getAbsolutePercentage();
        int tmpMoleculeFrequency = tmpFragmentDataModel.getMoleculeFrequency();
        String tmpStringMoleculeFrequency = String.format("%d", tmpMoleculeFrequency);
        String tmpStringAbsolutePercentage = String.format("%.3f", tmpAbsolutePercentage);
        double tmpMoleculePercentage = tmpFragmentDataModel.getMoleculePercentage();
        String tmpStringMoleculePercentage = String.format("%.2f", tmpMoleculePercentage);
        // creates an image of the fragment
        PdfPCell tmpImageFragmentCell = new PdfPCell();
        tmpImageFragmentCell.setFixedHeight(85f);
        IAtomContainer tmpStructureOfFragment;
        try {
            tmpStructureOfFragment = tmpFragmentDataModel.getAtomContainer();
        } catch (CDKException anException) {
            Exporter.LOGGER.getLogger(MoleculeDataModel.class.getName()).log(Level.SEVERE, anException.toString() + "_" + tmpFragmentDataModel.getName(), anException);
            tmpFailedExportFragments.add(tmpFragmentDataModel.getUniqueSmiles());
            continue;
        }
        javafx.scene.image.Image tmpImageStructureOfFragment = DepictionUtil.depictImageWithZoom(tmpStructureOfFragment, 4.0);
        BufferedImage tmpBufferedImageFragment = SwingFXUtils.fromFXImage(tmpImageStructureOfFragment, null);
        Image tmpImageFragment = this.getITextImage(tmpBufferedImageFragment);
        // inserts the data into the table
        PdfPCell tmpCellOfFrequency = new PdfPCell(new Paragraph(tmpStringAbsoluteFrequency));
        tmpCellOfFrequency.setHorizontalAlignment(Element.ALIGN_RIGHT);
        PdfPCell tmpCellOfPercentage = new PdfPCell(new Paragraph(tmpStringAbsolutePercentage));
        tmpCellOfPercentage.setHorizontalAlignment(Element.ALIGN_RIGHT);
        PdfPCell tmpCellOfMolFrequency = new PdfPCell(new Paragraph(tmpStringMoleculeFrequency));
        tmpCellOfMolFrequency.setHorizontalAlignment(Element.ALIGN_RIGHT);
        PdfPCell tmpCellOfMolPercentage = new PdfPCell(new Paragraph(tmpStringMoleculePercentage));
        tmpCellOfMolPercentage.setHorizontalAlignment(Element.ALIGN_RIGHT);
        tmpImageFragmentCell.addElement(tmpImageFragment);
        tmpFragmentationTable.addCell(tmpImageFragmentCell);
        tmpFragmentationTable.addCell(tmpFragmentDataModel.getUniqueSmiles());
        tmpFragmentationTable.addCell(tmpCellOfFrequency);
        tmpFragmentationTable.addCell(tmpCellOfPercentage);
        tmpFragmentationTable.addCell(tmpCellOfMolFrequency);
        tmpFragmentationTable.addCell(tmpCellOfMolPercentage);
    }
    this.document.add(tmpHeader);
    this.document.add(tmpSpace);
    this.document.add(this.createHeaderTable(aFragmentDataModelList.size(), aMoleculeDataModelList.size(), aFragmentationName));
    this.document.add(tmpSpace);
    this.document.add(tmpFragmentationTable);
    this.document.close();
    return tmpFailedExportFragments;
}
Also used : PdfPCell(com.lowagie.text.pdf.PdfPCell) IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) CDKException(org.openscience.cdk.exception.CDKException) Document(com.lowagie.text.Document) Chunk(com.lowagie.text.Chunk) BufferedImage(java.awt.image.BufferedImage) Image(com.lowagie.text.Image) LinkedList(java.util.LinkedList) BufferedImage(java.awt.image.BufferedImage) Paragraph(com.lowagie.text.Paragraph) FragmentDataModel(de.unijena.cheminf.mortar.model.data.FragmentDataModel) PdfPTable(com.lowagie.text.pdf.PdfPTable) FileOutputStream(java.io.FileOutputStream) MoleculeDataModel(de.unijena.cheminf.mortar.model.data.MoleculeDataModel)

Aggregations

MoleculeDataModel (de.unijena.cheminf.mortar.model.data.MoleculeDataModel)17 FragmentDataModel (de.unijena.cheminf.mortar.model.data.FragmentDataModel)13 LinkedList (java.util.LinkedList)9 IAtomContainer (org.openscience.cdk.interfaces.IAtomContainer)9 CDKException (org.openscience.cdk.exception.CDKException)8 File (java.io.File)5 HashMap (java.util.HashMap)5 List (java.util.List)5 IDataTableView (de.unijena.cheminf.mortar.gui.views.IDataTableView)4 ItemizationDataTableView (de.unijena.cheminf.mortar.gui.views.ItemizationDataTableView)4 IMoleculeFragmenter (de.unijena.cheminf.mortar.model.fragmentation.algorithm.IMoleculeFragmenter)4 PrintWriter (java.io.PrintWriter)4 Hashtable (java.util.Hashtable)4 GridTabForTableView (de.unijena.cheminf.mortar.gui.panes.GridTabForTableView)3 FragmentsDataTableView (de.unijena.cheminf.mortar.gui.views.FragmentsDataTableView)3 MoleculesDataTableView (de.unijena.cheminf.mortar.gui.views.MoleculesDataTableView)3 Importer (de.unijena.cheminf.mortar.model.io.Importer)3 FileOutputStream (java.io.FileOutputStream)3 IOException (java.io.IOException)3 Chunk (com.lowagie.text.Chunk)2