grapa.graph.Graph

class grapa.graph.Graph(filename: str | List[str] | List | ndarray = '', complement: dict | str | List[dict | str] = '', silent: bool = True, config: str | None = 'auto', log_active: bool = False)

Bases: object

A Graph can be though as containing a list of Curves, and is a convenient way to read, store and manipulate data, as well as export plot as images and text files.

Parameters:
  • filename – str filename to open, or list[str] (filenames), or list of data series [xseries, yseries [, zseries…]]. Default ‘’ (graph empty).

  • complement

    dict, the elements will be stored as graph attributes. Example: {‘xlim’: [1, ‘’]}. Special values:

    • ’isfilecontent’ = True: content of variable filename is interpreted as data

    • ’readas’ in [‘database’, ‘generic’]. ‘database’ can be useful. You may consider using pandas instead

  • silent – to get more details on what is going on. Default True

  • config – configuration datafile. Default “auto”: same as first one specified. Fallback ‘config.txt’

  • log_active – if True, activates a CommandRecorder that logs the actions performed on the graph object (low level instructions, not API-level). Purpose is to offer do/undo functionalities.

__init__(filename: str | List[str] | List | ndarray = '', complement: dict | str | List[dict | str] = '', silent: bool = True, config: str | None = 'auto', log_active: bool = False)

default constructor. Calls method reset.

Methods

__init__([filename, complement, silent, ...])

default constructor.

alterListGUI()

Compiles a list of possible data transforms, retrieved from all Curves

append(curve[, idx])

Add into the object list a Curve, a list or Curves, or every Curve in a Graph object.

apply_template(graph[, also_curves])

Apply a template to the Graph object.

attr(key[, default])

Retrieve an attribute value in header, graphInfo or in curve[0]

attr_pop(key)

Delete an attribute of the Graph, and return its value

castCurve(newtype, idx[, silentSuccess])

Deprecated.

colorize(colorscale[, sameIfEmptyLabel, ...])

Colorize a graph, by coloring each Curve along a colorscale gradient.

config(key[, default, astype])

Returns the value corresponding to key in the configuration file.

config_all()

Returns all key-value pairs in config file, and filename

curve(idx)

Returns the Curve object at index i in the list.

curve_cast(new_type, idx[, print_success])

Replace a Curve with another type of Curve with identical data and properties.

curve_delete(idx)

Delete a Curve at index i from the Graph object.

curve_duplicate(idx)

Duplicate (clone) an existing curve and append it in the curves list.

curve_move_to_index(idx_source, idx_target)

Change the position of a Curve in the list

curve_replace(new_curve, idx)

Update a Curve with a new one.

curves(key, value[, str_lower, str_startswith])

Returns a list of Curves for which curve.attr(key) value (type and value equality)

curves_reverse()

Reverse the order of the Curves.

curves_swap(idx1, idx2[, relative])

Exchange the Curves at index idx1 and idx2.

deleteCurve(i)

duplicateCurve(idx1)

export([filesave, save_altered, ...])

Exports content of Grah object into a human- and machine-readable format.

filenamewithpath(filename)

Returns the absolute path of the file, joining it with the path of the Graph object if necessary.

formatAxisLabel(label)

format_axis_label(label)

Returns a string for label according to user preference.

getAttribute(key[, default])

getAttributes([keys_list])

getCurveData(idx[, ifAltered])

Returns the x and y data of Curve at index idx, as a 2D numpy array.

get_alter()

returns the formatted alter instruction of self

get_attributes([keys_list])

Returns a dict containing the content of both headers and graphInfo

get_list_subclasses_parse()

Sweeps through files in folder datatypes whose filename start with 'curve' or 'graph'.

has_attr(key)

Check if graph has attribute key

iterCurves()

length()

Returns the number of Curve objects in the list.

merge(other_graph)

Add in a Graph object the content of another Graph object Append Curves, graph metadata copy content only for keys which did not already existed

moveCurveToIndex(idxsource, idxtarget)

plot([filesave, img_format, figsize, ...])

Plot the content of the Graph object.

replaceCurve(new_curve, idx)

replace_labels(old, new)

Modify all labels of the Graph, by replacing 'old' by 'new'

reverseCurves()

swapCurves(idx1, idx2[, relative])

text_add(text, textxy[, textargs])

Adds a text to be annotated in the plot, handling the not-so-nice internal implementation.

text_check_valid()

Call TextHandler.checkValidText, to make sure the text annotation attributes are consistent

text_remove([by_id])

By default, removes the last text annotation in the list (pop)

update(attributes[, if_all])

Update the properties of the Graph object.

updateValuesDictkeys(*args, **kwargs)

Deprecated.

update_values_keys(*values[, keys])

Update the graph using a specific data input, for GUI purposes.

Attributes

AXISLABELS

CONFIG_FILENAME_DEFAULT

CONFIG_FILENAME_FALLBACK

CONFIG_FILES

DEFAULT

FIGSIZE_DEFAULT

FILEIO_DPI

alterListGUI() List[AlterListItem]

Compiles a list of possible data transforms, retrieved from all Curves

append(curve: Curve | Graph | tuple | list, idx=None)

Add into the object list a Curve, a list or Curves, or every Curve in a Graph object. id idx is provided, acts as an insert() function.

apply_template(graph: Graph, also_curves=True)

Apply a template to the Graph object. The template is a Graph object which contains:

  • self.get_attributes listed in KEYWORDS_GRAPH[“keys”]

  • self[i].get_attributes listed in KEYWORDS_CURVE[“keys”]

Parameters:

also_curves – True also apply Curves properties, False only apply Graph properties

attr(key: str, default: Any = '') Any

Retrieve an attribute value in header, graphInfo or in curve[0]

