Skip to content

Quick Tools

codechembook.quickTools

importFromPy(py_name, *args)

Import a function or other object from a Python file that is not in the CWD or library.

Required Params: py_name (str): The name of the Python script from which you want to import. If not in PYTHONPATH, a dialog box will open to allow the user to specify the file location. *args (str): Names of the objects to import from the script.

Source code in src/codechembook/quickTools.py
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
def importFromPy(py_name, *args):
    """
    Import a function or other object from a Python file that is not in the CWD or library.

    Required Params:
    py_name (str): The name of the Python script from which you want to import.
                     If not in PYTHONPATH, a dialog box will open to allow the user to specify
                     the file location.
    *args (str):   Names of the objects to import from the script.
    """
    import importlib.util
    from pathlib import Path
    import sys
    import builtins
    import keyword

    # Check if the user supplied the full file name or just the stem
    if not py_name.endswith('.py'):
        filename = py_name + '.py'
    else:
        filename = py_name
        py_name = py_name.split('.')[0]

    # Locate the file
    path = Path(filename)
    if not path.exists():
        quickPopupMessage(f'{filename} not found. Please locate it using the file dialog.')
        path = quickOpenFilename(filetypes="Python Files, *.py")

        if not path:
            raise FileNotFoundError(f"The file {filename} could not be located.")

    # Load its module
    module_name = py_name
    module_spec = importlib.util.spec_from_file_location(module_name, str(path))
    module = importlib.util.module_from_spec(module_spec)

    # Import the module
    try:
        sys.modules[module_name] = module
        module_spec.loader.exec_module(module)
    except Exception as e:
        quickPopupMessage(f"Failed to load module {filename}: {e}")
        raise

    # Import objects
    imported_objects = {}
    for obj_name in args:
        try:
            imported_objects[obj_name] = getattr(module, obj_name)
        except AttributeError:
            quickPopupMessage(f"{obj_name} not found in {filename}.")
            raise ImportError(f"'{obj_name}' not found in '{filename}'.")

    # Add to the global namespace
    import __main__
    for obj_name, obj in imported_objects.items():
        # Check to make sure 
        if obj_name in dir(builtins) or keyword.iskeyword(obj_name):
            print(f"{obj_name} is a reserved keyword or built-in function name and will not be imported.")
        else:
            setattr(__main__, obj_name, obj)
            print(f"Imported {obj_name}")

    return imported_objects

quickHTMLFormula(formula, charge=0, name=None, CAS=None)

Outputs a properly formatted chemical formula for use in HTML contexts.

Required Params: formula (string): An unformatted chemical formula, without charge.

Optional Params: charge (int): The charge of the compound. (default: 0) name (string): The name of the compound. (default: None) CAS (string): The CAS number. (default: None)

Returns: (string): An HTML-formatted chemical formula.

Source code in src/codechembook/quickTools.py
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
def quickHTMLFormula(formula, charge = 0, name = None, CAS = None):
    '''
    Outputs a properly formatted chemical formula for use in HTML contexts.

    Required Params:
    formula (string): An unformatted chemical formula, without charge.

    Optional Params:
    charge (int):  The charge of the compound. (default: 0)
    name (string): The name of the compound. (default: None)
    CAS (string):  The CAS number. (default: None)

    Returns:
    (string): An HTML-formatted chemical formula.
    '''
    return ChemFormula(formula, charge = charge, name = name, cas = CAS).html.replace("<span class='ChemFormula'>", "").replace("</span>", "")

quickLatexFormula(formula, charge=0, name=None, CAS=None)

Outputs a properly formatted chemical formula for use in Latex contexts.

Required Params: formula (string): An unformatted chemical formula, without charge.

Optional Params: charge (int): The charge of the compound. (default: 0) name (string): The name of the compound. (default: None) CAS (string): The CAS number. (default: None)

Returns: (string): A Latex-formatted chemical formula.

Source code in src/codechembook/quickTools.py
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
def quickLatexFormula(formula, charge = 0, name = None, CAS = None):
    '''
    Outputs a properly formatted chemical formula for use in Latex contexts.

    Required Params:
    formula (string): An unformatted chemical formula, without charge.

    Optional Params:
    charge (int):  The charge of the compound. (default: 0)
    name (string): The name of the compound. (default: None)
    CAS (string):  The CAS number. (default: None)

    Returns:
    (string): A Latex-formatted chemical formula.
    '''
    return ChemFormula(formula, charge = charge, name = name, cas = CAS).latex

quickOpenFilename(title='Select file to open', initialpath='.', filetypes='All files, *.*')

Opens a file dialog to select a single file, returning a Path object to the file.

Optional Params: title (str): Title of the file selection dialog window. (default: "Select files to open") initialpath (str or Path): Initial directory for the dialog. (default: '.') filetypes (str or iterable): Types of files to display in the dialog. (default: "All files, .") Should be 'Description, *.extension' or a list/tuple of the same.

Returns: (Path or None): Selected file if "OK" is clicked, None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def quickOpenFilename(title="Select file to open", initialpath='.', filetypes='All files, *.*'):
    """
    Opens a file dialog to select a single file, returning a Path object to the file.

    Optional Params:
    title (str):                 Title of the file selection dialog window. (default: "Select files to open")
    initialpath (str or Path):   Initial directory for the dialog. (default: '.')
    filetypes (str or iterable): Types of files to display in the dialog. (default: "All files, *.*")
                                     Should be 'Description, *.extension' or a list/tuple of the same.

    Returns:
    (Path or None): Selected file if "OK" is clicked, None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow
    from pathlib import Path

    # Ensure initialpath is a string (if passed as a Path object)
    if isinstance(initialpath, Path):
        initialpath = str(initialpath)

    # If we got a list of file types, reformat it for getOpenFileName as a string with ';;' between entries
    if isinstance(filetypes, list):
        filetypes = ';;'.join(filetypes)

    # Ensure QApplication instance exists
    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    # Create a temporary hidden parent window to ensure the dialog appears on top
    parent = QMainWindow()
    parent.hide()  # Ensure the parent window is hidden

    filepath, _ = QFileDialog.getOpenFileName(None, title, initialpath, filetypes)

    # Close and clean up the parent window
    parent.close()
    parent.deleteLater()

    return Path(filepath) if filepath != '' else None

quickOpenFilenames(title='Select files to open', initialpath='.', filetypes='All files, *.*', sort=True)

Opens a file dialog to select multiple files, returning a sorted list of Path objects.

Optional Params: title (str): Title of the file selection dialog window. (default: "Select files to open") initialpath (str or Path): Initial directory for the dialog. (default: ',' (current working directory)) filetypes (str or iterable): Types of files to display in the dialog. (default: "All files, .") Should be 'Description, *.extension' or a list/tuple of the same. sort (bool): Whether the filenames in the collection should be sorted.

Returns: (list of Path): Selected file paths, or empty list if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def quickOpenFilenames(title="Select files to open", initialpath='.', filetypes='All files, *.*', sort = True):
    """
    Opens a file dialog to select multiple files, returning a sorted list of Path objects.

    Optional Params:
    title (str):                 Title of the file selection dialog window. (default: "Select files to open")
    initialpath (str or Path):   Initial directory for the dialog. (default: ',' (current working directory))
    filetypes (str or iterable): Types of files to display in the dialog. (default: "All files, *.*")
                                   Should be 'Description, *.extension' or a list/tuple of the same.
    sort (bool):                 Whether the filenames in the collection should be sorted.

    Returns:
    (list of Path): Selected file paths, or empty list if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow
    from pathlib import Path


    # Ensure initialpath is a string (if passed as a Path object)
    if isinstance(initialpath, Path):
        initialpath = str(initialpath)

    # If we got a list of file types, reformat it for getOpenFileName as a string with ';;' between entries
    if isinstance(filetypes, list):
        filetypes = ';;'.join(filetypes)

    # Ensure QApplication instance exists
    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    # Create a temporary hidden parent window to ensure the dialog appears on top
    parent = QMainWindow()
    parent.hide()  # Ensure the parent window is hidden

    filepaths, _ = QFileDialog.getOpenFileNames(None, title, initialpath, filetypes)

    # Close and clean up the parent window
    parent.close()
    parent.deleteLater()

    if sort:
        filepaths = sorted(filepaths)

    return [Path(filepath) for filepath in filepaths]

quickPlotCSV(file, cols=None, skip_header=1, plotType='scatter', xcol=0)

Plot the data in a CSV file using plotly.

Assumes that all columns share a single set of x points that by default is column 0 but can be specified by xcol = . Can produce scatter, bar, and histogram plot types.

Optional Params: file (str or Path): The file to be read. (default: open a dialog box to choose) cols (list of int): A list of the columns to be read. (default: read all columns) delimiter (str): The delimiter. (default: comma) skip_header (int): How many rows to skip, when acting as a header. (default: 1) xcol (int): The column number for the x-data. (default: 0) plotType (str): The type of plot that we want. (default: 'scatter', options: ('hist', 'bars'))

Returns: (Figure): A plotly figure object

Source code in src/codechembook/quickTools.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def quickPlotCSV(file, cols = None, skip_header = 1, plotType = "scatter", xcol = 0):
    '''
    Plot the data in a CSV file using plotly.

    Assumes that all columns share a single set of x points that by default is column
    0 but can be specified by xcol = <int>.  Can produce scatter, bar, and histogram plot types.

    Optional Params:
    file (str or Path): The file to be read. (default: open a dialog box to choose)
    cols (list of int): A list of the columns to be read. (default: read all columns)
    delimiter (str):    The delimiter. (default: comma)
    skip_header (int):  How many rows to skip, when acting as a header. (default: 1)
    xcol (int):         The column number for the x-data. (default: 0)
    plotType (str):     The type of plot that we want. (default: 'scatter', options: ('hist', 'bars'))

    Returns:
    (Figure): A plotly figure object
    '''

    from codechembook import quickPlots as qp

    read_columns = quickReadCSV(file, cols = cols, skip_header = skip_header)

    xdata = read_columns[xcol]
    ydata = []
    for c in range(0, xcol):
        ydata.append(read_columns[c])
    for c in range(xcol+1, len(read_columns)):
        ydata.append(read_columns[c])

    if plotType == "scatter":
        fig = qp.quickScatter(x = xdata, y = ydata)
        fig.show()

    return fig

quickPopupCheckboxes(message='Select options:', options=('Option 1', 'Option 2', 'Option 3'))

Displays a popup dialog with a message, a series of checkboxes, and OK/Cancel buttons.

Parameters: message (str): Message to display in the popup. (default: "Select Options:") options (list or tuple of str): Options to display as checkboxes.

Returns: (tuple of int): Indices of the checkboxes that are checked, or None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
def quickPopupCheckboxes(message="Select options:", options=("Option 1", "Option 2", "Option 3")):
    """
    Displays a popup dialog with a message, a series of checkboxes, and OK/Cancel buttons.

    Parameters:
    message (str):                  Message to display in the popup. (default: "Select Options:")
    options (list or tuple of str): Options to display as checkboxes.

    Returns:
    (tuple of int): Indices of the checkboxes that are checked, or None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import (
        QApplication,
        QDialog,
        QVBoxLayout,
        QLabel,
        QCheckBox,
        QPushButton,
        QHBoxLayout,
        QMainWindow,
    )
    from PyQt5.QtCore import Qt

    app = QApplication.instance()
    if app is None:
        app = QApplication([])  # Create a QApplication if it doesn't already exist

    # Create a temporary parent window to ensure the dialog is always on top
    parent = QMainWindow()
    parent.setWindowFlags(Qt.WindowStaysOnTopHint)  # Ensure it's always on top
    parent.setWindowTitle("Temporary Parent")
    parent.resize(1, 1)  # Make the parent very small
    parent.show()  # Show the parent window
    parent.raise_()
    parent.activateWindow()

    # Create the custom dialog
    dialog = QDialog(parent)
    dialog.setWindowTitle("Checkbox Dialog")
    dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowStaysOnTopHint)  # Always on top

    # Set up the layout
    layout = QVBoxLayout()

    # Add the message label
    label = QLabel(message)
    layout.addWidget(label)

    # Add checkboxes for each option
    checkboxes = []
    for option in options:
        checkbox = QCheckBox(option)
        layout.addWidget(checkbox)
        checkboxes.append(checkbox)

    # Add OK and Cancel buttons
    button_layout = QHBoxLayout()
    ok_button = QPushButton("OK")
    cancel_button = QPushButton("Cancel")
    button_layout.addWidget(ok_button)
    button_layout.addWidget(cancel_button)
    layout.addLayout(button_layout)

    # Connect button actions
    def on_ok():
        dialog.accept()  # Accept the dialog and close it

    def on_cancel():
        dialog.reject()  # Reject the dialog and close it

    ok_button.clicked.connect(on_ok)
    cancel_button.clicked.connect(on_cancel)

    # Set the layout for the dialog
    dialog.setLayout(layout)

    # Show the dialog and wait for user interaction
    result = dialog.exec_()

    # Properly clean up the parent window
    parent.hide()  # Hide the parent window immediately
    app.processEvents()  # Process any pending events
    parent.close()  # Close the parent window
    parent.deleteLater()  # Mark the parent for deletion

    # Return the appropriate value based on user interaction
    if result == QDialog.Accepted:
        # Gather indices of checkboxes that are checked
        checked_indices = tuple(i for i, checkbox in enumerate(checkboxes) if checkbox.isChecked())
        return checked_indices
    else:
        return None  # Return None if Cancel was clicked

quickPopupChoice(message='Choose an option:', option1='Option 1', option2='Option 2')

Displays a popup dialog with a message and two buttons, returning the selected option as a string.

Optional Params: message (str): Message to display in the popup. (default: "Choose an option:") option1 (str): Text for the first button. (default: "Option 1") option2 (str): Text for the second button. (default: "Option 2")

Returns: (str): Text of the button selected by the user.

Source code in src/codechembook/quickTools.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def quickPopupChoice(message="Choose an option:", option1="Option 1", option2="Option 2"):
    """
    Displays a popup dialog with a message and two buttons, returning the selected option as a string.

    Optional Params:
    message (str): Message to display in the popup. (default: "Choose an option:")
    option1 (str): Text for the first button. (default: "Option 1")
    option2 (str): Text for the second button. (default: "Option 2")

    Returns:
    (str): Text of the button selected by the user.
    """
    from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow
    from PyQt5.QtCore import Qt

    app = QApplication.instance()
    if app is None:
        app = QApplication([])  # Create a QApplication if it doesn't already exist

    # Create a visible temporary parent window to ensure the popup appears on top
    parent = QMainWindow()
    parent.setWindowFlags(Qt.WindowStaysOnTopHint)  # Ensure it's always on top
    parent.setWindowTitle("Temporary Parent")
    parent.resize(1, 1)  # Make the parent very small
    parent.show()  # Show the parent window
    parent.raise_()
    parent.activateWindow()

    # Create the message box with the parent
    msg_box = QMessageBox(parent)
    msg_box.setIcon(QMessageBox.Question)  # Set the icon to Question
    msg_box.setText(message)
    msg_box.setWindowTitle("Make a Choice")

    # Add the two custom buttons
    button1 = msg_box.addButton(option1, QMessageBox.ActionRole)
    button2 = msg_box.addButton(option2, QMessageBox.ActionRole)

    # Ensure the message box always appears on top
    msg_box.setWindowFlags(msg_box.windowFlags() | Qt.WindowStaysOnTopHint)
    msg_box.raise_()
    msg_box.activateWindow()

    # Show the message box and wait for the user's choice
    msg_box.exec_()

    # Determine which button was clicked
    if msg_box.clickedButton() == button1:
        choice = option1
    elif msg_box.clickedButton() == button2:
        choice = option2
    else:
        choice = None  # Fallback in case no valid button was clicked (shouldn't happen)

    # Clean up the parent window
    parent.hide()
    app.processEvents()
    parent.close()
    parent.deleteLater()

    return choice

quickPopupDropdown(message='Select an option:', options=('Option 1', 'Option 2', 'Option 3'))

Displays a popup dialog with a message, a dropdown menu, and OK/Cancel buttons.

Optional Params: message (str): Message to display in the popup. (default: "Select an option:") options (list or tuple of str): Options to display in the dropdown.

Returns: (int): Index of the selected option, or None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def quickPopupDropdown(message="Select an option:", options=("Option 1", "Option 2", "Option 3")):
    """
    Displays a popup dialog with a message, a dropdown menu, and OK/Cancel buttons.

    Optional Params:
    message (str):                  Message to display in the popup. (default: "Select an option:")
    options (list or tuple of str): Options to display in the dropdown.

    Returns:
    (int): Index of the selected option, or None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QComboBox, QPushButton, QHBoxLayout, QMainWindow
    from PyQt5.QtCore import Qt

    app = QApplication.instance()
    if app is None:
        app = QApplication([])  # Create a QApplication if it doesn't already exist

    # Create a temporary parent window to ensure the dialog is always on top
    parent = QMainWindow()
    parent.setWindowFlags(Qt.WindowStaysOnTopHint)  # Ensure it's always on top
    parent.setWindowTitle("Temporary Parent")
    parent.resize(1, 1)  # Make the parent very small
    parent.show()  # Show the parent window
    parent.raise_()
    parent.activateWindow()

    # Create the custom dialog
    dialog = QDialog(parent)
    dialog.setWindowTitle("Dropdown Dialog")
    dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowStaysOnTopHint)  # Always on top

    # Set up the layout
    layout = QVBoxLayout()

    # Add the message label
    label = QLabel(message)
    layout.addWidget(label)

    # Add the dropdown box
    dropdown = QComboBox()
    dropdown.addItems(options)  # Populate the dropdown with options
    layout.addWidget(dropdown)

    # Add OK and Cancel buttons
    button_layout = QHBoxLayout()
    ok_button = QPushButton("OK")
    cancel_button = QPushButton("Cancel")
    button_layout.addWidget(ok_button)
    button_layout.addWidget(cancel_button)
    layout.addLayout(button_layout)

    # Connect button actions
    def on_ok():
        dialog.accept()  # Accept the dialog and close it

    def on_cancel():
        dialog.reject()  # Reject the dialog and close it

    ok_button.clicked.connect(on_ok)
    cancel_button.clicked.connect(on_cancel)

    # Set the layout for the dialog
    dialog.setLayout(layout)

    # Show the dialog and wait for user interaction
    result = dialog.exec_()

    # Properly clean up the parent window
    parent.hide()  # Hide the parent window immediately
    app.processEvents()  # Force event loop to process hiding
    parent.close()  # Close the parent window
    parent.deleteLater()  # Mark the parent for deletion

    # Return the appropriate value based on user interaction
    if result == QDialog.Accepted:
        return dropdown.currentIndex()  # Return the index of the selected option
    else:
        return None  # Return None if Cancel was clicked

