Skip to content
Snippets Groups Projects
Commit 34688ec8 authored by Hock, Martin's avatar Hock, Martin
Browse files

Merge branch 'matplotlib' into 'dev'

Implement basic function to switch between plot engines.

See merge request !1
parents e8dde521 e14c4147
Branches
Tags
2 merge requests!12v.0.1 for alpha release,!1Implement basic function to switch between plot engines.
...@@ -90,7 +90,7 @@ celerybeat-schedule ...@@ -90,7 +90,7 @@ celerybeat-schedule
# Environments # Environments
.env .env
.venv .venv
env/ env*/
venv/ venv/
ENV/ ENV/
env.bak/ env.bak/
......
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 10:09:46 2021
@author: Richter
"""
#%% Test
a = 1
b = 2
print(a+b)
print(a-b)
\ No newline at end of file
# -*- coding: utf-8 -*-
import time
import uuid
def CreateID(method):
"""
Create an Identifier (str).
Creates an (sometimes unique) identifier based on the selected method
if no method is selected method 1 will be the default method
Returns
-------
ID
"""
if method == 1:
ID = time.time() # UNIX Time
ID = hex(int(ID)) # convert time to hexadecimal
time.sleep(0.5) # break for avoiding duplicate IDs
elif method == 2:
ID = str(uuid.uuid4()) # creates a random UUID
ID = ID[0:8] # only use first 8 numbers
else:
raise ValueError(
f'Your chosen ID method "{method}" is not supported.\n'
'At the moment these methods are available:\n'
'"1": Unix time converted to hexadecimal\n'
'"2": Random UUID')
return ID
# plot_ID_python # plot_ID_python
This is the python PlotID project This is the python PlotID project.
\ No newline at end of file
To run the program python version 3.10 is required.
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from TagPlot_matplotlib import TagPlot_matplotlib
import warnings
def TagPlot(figs, engine, prefix='', method=1, location='east'):
"""
Determine which plot engine should be used to tag the plots.
After determining the engine, TagPlot calls the corresponding
function which tags the plot.
Parameters
----------
figs : list
Figures that should be tagged.
prefix : string
Will be added as prefix to the ID.
engine : string
Plot engine which should be used to tag the plot.
method : int, optional
Method for creating the ID. Create an ID by Unix time is referenced
as 1, create a random ID with method=2. The default is 1.
location : string, optional
Location for ID to be displayed on the plot. Default is 'east'.
Raises
------
RuntimeWarning
DESCRIPTION.
Returns
-------
list
The resulting list contains two lists each with as many entries as
figures were given. The first list contains the tagged figures.
The second list contains the corresponding IDs as strings.
"""
# %% Validate inputs
if isinstance(prefix, str):
pass
else:
raise TypeError("Prefix is not a string.")
if isinstance(figs, list):
pass
else:
raise TypeError("Figures are not a list.")
# TODO: Rename method to more specific name (maybe id_method?).
# TODO: Change method key from integer to (more meaningful) string.
try:
method = int(method)
except ValueError:
raise TypeError('The chosen ID method is not an integer.')
if isinstance(location, str):
pass
else:
raise TypeError("Location is not a string.")
# TODO: Implement backwards combatibility with if-clauses
match location:
case 'north':
rotation = 0
position = (0.35, 0.975)
case 'east':
rotation = 90
position = (0.975, 0.35)
case 'south':
rotation = 0
position = (0.35, 0.015)
case 'west':
rotation = 90
position = (0.025, 0.35)
case 'southeast':
rotation = 0
position = (0.75, 0.015)
case 'custom':
# TODO: Get rotation and position from user input & check if valid
rotation = 0
position = (0.5, 0.5)
case _:
warnings.warn(f'Location "{location}" is not a defined location,'
' TagPlot uses location "east" instead.')
rotation = 90
position = (0.975, 0.35)
if engine == 'matplotlib' or engine == 'pyplot':
return TagPlot_matplotlib(figs, prefix, method, rotation, position)
else:
raise ValueError(f'The plot engine "{engine}" is not supported.')
# Following code only works for python >= 3.10
# match engine:
# case 'matplotlib' | 'pyplot':
# return TagPlot_matplotlib(figs, prefix, method)
# case _:
# raise ValueError(
# f'The plot engine "{engine}" is not supported.')
# -*- coding: utf-8 -*-
import CreateID
# from fcn_help.FST_colors import Colors
import matplotlib.pyplot as plt
import matplotlib
# plt.style.use('./fcn_help/FST.mplstyle')
def TagPlot_matplotlib(figs, prefix, method, rotation, position):
"""
Add IDs to figures with matplotlib.
The ID is placed visual on the figure window and
as Tag (Property of figure).
TagPlot can tag multiple figures at once
"""
# Check if figs is a valid figure or a list of valid figures
if isinstance(figs, matplotlib.figure.Figure):
pass
elif isinstance(figs, list):
for i in range(len(figs)):
if isinstance(figs[i], matplotlib.figure.Figure):
pass
else:
raise TypeError('Figure is not a valid matplotlib-figure.')
FONTSIZE = 'small'
COLOR = 'grey'
IDs = []
# Loop to create and position the IDs
for fig in figs:
ID = CreateID.CreateID(method)
ID = prefix + str(ID)
IDs.append(ID)
plt.figure(fig.number)
plt.figtext(x=position[0], y=position[1], s=ID, ha='left', wrap=True,
rotation=rotation, fontsize=FONTSIZE, color=COLOR)
fig.tight_layout()
return [figs, IDs]
Image diff could not be displayed: it is too large. Options to address this: view the blob.
Image diff could not be displayed: it is too large. Options to address this: view the blob.
...@@ -4,68 +4,62 @@ Created on Tue Jul 20 12:22:33 2021 ...@@ -4,68 +4,62 @@ Created on Tue Jul 20 12:22:33 2021
example workflow for integrating plotIDs example workflow for integrating plotIDs
@author: Richter @author: Richter
""" """
#%% Code und Konsole aufräumen
%reset
%matplotlib
%clear
# %% Module einbinden # %% Module einbinden
import sys import sys
import numpy as np import numpy as np
from numpy import random from numpy import random
import h5py as h5 # import h5py as h5
import matplotlib # import matplotlib
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
from TagPlot import TagPlot
from fcn_help.FST_colors import Colors
plt.style.use('fcn_help/FST.mplstyle') plt.style.use('fcn_help/FST.mplstyle')
%matplotlib qt # %matplotlib qt
# %matplotlib inline # %matplotlib inline
from FST_colors import Colors
from TagPlot import TagPlot
# %% Pfade hinzufügen # %% Pfade hinzufügen
sys.path.append("fcn_core") sys.path.append("fcn_core")
sys.path.append("fcn_help") sys.path.append("fcn_help")
# %% Project ID # %% Project ID
ProjectID= "MR01" ProjectID = "MR04_"
#%% Daten erzeugen # %% Plot engine
plot_engine = "matplotlib"
# %% Create sample data
x = np.linspace(0, 10, 100) x = np.linspace(0, 10, 100)
y = random.rand(100) + 2 y = random.rand(100) + 2
y_2 = np.sin(x) + 2 y_2 = np.sin(x) + 2
#%% Daten speichern # %% Create figure
dataset1 = "test_data.npy" # Colors
np.save(dataset1, x,y, y_2)
#%% figure erstellen
# Farben
colors = Colors() # create instance from class colors = Colors() # create instance from class
color_list = colors.get_color_names() color_list = colors.get_color_names()
# Plot erstellen # Create plot
color1 = colors.get_rgb('black') color1 = colors.get_rgb('black')
color2 = colors.get_rgb('yellow') color2 = colors.get_rgb('yellow')
# 1.Figure # 1.Figure
fig1 = plt.figure() fig1 = plt.figure()
plt.plot(x, y, color=color1) plt.plot(x, y, color=color1)
plt.plot(x, y_2, color=color2) plt.plot(x, y_2, color=color2)
#plt.draw()
# 2.Figure # 2.Figure
plt.clf #Figure schließen plt.clf # Close figure
fig2 = plt.figure() fig2 = plt.figure()
plt.plot(x, y, color=color2) plt.plot(x, y, color=color2)
plt.plot(x, y_2, color=color1) plt.plot(x, y_2, color=color1)
#plt.draw() plt.clf # Close figure
plt.clf #Figure schließen
fig = [fig1, fig2] fig = [fig1, fig2]
#%% TagPlot
[figs, ID] = TagPlot(fig, ProjectID)
# %% TagPlot
[figs, ID] = TagPlot(fig, plot_engine, prefix=ProjectID,
method='2', location='west')
# %% Figure als tiff-Datei abspeichern # %% Figure als tiff-Datei abspeichern
for i in range(len(figs)): for i, figure in enumerate(figs):
name = "Test"+str(i)+".tiff" name = "Test"+str(i)+".tiff"
figs[i].savefig(name) figure.savefig(name)
File moved
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 17:02:27 2021
CreateID
@author: Richter
"""
#%% Module importieren
import time
import uuid
#%% Funktion
def CreateID(method):
"""
% CreateID Creates an Identifier (str)
% Creates an (sometimes unique) identifier based on the selected method
% if no method is selected method 1 will be the default method
Returns
-------
ID
"""
if method == 1:
ID = time.time() # UNIX Time
ID = hex(int(ID)) # Hexadezimalzahl
time.sleep(0.5) # Pause
elif method == 2:
ID = str(uuid.uuid4()) # creates a random UUID
ID = ID[0:8] # Verwendung der ersten 8 Ziffern
time.sleep(0.5) # Pause
return ID
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 27 10:50:20 2021
@author: Richter
"""
import matplotlib
import matplotlib.pyplot as plt
plt.style.use('fcn_help/FST.mplstyle')
#%matplotlib qt
#%matplotlib inline
import numpy as np
from FST_colors import Colors
import CreateID
def TagPlot(figs,prefix, *method):
"""
TagPlot adds IDs to figures
The ID is placed visual on the figure window and as Tag (Property of figure)
TagPlot can tag multiple figures at once
"""
#%% Eingaben prüfen
if prefix:
pass
else:
raise RuntimeWarning("no prefix set")
if figs:
pass
else:
raise RuntimeWarning("no figures set")
if method:
method = method
else:
method = 1
pass
#isinstance(figs, t)
#%% Schleife zur Erzeugung und Positionierung der IDs
for i in range(len(figs)):
#print(i)
#CreateID aufrufen
ID = CreateID.CreateID(method)
#ID = prefix + '_' +'Test'+str(i)
ID = prefix + '_' + str(ID)
#print(ID)
fig =figs[i]
#print(type(fig))
plt.figure(fig.number)
x_lim = plt.xlim()
y_lim = plt.ylim()
y_mitte = 0.4*(y_lim[1]+y_lim[0])
plt.text(x = x_lim[1], y = y_mitte, s = ID, ha='left',
rotation='vertical', fontsize = "small", wrap=True, color = "grey")
fig.tight_layout()
#plt.draw()
#%% Rückgabewerte
return(figs, ID)
\ No newline at end of file
File moved
matplotlib == 3.5.1
File moved
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 23 10:09:46 2021
@author: Richter
"""
#%% Test
a = 1
b = 2
print(a+b)
print(a-b)
\ No newline at end of file
File added
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Unittests for CreateID
'''
import unittest
import CreateID
class TestCreateID(unittest.TestCase):
def test_existence(self):
self.assertIsInstance(CreateID.CreateID(1), str)
self.assertIsInstance(CreateID.CreateID(2), str)
def test_errors(self):
with self.assertRaises(ValueError):
CreateID.CreateID(3)
with self.assertRaises(ValueError):
CreateID.CreateID('h')
def test_length(self):
self.assertEqual(len(CreateID.CreateID(1)), 10)
self.assertEqual(len(CreateID.CreateID(2)), 8)
if __name__ == '__main__':
unittest.main()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment