Skip to content

Commit

Permalink
Refactor the structure of code
Browse files Browse the repository at this point in the history
  • Loading branch information
hasanisaeed committed Nov 15, 2024
1 parent d17dc67 commit c33d931
Show file tree
Hide file tree
Showing 7 changed files with 127 additions and 97 deletions.
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
The Academic License

Copyright (c) [2020] [Saeed Hasani Borzadaran]
Copyright (c) [2020] [Saeed Hasani]

This project includes academic-research code and documents under development.
You would be a fool to run any of the code.
Expand Down
39 changes: 35 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,45 @@
# Recurrence Plot
[Recurrence Plot](https://en.wikipedia.org/wiki/Recurrence_plot) – A recurrence plot (RP) is an advanced technique of **nonlinear** data analysis. It is a visualisation (or a graph) of a square matrix, in which the matrix elements correspond to those times at which a state of a dynamical system recurs (columns and rows correspond then to a certain pair of times).

# Result
## Result
![](results/1D_to_2D.jpg)

# Usage
## Usage
**1. Install requirements:**

Ensure you have Python 3 installed. Install the required dependencies using:


pip install -r requirements.txt

**2. Run `main.py` script:**
**2. Run `example.py` script:**

python3 example.py # or python example.py

This will:

- Generate a random signal.
- Smooth the signal using a moving average filter.
- Compute and visualize the recurrence plot.
- Save the resulting plot as results/1D_to_2D.jpg.

----
## How to Use the recurrence Package

If you want to use the recurrence package in your own projects:

1) **Import the Required Modules:**

For recurrence plot functions, import from recurrence.plotting.
For signal processing utilities, import from recurrence.convolve.

Example:

```python
from recurrence.plotting import setup_plot, save_plot
from recurrence.convolve import calculate_convolve
```

python3 main.py
2) **Process Your Signal:**

Use `calculate_convolve` to smooth your input signal, then use the `setup_plot` and `save_plot` functions to generate and save recurrence plots.
30 changes: 30 additions & 0 deletions example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import matplotlib.pyplot as plt
import numpy as np
from recurrence.plotting import setup_plot, save_plot
from recurrence.convolve import calculate_convolve

if __name__ == "__main__":
# Example usage
fig = plt.figure(figsize=(8, 2))

# Configuration
row, col = 1, 2
size = f"{row}{col}"

# Generate raw signal
raw_signal = np.random.uniform(-1, 1, 50)

# Process the signal
convolved_signal = calculate_convolve(raw_signal)

# Plot signals and recurrence plot
setup_plot(
signal=convolved_signal,
size=size,
cell=1,
signal_name='Input Signal',
image_name='2D Image of Signal'
)

# Save the plot
save_plot(filepath='results/1D_to_2D.jpg')
92 changes: 0 additions & 92 deletions main.py

This file was deleted.

Empty file added recurrence/__init__.py
Empty file.
File renamed without changes.
61 changes: 61 additions & 0 deletions recurrence/plotting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import pdist, squareform

# ----------------- Plot config --------------------------------------- #
SMALL = 8
MEDIUM = 10
BIGGER = 11

plt.rc('font', size=SMALL) # controls default text sizes
plt.rc('axes', titlesize=SMALL) # font size of the axes title
plt.rc('axes', labelsize=MEDIUM) # font size of the x and y labels
plt.rc('xtick', labelsize=SMALL) # font size of the tick labels
plt.rc('ytick', labelsize=SMALL) # font size of the tick labels
plt.rc('legend', fontsize=SMALL) # legend font size
plt.rc('figure', titlesize=BIGGER) # font size of the figure title

plt.rcParams["font.family"] = "Times", "Times New Roman", "serif"

# --------------------------------------------------------------------- #

def save_plot(filepath='results/1D_to_2D.jpg'):
"""Adjust and save the plot."""
left = 0.2
right = 0.9
bottom = 0.1
top = 0.9
wspace = 0.2
hspace = 0.1

plt.subplots_adjust(left, bottom, right, top, wspace, hspace)
plt.savefig(filepath, bbox_inches='tight')

def recurrence_plot(signal, eps=0.10, steps=3):
"""Generate a recurrence plot from a 1D signal."""
_2d_array = signal[:, None]
distance = pdist(_2d_array)
distance = np.floor(distance / eps)
distance[distance > steps] = steps
return squareform(distance)

def subplot(x, size, cell, is_signal=True, title=None, grid=True):
"""Create a subplot for the signal or image."""
ax = plt.subplot(int(f"{size}{cell}"))
ax.grid(color='gray', linestyle='dotted', linewidth=0.5)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

if is_signal:
plt.plot(x, 'm', linewidth=1)
else:
plt.imshow(x)

plt.title(title)
plt.grid(grid)

def setup_plot(signal, size, cell, signal_name='Raw Signal', image_name='2D Image'):
"""Set up and display the plot for the signal and its recurrence plot."""
subplot(signal, size=size, cell=cell, is_signal=True, title=signal_name)
rp = recurrence_plot(signal)
subplot(rp, size=size, cell=cell + 1, is_signal=False, title=image_name)

0 comments on commit c33d931

Please sign in to comment.