quickPopupInput(message='Enter some text:')

Displays a popup dialog with a message, a text input box, and OK/Cancel buttons.

Optional Params: message (str): Message to display in the popup.

Returns: (str): Text entered by the user, or None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def quickPopupInput(message="Enter some text:"):
    """
    Displays a popup dialog with a message, a text input box, and OK/Cancel buttons.

    Optional Params:
    message (str): Message to display in the popup.

    Returns:
    (str): Text entered by the user, or None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QHBoxLayout, QMainWindow
    from PyQt5.QtCore import Qt

    app = QApplication.instance()
    if app is None:
        app = QApplication([])  # Create a QApplication if it doesn't already exist

    # Create a temporary parent window to ensure the dialog is always on top
    parent = QMainWindow()
    parent.setWindowFlags(Qt.WindowStaysOnTopHint)  # Ensure it's always on top
    parent.setWindowTitle("Temporary Parent")
    parent.resize(1, 1)  # Make the parent very small
    parent.show()  # Show the parent window
    parent.raise_()
    parent.activateWindow()

    # Create the custom dialog
    dialog = QDialog(parent)
    dialog.setWindowTitle("Input Dialog")
    dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowStaysOnTopHint)  # Always on top

    # Set up the layout
    layout = QVBoxLayout()

    # Add the message label
    label = QLabel(message)
    layout.addWidget(label)

    # Add the text input box
    text_input = QLineEdit()
    layout.addWidget(text_input)

    # Add OK and Cancel buttons
    button_layout = QHBoxLayout()
    ok_button = QPushButton("OK")
    cancel_button = QPushButton("Cancel")
    button_layout.addWidget(ok_button)
    button_layout.addWidget(cancel_button)
    layout.addLayout(button_layout)

    # Connect button actions
    def on_ok():
        dialog.accept()  # Accept the dialog and close it

    def on_cancel():
        dialog.reject()  # Reject the dialog and close it

    ok_button.clicked.connect(on_ok)
    cancel_button.clicked.connect(on_cancel)

    # Set the layout for the dialog
    dialog.setLayout(layout)

    # Show the dialog and wait for user interaction
    result = dialog.exec_()

    # Clean up the parent window
    parent.hide()
    app.processEvents()
    parent.close()
    parent.deleteLater()

    # Return the appropriate value based on user interaction
    if result == QDialog.Accepted:
        return text_input.text()  # Return the entered text if OK was clicked
    else:
        return None  # Return None if Cancel was clicked

quickPopupMessage(message='This is a message. Click OK to continue.')

Displays a simple popup dialog with a message and an OK button.

Optional Params: message (str): Message to display. (default: "This is a message. Click OK to continue")

Source code in src/codechembook/quickTools.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def quickPopupMessage(message="This is a message. Click OK to continue."):
    """
    Displays a simple popup dialog with a message and an OK button.

    Optional Params:
    message (str): Message to display. (default: "This is a message. Click OK to continue")

    """
    from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow
    from PyQt5.QtCore import Qt

    app = QApplication.instance()
    if app is None:
        app = QApplication([])  # Create a QApplication if it doesn't already exist

    # Create a visible temporary parent window
    parent = QMainWindow()
    parent.setWindowFlags(Qt.WindowStaysOnTopHint)  # Ensure it's always on top
    parent.setWindowTitle("Temporary Parent")
    parent.resize(1, 1)  # Make the parent very small
    parent.show()  # Show the parent window
    parent.raise_()
    parent.activateWindow()

    # Create the message box with the parent
    msg_box = QMessageBox(parent)
    msg_box.setIcon(QMessageBox.Information)
    msg_box.setText(message)
    msg_box.setWindowTitle("Message")
    msg_box.setStandardButtons(QMessageBox.Ok)

    # Ensure the message box is always on top
    msg_box.setWindowFlags(msg_box.windowFlags() | Qt.WindowStaysOnTopHint)
    msg_box.raise_()  # Bring it to the front
    msg_box.activateWindow()  # Make it the active window

    # Show the message box and wait for user interaction
    msg_box.exec_()

    # Clean up the parent window
    parent.hide()
    app.processEvents()
    parent.close()
    parent.deleteLater()

quickPopupMultiInput(messages=['Enter some text:'])

Displays a popup dialog with multiple messages, each with a text input box, and OK/Cancel buttons.

Optional Params: message (list of str): Messages to display in the popup.

Returns: (list of str): Text entered by the user, or None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
def quickPopupMultiInput(messages=["Enter some text:"]):
    """
    Displays a popup dialog with multiple messages, each with a text input box, and OK/Cancel buttons.

    Optional Params:
    message (list of str): Messages to display in the popup.

    Returns:
    (list of str): Text entered by the user, or None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QLineEdit, QPushButton, QHBoxLayout, QMainWindow
    from PyQt5.QtCore import Qt

    app = QApplication.instance()
    if app is None:
        app = QApplication([])  # Create a QApplication if it doesn't already exist

    # Create a temporary parent window to ensure the dialog is always on top
    parent = QMainWindow()
    parent.setWindowFlags(Qt.WindowStaysOnTopHint)  # Ensure it's always on top
    parent.setWindowTitle("Temporary Parent")
    parent.resize(1, 1)  # Make the parent very small
    parent.show()  # Show the parent window
    parent.raise_()
    parent.activateWindow()

    # Create the custom dialog
    dialog = QDialog(parent)
    dialog.setWindowTitle("Input Dialog")
    dialog.setWindowFlags(dialog.windowFlags() | Qt.WindowStaysOnTopHint)  # Always on top

    # Set up the layout
    layout = QVBoxLayout()

    # Add the message label and text input box for each input
    labels = []
    text_inputs = []
    for message in messages:
        labels.append(QLabel(message))
        layout.addWidget(labels[-1])
        text_inputs.append(QLineEdit())
        layout.addWidget(text_inputs[-1])

    # Add OK and Cancel buttons
    button_layout = QHBoxLayout()
    ok_button = QPushButton("OK")
    cancel_button = QPushButton("Cancel")
    button_layout.addWidget(ok_button)
    button_layout.addWidget(cancel_button)
    layout.addLayout(button_layout)

    # Connect button actions
    def on_ok():
        dialog.accept()  # Accept the dialog and close it

    def on_cancel():
        dialog.reject()  # Reject the dialog and close it

    ok_button.clicked.connect(on_ok)
    cancel_button.clicked.connect(on_cancel)

    # Set the layout for the dialog
    dialog.setLayout(layout)

    # Show the dialog and wait for user interaction
    result = dialog.exec_()

    # Clean up the parent window
    parent.hide()
    app.processEvents()
    parent.close()
    parent.deleteLater()

    # Return the appropriate value based on user interaction
    if result == QDialog.Accepted:
        return [text_input.text() for text_input in text_inputs]  # Return the entered text if OK was clicked
    else:
        return None  # Return None if Cancel was clicked

