Skip to content

Commit

Permalink
Font embedding on PDFs
Browse files Browse the repository at this point in the history
* New option to force usage of type 42 fonts in PDFs
* MatPlotLib will insert the appropriate font glyphs into the document, aka subsetting
* Updated header documentations
* Updated command line options
  • Loading branch information
hmedina committed Mar 27, 2024
1 parent 3a172fc commit 0cdc405
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 74 deletions.
22 changes: 14 additions & 8 deletions KaSaAn/scripts/kappa_catalytic_potential.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
``` {.text}
usage: kappa_catalytic_potential [-h] [-d DIRECTORY] -e ENZYME_NAME -s SUBSTRATE_NAME [-v] [-o OUTPUT_FILE] [-p SNAPSHOT_PATTERN] [-ts TEXT_SIZE]
[-h] Show detailed help.
[-d DIRECTORY] Directory containing the snapshots.
-e ENZYME_NAME Name of the first agent.
-s SUBSTRATE_NAME Name of the second agent.
[-v] If set, print additional information to standard output.
[-o OUTPUT_FILE] If specified, save to file; else print to standard output.
-p SNAPSHOT_PREFIX The prefix by which the snapshots are named.
[-ts TEXT_SIZE] Override default size for text, in points.
[-h] Show detailed help.
[-d DIRECTORY] Directory containing the snapshots.
-e ENZYME_NAME Name of the first agent.
-s SUBSTRATE_NAME Name of the second agent.
[-v] If set, print additional information to standard output.
[-o OUTPUT_FILE] If specified, save to file; else print to standard output.
-p SNAPSHOT_PREFIX The prefix by which the snapshots are named.
[-ts TEXT_SIZE] Override default size for text, in points.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
"""

Expand Down Expand Up @@ -50,10 +51,15 @@ def main(args=None):
help='Pattern by which the snapshots are named; e.g. <snap_4.ka> would have <snap_*.ka>.')
parser.add_argument('-ts', '--text_size', type=int,
help="If given, set point size for all text elements, overriding MatPlotLib's default.")
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')

args = parser.parse_args()
if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

data = get_potential_of_folder(args.directory, args.enzyme_name, args.substrate_name,
args.verbose, args.snapshot_pattern)
Expand Down
6 changes: 6 additions & 0 deletions KaSaAn/scripts/kappa_contact_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
[--summarize_flagpole] Summarizes state-only sites as a numeric annotation.
[--keep_axes_ticks] Show the X & Y axes ticks.
[-ts TEXT_SIZE] Override default size for text, in points.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
"""

Expand Down Expand Up @@ -58,10 +59,15 @@ def main():
' for manual agent placement.')
parser.add_argument('-ts', '--text_size', type=int,
help="If given, set point size for all text elements, overriding MatPlotLib's default.")
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')
args = parser.parse_args()

if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

this_cm = KappaContactMap(args.input_file_name)
fig, ax = plt.subplots(figsize=args.fig_size, layout='constrained')
Expand Down
6 changes: 6 additions & 0 deletions KaSaAn/scripts/kappa_observable_coplotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
outside left upper, outside right upper,
outside left lower, outside right lower
[--legend_ncol LEGEND_NCOL] Number of columns for the legend.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
"""

Expand Down Expand Up @@ -88,10 +89,15 @@ def main():
help='Number of columns for the legend.')
parser.add_argument('-ts', '--text_size', type=int,
help="If given, set point size for all text elements, overriding MatPlotLib's default.")
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')
args = parser.parse_args()

if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

fig, ax = plt.subplots(figsize=args.figure_size, layout='constrained')
observable_coplot_axis_annotator(target_axis=ax,
Expand Down
6 changes: 6 additions & 0 deletions KaSaAn/scripts/kappa_observable_plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
outside left upper, outside right upper,
outside left lower, outside right lower
[--legend_ncol LEGEND_NCOL] Number of columns for the legend.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
"""

Expand Down Expand Up @@ -91,10 +92,15 @@ def main():
help='Override location of the legend. Options prefixed with <outside> plot outside the axes.')
parser.add_argument('--legend_ncol', type=int, default=1,
help='Number of columns for the legend.')
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')
args = parser.parse_args()

if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

this_data = observable_file_reader(args.input_file_name)

Expand Down
65 changes: 38 additions & 27 deletions KaSaAn/scripts/kappa_snapshot_largest_complex_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,38 @@
``` {.text}
usage: kappa_snapshot_largest_complex_time [-h] [-d DIRECTORY] [-p PATTERN] [-cs COLORING_SCHEME] [-o OUTPUT_NAME] [-fs WIDTH HEIGHT] [--lin_log] [--log_lin] [--log_log] [--un_stacked] [-mt MULTI_THREAD] [-ts TEXT_SIZE]
[-h] Show detailed help.
[-d DIRECTORY] Directory where snapshots are stored, default is <.>
[-p PATTERN] Pattern that groups desired snapshots names; default 'snap*.ka'.
[-cs FILE] Optional file containing a dictionary with color scheme to use for species composition. E.g.
<{"Bob": #fff, "Mary": #999, "Sue": #222}>, where the color can be anything converable to a
color by MatPlotLib (e.g. RGB[A] tuples, hex-strings, XKCD colors...). Supports KappaAgents,
with or without agent signature, as well as KappaComplexes. If not provided, the sum formula
will be displayed (arbitrary colors per agent, discarding agent signature).
[-o OUTPUT_NAME] The common file name for saving figures; shown if not given.
[-fs WIDTH HEIGHT] Size of the resulting figure, in inches.
[--lin_log] If specified, produce an additional plot with linear X-axis and logarithmic Y-axis.
[--log_lin] If specified, produce an additional plot with logarithmic X-axis and linear Y-axis.
[--log_log] If specified, produce an additional plot with logarithmic X-axis and logarithmic Y-axis.
[--un_stacked] If given, produce regular non-stacked plot.
[--mt THREADS] Launch multiple threads for reading snapshots. Safe, but always less performant: WIP.
[-ts TEXT_SIZE] Override default size for text, in points.
[--stack_method] {...} The order of elements in the stackplot. Choices are:
first_in_first_out: Patterns are plotted in the order in which they are encountered while reading snapshots.
interleaved_initial: Patterns are plotted alternating large and small abundances, as measured in the first snapshot.
interleaved_final: Patterns are plotted alternating large and small abundances, as measured in the final snapshot.
ascending_initial: Patterns are plotted in ascending abundances, as measured in the first snapshot.
ascending_final: Patterns are plotted in ascending abundances, as measured in the final snapshot.
descending_initial: Patterns are plotted in descending abundances, as measured in the first snapshot.
descending_final: Patterns are plotted in descending abundances, as measured in the final snapshot.
[-h] Show detailed help.
[-d DIRECTORY] Directory where snapshots are stored, default is <.>
[-p PATTERN] Pattern that groups desired snapshots names; default 'snap*.ka'.
[-cs FILE] Optional file containing a dictionary with color scheme to use for species composition. E.g.
<{"Bob": #fff, "Mary": #999, "Sue": #222}>, where the color can be anything converable to a
color by MatPlotLib (e.g. RGB[A] tuples, hex-strings, XKCD colors...). Supports KappaAgents,
with or without agent signature, as well as KappaComplexes. If not provided, the sum formula
will be displayed (arbitrary colors per agent, discarding agent signature).
[-o OUTPUT_NAME] The common file name for saving figures; shown if not given.
[-fs WIDTH HEIGHT] Size of the resulting figure, in inches.
[--lin_log] If specified, produce an additional plot with linear X-axis and logarithmic Y-axis.
[--log_lin] If specified, produce an additional plot with logarithmic X-axis and linear Y-axis.
[--log_log] If specified, produce an additional plot with logarithmic X-axis and logarithmic Y-axis.
[--un_stacked] If given, produce regular non-stacked plot.
[--mt THREADS] Launch multiple threads for reading snapshots. Safe, but always less performant: WIP.
[-ts TEXT_SIZE] Override default size for text, in points.
[--stack_method] {...} The order of elements in the stackplot. Choices are:
first_in_first_out: Patterns are plotted in the order in which they are encountered while reading snapshots.
interleaved_initial: Patterns are plotted alternating large and small abundances, as measured in the first snapshot.
interleaved_final: Patterns are plotted alternating large and small abundances, as measured in the final snapshot.
ascending_initial: Patterns are plotted in ascending abundances, as measured in the first snapshot.
ascending_final: Patterns are plotted in ascending abundances, as measured in the final snapshot.
descending_initial: Patterns are plotted in descending abundances, as measured in the first snapshot.
descending_final: Patterns are plotted in descending abundances, as measured in the final snapshot.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
"""

import argparse
import ast
import matplotlib as mpl
import matplotlib.colors as mpco
import matplotlib.pyplot as plt
from pathlib import Path
from KaSaAn.core.KappaError import ComplexParseError, AgentParseError
Expand Down Expand Up @@ -83,12 +85,17 @@ def main():
' 1, so a single-threaded for-loop.')
parser.add_argument('-ts', '--text_size', type=int,
help="If given, set point size for all text elements, overriding MatPlotLib's default.")
parser.add_argument('--stack_method', choices=_stacked_plot_methods.keys(), type=str,
parser.add_argument('--stack_method', choices=_stacked_plot_methods.keys(), type=str, default=next(iter(_stacked_plot_methods)),
help='\n'.join(['{}:\t{}'.format(k, v) for k, v in _stacked_plot_methods.items()]))
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')
args = parser.parse_args()

if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

# for user-defined coloring schemes, read the dictionary from a file, convert keys
# Since single-agents can be interpreted as KappaComplexes, and that preserves sorting & comparisons, we cast
Expand All @@ -98,11 +105,15 @@ def main():
with open(args.coloring_scheme, 'r') as cs_file:
coloring_scheme_raw = ast.literal_eval(cs_file.read())
for key, value in coloring_scheme_raw.items():
if mpco.is_color_like(value):
this_color = value
else:
this_color = mpco.to_hex(eval(value))
try:
coloring_scheme[KappaAgent(key)] = value
coloring_scheme[KappaAgent(key)] = this_color
except AgentParseError:
try:
coloring_scheme[KappaComplex(key)] = value
coloring_scheme[KappaComplex(key)] = this_color
except ComplexParseError:
raise ValueError('Could not parse {} as a KappaComplex nor a KappaAgent'.format(key))
else:
Expand Down
24 changes: 15 additions & 9 deletions KaSaAn/scripts/kappa_snapshot_visualizer_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@
``` {.text}
usage: kappa_snapshot_visualizer_network [-h] -sf SNAPSHOT_FILE_NAME [-cs COLORING_SCHEME] [-p [HIGHLIGHT_PATTERNS ...]] [-of OUTPUT_FILE] [-fs WIDTH HEIGHT] [-ns NODE_SIZE] [-ew EDGE_WIDTH] [-ts TEXT_SIZE]
[-h] Show detailed help.
-sf SNAPSHOT_FILE_NAME Name of the snapshot file to be viewed.
[-cs FILE_NAME] Optional file containing an agent coloring scheme.
[-p [...]] Agent patterns to highlight.
[-of OUTPUT_FILE] The common file name for saving figures; shown if not given.
[-fs WIDTH HEIGHT] Size of the resulting figure, in inches.
[-ns NODE_SIZE] Size of nodes; default of 300 as used by NetworkX.
[-ew EDGE_WIDTH] Width of edges; default of 1.0 as used by NetworkX.
[-ts TEXT_SIZE] Override default size for text, in points.
[-h] Show detailed help.
-sf SNAPSHOT_FILE_NAME Name of the snapshot file to be viewed.
[-cs FILE_NAME] Optional file containing an agent coloring scheme.
[-p [...]] Agent patterns to highlight.
[-of OUTPUT_FILE] The common file name for saving figures; shown if not given.
[-fs WIDTH HEIGHT] Size of the resulting figure, in inches.
[-ns NODE_SIZE] Size of nodes; default of 300 as used by NetworkX.
[-ew EDGE_WIDTH] Width of edges; default of 1.0 as used by NetworkX.
[-ts TEXT_SIZE] Override default size for text, in points.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
The following are two views of the same snapshot, one showing all nodes, the other
Expand Down Expand Up @@ -66,11 +67,16 @@ def main():
help='Width of edges; default of 1.0 as used by NetworkX.')
parser.add_argument('-ts', '--text_size', type=int,
help="If given, set point size for all text elements, overriding MatPlotLib's default.")
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')

args = parser.parse_args()

if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

# render graph
figure_list = render_snapshot_as_plain_graph(snapshot_file_name=args.snapshot_file_name,
Expand Down
22 changes: 14 additions & 8 deletions KaSaAn/scripts/kappa_snapshot_visualizer_patchwork.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
``` {.text}
usage: kappa_snapshot_visualizer_patchwork [-h] -sf SNAPSHOT_FILE [-cs COLORING_SCHEME] [-vm {all,mass,count,size}] [-of OUTPUT_FILE] [-fs WIDTH HEIGHT] [-dpi DOTS_PER_INCH] [-ts TEXT_SIZE]
[-h] Show detailed help.
-sf SNAPSHOT_FILE_NAME Name of snapshot to visualize.
[-cs FILE_NAME] File specifying a coloring scheme.
[-vm [all|mass|count|size]] How to scale area; default plots all three.
[-of OUTPUT_FILE] The common file name for saving figures; shown if not given.
[-fs WIDTH HEIGHT] Size of the resulting figure, in inches.
[-dpi DOTS_PER_INCH] Resolution of the figure.
[-ts TEXT_SIZE] Override default size for text, in points.
[-h] Show detailed help.
-sf SNAPSHOT_FILE_NAME Name of snapshot to visualize.
[-cs FILE_NAME] File specifying a coloring scheme.
[-vm [all|mass|count|size]] How to scale area; default plots all three.
[-of OUTPUT_FILE] The common file name for saving figures; shown if not given.
[-fs WIDTH HEIGHT] Size of the resulting figure, in inches.
[-dpi DOTS_PER_INCH] Resolution of the figure.
[-ts TEXT_SIZE] Override default size for text, in points.
[--text_instead_of_paths] Output text elements instead of paths; embeds used glyphs
```
For example:
Expand Down Expand Up @@ -63,11 +64,16 @@ def main(args=None):
help='Resolution of the figure, specified as dots per inch.')
parser.add_argument('-ts', '--text_size', type=int,
help="If given, set point size for all text elements, overriding MatPlotLib's default.")
parser.add_argument('--text_instead_of_paths', action='store_true',
help='If set, figure will embed used glyphs and export text elements, instead of rendering the'
' glyphs into paths. Only supported for PDF export.')

args = parser.parse_args()

if args.text_size:
mpl.rcParams['font.size'] = args.text_size
if args.text_instead_of_paths:
plt.rcParams['pdf.fonttype'] = 42

# for user-defined coloring schemes, read the dictionary from a file, convert keys to KappaAgent
if args.coloring_scheme:
Expand Down
Loading

0 comments on commit 0cdc405

Please sign in to comment.