attr_pop(key: str)

Delete an attribute of the Graph, and return its value

castCurve(newtype: str, idx: int, silentSuccess=False)

Deprecated. Use graph.curve_cast() instead. Replace a Curve with another type of Curve with identical data and properties. :meta private:

colorize(colorscale, sameIfEmptyLabel=False, avoidWhite=False, curvesselection=None)

Colorize a graph, by coloring each Curve along a colorscale gradient.

config(key: str, default: Any = '', astype='auto')

Returns the value corresponding to key in the configuration file.

config_all() dict

Returns all key-value pairs in config file, and filename

curve(idx: int) Curve | None

Returns the Curve object at index i in the list. Deprecated. Should use graph[idx] instead :meta private:

curve_cast(new_type: str, idx: int, print_success=False)

Replace a Curve with another type of Curve with identical data and properties.

curve_delete(idx: int | List[int] | Tuple[int])

Delete a Curve at index i from the Graph object.

curve_duplicate(idx)

Duplicate (clone) an existing curve and append it in the curves list.

curve_move_to_index(idx_source, idx_target)

Change the position of a Curve in the list

curve_replace(new_curve: Curve, idx: int)

Update a Curve with a new one.

curves(key: str, value, str_lower: bool = False, str_startswith: bool = False) list

Returns a list of Curves for which curve.attr(key) value (type and value equality)

Parameters:
  • key – the attribute to check. By default, ‘label’.

  • value – the value to test

  • str_lower – if True, performs .lower() onto value and curve.attr(key) before comparison, in case each are str.

  • str_startswith – is both value and the attribute are str, only look at the first characters

Returns:

a list of Curves

curves_reverse()

Reverse the order of the Curves.

curves_swap(idx1, idx2, relative=False)

Exchange the Curves at index idx1 and idx2. For example useful to modify the plot order (and order in the legend)

export(filesave='', save_altered=False, if_template=False, if_compact=True, if_only_labels=False, if_clipboard_export=False)

Exports content of Grah object into a human- and machine-readable format.

filenamewithpath(filename)

Returns the absolute path of the file, joining it with the path of the Graph object if necessary.

format_axis_label(label: str | List[str]) str

Returns a string for label according to user preference. ‘Some quantity [unit]’ may become ‘Some quantify (unit)’ Other possible input is [‘This is a Quantity’, ‘Q’, ‘unit’]

getCurveData(idx, ifAltered=True)

Returns the x and y data of Curve at index idx, as a 2D numpy array. :meta private:

get_alter()

returns the formatted alter instruction of self

get_attributes(keys_list: list | None = None) dict

Returns a dict containing the content of both headers and graphInfo

classmethod get_list_subclasses_parse()

Sweeps through files in folder datatypes whose filename start with ‘curve’ or ‘graph’. Therefore compiles all possible user-created Curve and Graph subclasses for e.g. curve type cast. Returns the child classes of Graph which have implemented the methods required to parse files “isFileReadable”, “readDataFromFile”, and class attribute FILEIO_GRAPHTYPE.

has_attr(key: str)

Check if graph has attribute key

merge(other_graph: Graph)

Add in a Graph object the content of another Graph object Append Curves, graph metadata copy content only for keys which did not already existed

plot(filesave='', img_format='', figsize=(0, 0), if_save: bool | str = 'auto', if_export: bool | str = 'auto', fig_ax: list | None = None, if_subplot: bool | str = 'auto', figure_factory: MplFigureFactory | None = None) Tuple[Figure, List[Axes]]

Plot the content of the Graph object.

Parameters:
  • filesave – filename for the saved graph image and export text file.

  • img_format – by default image format will be .png. Possible formats are the ones supported by matplotlib Figure.savefig() and possibly .emf

  • figsize – figure size in inch. The actual default value is from a class constant

  • if_save – [True/False/’auto’] if True, save the Graph as an image. If left to default, saves the image only if filesave is provided

  • if_export – [True/False/’auto’] if True, create a human- and machine- readable .txt file containing all information of the graph. By default, export only if filesave is provided.

  • fig_ax – [fig, ax]. the graph will be plotted in the provided figure and ax. Providing None or [fig, None] will erase all existing axes and create what is needed

  • if_subplot – [True/False/’auto’] If True, prevents deletion of the existing axes in the figure. By default, keeps axes if axes are provided in figAx.

replace_labels(old, new)

Modify all labels of the Graph, by replacing ‘old’ by ‘new’

text_add(text, textxy, textargs=None)

Adds a text to be annotated in the plot, handling the not-so-nice internal implementation.

Parameters:
  • text – as single element, or as list (1 item per annotation)

  • textxy – as single element, or as list (1 item per annotation)

  • textargs – as single element, or as list (1 item per annotation)

Returns:

initial values of self.attr(“text”), “textxy”, “textargs”

text_check_valid()

Call TextHandler.checkValidText, to make sure the text annotation attributes are consistent

text_remove(by_id=-1)

By default, removes the last text annotation in the list (pop)

Parameters:

by_id – index of the annotation to remove

Returns:

a dict with initial text values, prior to removal (use case: restore)

update(attributes: dict, if_all=False) None

Update the properties of the Graph object. The properties are stored in dict objects, so update works similarly as the dict.update() method. If a property is not known to belong to the Graph object, it is attributed to the 1st Curve object (unless if_all=True)

update_values_keys(*values, keys: list | None = None)

Update the graph using a specific data input, for GUI purposes. Falls back onto ({key1: value1, key2: value2, …}). Mandatory: len(args) == len(kwargs[“keys”]).

Parameters:
  • values – value1, value2, …

  • kwargs – key=[‘key1’, ‘key2’, …]