quickReadCSV(file=None, cols=None, delimiter=',', skip_header=1)

A wrapper for Numpy's genfromtxt to read a CSV file with minimal code.

Will work out of the box for a typical CSV having one header row with no keywords, returns columns as tuple of Numpy arrays.

Optional Params: file (str or Path): The file to be read. (default: open a dialog box to choose) cols (list of int): A list of the columns to be read. (default: read all columns) delimiter (str): The delimiter. (default, comma) skip_header (int): How many rows to skip, when acting as a header. (default, 1)

Returns: (tuple): The columns of data as Numpy ndarrays.

Source code in src/codechembook/quickTools.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def quickReadCSV(file = None, cols = None, delimiter = ",", skip_header = 1):
    '''
    A wrapper for Numpy's genfromtxt to read a CSV file with minimal code.

    Will work out of the box for a typical CSV having one header row with 
    no keywords, returns columns as tuple of Numpy arrays.

    Optional Params:
    file (str or Path): The file to be read. (default: open a dialog box to choose)
    cols (list of int): A list of the columns to be read. (default: read all columns)
    delimiter (str):    The delimiter. (default, comma)
    skip_header (int):  How many rows to skip, when acting as a header. (default, 1)

    Returns:
    (tuple): The columns of data as Numpy ndarrays.
    '''
    if file is None:
        file = quickOpenFilename()

    if file is None:
        print('No file selected.')
        return

    if cols == None: # no specific set of columns specified
        read_columns = np.genfromtxt(file, 
                                    delimiter = delimiter,
                                    skip_header=skip_header,
                                    unpack=True,
                                    )
    else: # probably should check to make sure it is a thing that can be a list... in elif
        read_columns = np.genfromtxt(file, 
                                delimiter = delimiter,
                                skip_header=skip_header,
                                usecols=cols,
                                unpack=True,
                                )
    return read_columns

