Skip to content

Commit

Permalink
Dev (#744)
Browse files Browse the repository at this point in the history
* read the string back

* Add chromosome()

* fix ci

* Add get_shades()

* fix ci

* draw chromosomes

* minor

* add cross symbol

* simulate sequentially

* minor fix

* update savefig

* use multiprocessing

* sort by descending weight

* update

* superfluous sorted()

* update
  • Loading branch information
tanghaibao authored Jan 24, 2025
1 parent e512c83 commit 5bad2c6
Show file tree
Hide file tree
Showing 6 changed files with 338 additions and 121 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ jobs:
cache: 'pip'

- name: Install BEDTools (Linux)
run: sudo apt-get install bedtools libmagickwand-dev
run: |
sudo apt-get update
sudo apt-get install --fix-missing bedtools libmagickwand-dev
if: matrix.os == 'ubuntu-latest'

- name: Install BEDTools (macOS)
Expand Down
5 changes: 1 addition & 4 deletions src/jcvi/apps/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,9 @@
from socket import gethostname
from subprocess import CalledProcessError, PIPE, call, check_output
from time import ctime
from typing import Any, Collection, List, Optional, Tuple, Union
from typing import Collection, List, Optional, Tuple, Union
from urllib.parse import urlencode

# from optparse import OptionParser as OptionP, OptionGroup, SUPPRESS_HELP


from natsort import natsorted
from rich.console import Console
from rich.logging import RichHandler
Expand Down
51 changes: 29 additions & 22 deletions src/jcvi/graphics/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

mpl.use("Agg")

import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

Expand Down Expand Up @@ -322,39 +323,20 @@ def update_figname(figname: str, format: str) -> str:
return figname + "." + format


def update_figname(figname: str, format: str) -> str:
"""Update the name of a figure to include the format.
Args:
figname (str): Path to the figure
format (str): Figure format, must be one of GRAPHIC_FORMATS
Returns:
str: New file path
"""
_, ext = op.splitext(figname)
if ext.strip(".") in GRAPHIC_FORMATS: # User suffix has precedence
return figname
# When the user has not supplied a format in the filename, use the requested format
assert format in GRAPHIC_FORMATS, "Invalid format"
return figname + "." + format


def savefig(figname, dpi=150, iopts=None, cleanup=True, transparent=False):
try:
format = figname.rsplit(".", 1)[-1].lower()
except:
format = "pdf"
logger.debug("Matplotlib backend is: %s", mpl.get_backend())
try:
logger.debug(f"Matplotlib backend is: {mpl.get_backend()}")
logger.debug(f"Attempting save as: {figname}")
logger.debug("Attempting save as: `%s`", figname)
plt.savefig(figname, dpi=dpi, format=format, transparent=transparent)
except Exception as e:
message = "savefig failed with message:"
message += "\n{0}".format(str(e))
logger.error(message)
logger.debug(f"Matplotlib backend is: {mpl.get_backend()}")
logger.debug(f"Attempted save as: {format}")
logger.debug("Attempted save as: %s", format)
logger.info("Try running again with --notex option to disable latex.")
if op.exists(figname):
if op.getsize(figname) < 1000:
Expand Down Expand Up @@ -677,6 +659,31 @@ def get_intensity(octal):
return intensity


def get_shades(base_color: str, n: int) -> np.array:
"""
Generate N shades of a base color by blending with white and black. The base
color is in hex format, e.g., '#FF0000' for red.
"""
base_rgb = np.array(mcolors.to_rgb(base_color)) # Convert hex to RGB (normalized)
lighter = n // 2
darker = n - lighter - 1

# Generate lighter shades by blending with white
white = np.array([1, 1, 1]) # White color as a NumPy array
lighter_shades = [
(white * (1 - i) + base_rgb * i) for i in np.linspace(0.2, 1, lighter + 1)
][:-1]

# Generate darker shades by blending with black
black = np.array([0, 0, 0]) # Black color as a NumPy array
darker_shades = [
(base_rgb * i + black * (1 - i)) for i in np.linspace(1, 0.2, darker + 1)
][1:]

# Combine all shades with the base color in the middle
return lighter_shades + [base_rgb] + darker_shades


def adjust_spines(ax, spines, outward=False, color="lightslategray"):
# Modified from <http://matplotlib.org/examples/pylab_examples/spine_placement_demo.html>
for loc, spine in ax.spines.items():
Expand Down
20 changes: 10 additions & 10 deletions src/jcvi/graphics/chromosome.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from itertools import groupby
from math import ceil
from typing import Optional, Tuple
from typing import List, Optional, Tuple

import numpy as np

Expand Down Expand Up @@ -43,15 +43,15 @@ class Chromosome(BaseGlyph):
def __init__(
self,
ax,
x,
y1,
y2,
width=0.015,
ec="k",
patch=None,
patchcolor="lightgrey",
lw=1,
zorder=2,
x: float,
y1: float,
y2: float,
width: float = 0.015,
ec: str = "k",
patch: Optional[List[float]] = None,
patchcolor: str = "lightgrey",
lw: int = 1,
zorder: int = 2,
):
"""
Chromosome with positions given in (x, y1) => (x, y2)
Expand Down
Loading

0 comments on commit 5bad2c6

Please sign in to comment.