quickSaveCSV(file, data, format=None, delimiter=', ', header='')

A wrapper for Numpy's savetxt to write a CSV file in a common format with minimal code.

Required Params: data (list or ndarray): The data to save. Can be 1D or 2D list or ndarrays, or list of 1D ndarrays.

Optional Params: file (str or Path): The path to save the file. (default: use a dialog box) format (str or list): A format string using either pre-Python2.6 format ('%5.3f') for f-string format ('5.3f'). The colon is omitted. Default is '.14f'. If columns need different formatting, a list of f-string style format strings for each column can be provided. delimiter (str): The delimiter character. (default: ', ', options: (' ', ' ', anything else)) header (str): Column header text. Default is no header

Source code in src/codechembook/quickTools.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def quickSaveCSV(file, data, format = None, delimiter = ', ', header = ''):
    """
    A wrapper for Numpy's savetxt to write a CSV file in a common format with minimal code.

    Required Params:
    data (list or ndarray): The data to save.  Can be 1D or 2D list or ndarrays, or list of 1D ndarrays.

    Optional Params:
    file (str or Path):     The path to save the file. (default: use a dialog box)
    format (str or list):   A format string using either pre-Python2.6 format ('%5.3f') for f-string
                              format ('5.3f').  The colon is omitted.  Default is '.14f'.  If columns need 
                              different formatting, a list of f-string style format strings for each column 
                              can be provided.
    delimiter (str):        The delimiter character. (default: ', ', options: (' ', '\t', anything else))
    header (str):           Column header text.  Default is no header
    """
    # Check which type of data we have received and make a new numpy array holding it
    if isinstance(data, list) or isinstance(data, tuple):
        # If we got a list, then we need to turn rows into columns to make a 2D array
        prep_data = np.column_stack(data)

    elif isinstance(data, np.ndarray):
        # If we got a numpy array, we need to figure out what its dimension is
        if len(data.shape) > 2:
            print('This function can not handle arrays with three or more dimensions!')
            return

        elif len(data.shape) in [2, 1]:
            # Easy, we just copy it over
            prep_data = data

        else:
            print('Incompatible numpy array shape for this function.')

    elif isinstance(data, (int, float, complex, bool, str)):
        # For whatever reason, the user wants to write just one value
        prep_data = np.array([data])

    else:
        print('This data type is not supported by this function.')
        return

    if format is None:
        # No format statement given, let's just print 20 characters total
        new_format = '%.14e' # good for anything but the most precise measurements made by humans

    elif isinstance(format, str):
        if format[0] == '%' or format[1] == '%':
            # We have an old-school python format string, use it as is
            new_format = format

        else:
            # Assume we have an f-strings type format string
            # Quick way to format large ndarrays: define format function, vectorize, apply
            def temp(x):
                return f'{x:{format}}'
            fast_format = np.vectorize(temp)
            prep_data = fast_format(prep_data)

            # Now we have a formatted string, so we just want the format statement to keep it the same
            new_format = '%s'

    elif isinstance(format, list):
        # We want different columns to be different formats.  First make sure formats and columns match
        if len(format) == prep_data.shape[1]:
            # Empty list of columns of formatted data
            string_data = []
            print(f'Formatting {prep_data.shape[1]} columns with {len(format)} format statements')

            # Loop over columns and format them one by one with the appropriate format string
            for i, f in enumerate(format):
                # See previous elif for explanation
                def temp(x):
                    return f'{x:{f}}'
                fast_format = np.vectorize(temp)

                # Add the new formatted column to the data list
                string_data.append(fast_format(prep_data[:,i]))

            # Make a ndarray with the formatted columns
            prep_data = np.column_stack(string_data)

            # Now we have a formatted string, so we just want the format statement to keep it the same
            new_format = '%s'

        else:
            # Number of data columns and format strings are not the same, fail with a useful message
            print(f'Failed: Received {prep_data.shape[1]} columns but {len(format)} format statements.\nNot writing any file.')
            return

    # Write the file
    np.savetxt(file, prep_data, delimiter = delimiter, fmt = new_format, header = header, comments = '')

quickSaveFilename(title='Choose or create a filename to save', initialpath='.', filetypes='All files, *.*')

Opens a file dialog to choose a filename for saving, returns a Path object.

Optional Params: title (str): Title of the file selection dialog window. (default: "Define file to save") initialpath (str or Path): Initial directory for the dialog. (default: ',' (current working directory)) filetypes (str or iterable): Types of files to display in the dialog. (default: "All files, .") Should be 'Description, *.extension' or a list/tuple of the same.

Returns: (Path): Path to file that is to be saved, or None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def quickSaveFilename(title="Choose or create a filename to save", 
                      initialpath='.', filetypes='All files, *.*'):
    """
    Opens a file dialog to choose a filename for saving, returns a Path object.

    Optional Params:
    title (str):                 Title of the file selection dialog window. (default: "Define file to save")
    initialpath (str or Path):   Initial directory for the dialog. (default: ',' (current working directory))
    filetypes (str or iterable): Types of files to display in the dialog. (default: "All files, *.*")
                                     Should be 'Description, *.extension' or a list/tuple of the same.

    Returns:
    (Path): Path to file that is to be saved, or None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow
    from pathlib import Path

    # Ensure initialpath is a string (if passed as a Path object)
    if isinstance(initialpath, Path):
        initialpath = str(initialpath)

    # If we got a list of file types, reformat it for getSaveFileName as a string with ';;' between entries
    if isinstance(filetypes, list):
        filetypes = ';;'.join(filetypes)

    # Ensure QApplication instance exists
    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    # Create a temporary hidden parent window
    parent = QMainWindow()
    parent.hide()  # Do not display the window

    # Open the file dialog with the temporary parent
    filepath, _ = QFileDialog.getSaveFileName(parent, title, initialpath, filetypes)

    # Close the temporary parent window
    parent.close()
    parent.deleteLater()  # Ensure proper cleanup of the parent window

    return Path(filepath) if filepath else None

quickSelectFolder(title='Select folder', initialpath='.')

Opens a folder selection dialog, returning the selected folder as a Path object.

Optional Params: title (str): Title of the folder selection dialog window. (default: "Select folder") initialpath (str or Path): Initial directory for the dialog. (default: '.')

Returns: (Path): Selected folder, or None if "Cancel" is clicked.

Source code in src/codechembook/quickTools.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def quickSelectFolder(title="Select folder", initialpath="."):
    """
    Opens a folder selection dialog, returning the selected folder as a Path object.

    Optional Params:
    title (str):               Title of the folder selection dialog window. (default: "Select folder")
    initialpath (str or Path): Initial directory for the dialog. (default: '.')

    Returns:
    (Path): Selected folder, or None if "Cancel" is clicked.
    """
    from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow
    from pathlib import Path

    # Ensure initialpath is a string (if passed as a Path object)
    if isinstance(initialpath, Path):
        initialpath = str(initialpath)

    # Ensure QApplication instance exists
    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    # Create a temporary hidden parent window to ensure the dialog appears on top
    parent = QMainWindow()
    parent.hide()  # Ensure the parent window is hidden

    # Open the folder selection dialog with the hidden parent
    folderpath = QFileDialog.getExistingDirectory(parent, title, initialpath)

    # Close and clean up the parent window
    parent.close()
    parent.deleteLater()

    # Return the selected folder as a Path object, or None if no folder was selected
    return Path(folderpath) if folderpath else None

quickUnicodeFormula(formula, charge=0, name=None, CAS=None)

Outputs a properly formatted chemical formula for use in unicode.

Required Params: formula (string): An unformatted chemical formula, without charge.

Optional Params: charge (int): The charge of the compound. (default: 0) name (string): The name of the compound. (default: None) CAS (string): The CAS number. (default: None)

Returns: (string): A unicode chemical formula.

Source code in src/codechembook/quickTools.py
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
def quickUnicodeFormula(formula, charge = 0, name = None, CAS = None):
    '''
    Outputs a properly formatted chemical formula for use in unicode.

    Required Params:
    formula (string): An unformatted chemical formula, without charge.

    Optional Params:
    charge (int):  The charge of the compound. (default: 0)
    name (string): The name of the compound. (default: None)
    CAS (string):  The CAS number. (default: None)

    Returns:
    (string): A unicode chemical formula.
    '''
    return ChemFormula(formula, charge = charge, name = name, cas = CAS).unicode