Skip to content

Commit

Permalink
fix title and class
Browse files Browse the repository at this point in the history
  • Loading branch information
wanghui5801 committed Nov 27, 2024
1 parent 6f2c254 commit c6a911a
Show file tree
Hide file tree
Showing 69 changed files with 372 additions and 501 deletions.
5 changes: 4 additions & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ Imports:
stats,
corrplot,
graphics,
plot3D
plot3D,
ggplot2,
gridExtra,
grid
Encoding: UTF-8
LazyData: true
Roxygen: list(markdown = TRUE)
Expand Down
13 changes: 8 additions & 5 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
# Generated by roxygen2: do not edit by hand

S3method(plot,pc_fit)
S3method(plot_components,pc_fit)
S3method(plot_total,pc_fit)
S3method(print,pc_fit)
S3method(summary,pc_fit)
export(convertSignatureToValue)
export(convertSignatureToValueOutOfSample)
export(dataBank)
export(distanceMatrix)
export(distanceVector)
export(fillPCMatrix)
export(firstCausalityPoint)
export(firstCausalityPointCHECK)
export(metricDistance)
export(natureOfCausality)
export(optimalParametersSearch)
export(pastNNsInfo)
export(pastNNsInfo_Lite)
export(patternHashing)
export(patternSpace)
export(pcAccuracy)
Expand All @@ -21,13 +22,15 @@ export(pcEffect)
export(pcFullDetails)
export(pcLightweight)
export(pcMatrix)
export(pc_fit)
export(plotCV)
export(plotEffect)
export(plotMatrix)
export(plotState)
export(plot_components)
export(plot_total)
export(predictionY)
export(projectedNNsInfo)
export(projectedNNsInfo_Lite)
export(signatureSpace)
export(stateSpace)
importFrom(corrplot,COL1)
Expand Down
2 changes: 1 addition & 1 deletion R/PC.Mk.II.Full.Details.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' @title Pattern Causality Mark II: Full Details
#' @title Get Full Pattern Causality Details
#' @description Implements an advanced pattern causality algorithm to explore the causal relationships between two time series datasets. This function reconstructs state spaces, calculates distances, and evaluates causality using predefined metrics and pattern analysis. The methodology supports complex system analysis where traditional linear methods fall short.
#' @param X Numeric vector, the first time series data.
#' @param Y Numeric vector, the second time series data.
Expand Down
11 changes: 9 additions & 2 deletions R/PC.Mk.II.Lightweight.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' @title Pattern Causality Lightweight Function
#' @title Calculate Lightweight Pattern Causality
#' @description This function implements the Pattern Causality Model Mk. II for lightweight analysis of causal interactions between two time series using pattern and signature spaces. It assesses causality through reconstructed state spaces and hashed pattern analysis.
#' @param X A numeric vector representing the first time series.
#' @param Y A numeric vector representing the second time series.
Expand Down Expand Up @@ -100,5 +100,12 @@ pcLightweight <- function(X, Y, E, tau, metric, h, weighted, tpb=TRUE) {
negaCausPercent <- mean(ifelse(causality$noCausality[real_loop] != 1, causality$Negative[real_loop], NA), na.rm = T)
darkCausPercent <- mean(ifelse(causality$noCausality[real_loop] != 1, causality$Dark[real_loop], NA), na.rm = T)
# return(list(causality,totalCausPercent,posiCausPercent,negaCausPercent,darkCausPercent))
return(data.frame(total = totalCausPercent, positive = posiCausPercent, negative = negaCausPercent, dark = darkCausPercent))
result <- pc_fit(
total = totalCausPercent,
positive = posiCausPercent,
negative = negaCausPercent,
dark = darkCausPercent
)

return(result)
}
138 changes: 138 additions & 0 deletions R/classes.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
#' Plot Total Causality
#'
#' @param x An object
#' @param ... Additional arguments
#' @export
plot_total <- function(x, ...) {
UseMethod("plot_total")
}

#' Plot Causality Components
#'
#' @param x An object
#' @param ... Additional arguments
#' @export
plot_components <- function(x, ...) {
UseMethod("plot_components")
}

#' Pattern Causality Fit Object
#'
#' @description Create a pattern causality fit object
#' @param total Total causality strength
#' @param positive Positive causality strength
#' @param negative Negative causality strength
#' @param dark Dark causality strength
#' @return An object of class "pc_fit"
#' @export
pc_fit <- function(total = NULL, positive = NULL, negative = NULL, dark = NULL) {
structure(
list(
total = total,
positive = positive,
negative = negative,
dark = dark
),
class = "pc_fit"
)
}

#' Print Pattern Causality Results
#'
#' @param x A pc_fit object
#' @param ... Additional arguments passed to print
#' @return Invisibly returns the input object
#' @export
#' @method print pc_fit
print.pc_fit <- function(x, ...) {
cat("Pattern Causality Analysis Results:\n")
cat(sprintf("Total: %.4f\n", x$total))
cat(sprintf("Positive: %.4f\n", x$positive))
cat(sprintf("Negative: %.4f\n", x$negative))
cat(sprintf("Dark: %.4f\n", x$dark))
invisible(x)
}

#' Summarize Pattern Causality Results
#'
#' @param object A pc_fit object
#' @param ... Additional arguments passed to summary
#' @return Invisibly returns the input object
#' @export
#' @method summary pc_fit
summary.pc_fit <- function(object, ...) {
cat("Pattern Causality Summary:\n\n")
cat("Causality Strengths:\n")
res <- data.frame(
Type = c("Total", "Positive", "Negative", "Dark"),
Value = c(object$total, object$positive, object$negative, object$dark)
)
print(res)
invisible(object)
}

#' Plot Total Causality
#'
#' @param x A pc_fit object
#' @param ... Additional arguments passed to plotting functions
#' @return A ggplot object
#' @export
#' @method plot_total pc_fit
plot_total.pc_fit <- function(x, ...) {
df1 <- data.frame(
name = c("Non-causal", "Causal"),
value = c(1 - x$total, x$total)
)

ggplot2::ggplot(df1, ggplot2::aes(x = name, y = value, fill = name)) +
ggplot2::geom_bar(stat = "identity", width = 0.4) +
ggplot2::scale_fill_manual(values = c("grey80", "grey20")) +
ggplot2::labs(x = "", y = "Strength") +
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "none")
}

#' Plot Causality Components
#'
#' @param x A pc_fit object
#' @param ... Additional arguments passed to plotting functions
#' @return A ggplot object
#' @export
#' @method plot_components pc_fit
plot_components.pc_fit <- function(x, ...) {
df2 <- data.frame(
name = c("Positive", "Negative", "Dark"),
value = c(x$positive, x$negative, x$dark),
color = c("#5BA3CF", "#F6583E", "#6A51A3")
)

ggplot2::ggplot(df2, ggplot2::aes(x = name, y = value, fill = name)) +
ggplot2::geom_bar(stat = "identity", width = 0.4) +
ggplot2::scale_fill_manual(values = df2$color) +
ggplot2::labs(x = "", y = "Strength") +
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "none")
}

#' Plot Pattern Causality Results
#'
#' @param x A pc_fit object
#' @param ... Additional arguments passed to plotting functions
#' @return A list of two ggplot objects
#' @export
#' @method plot pc_fit
plot.pc_fit <- function(x, ...) {
# 创建两个图形对象
p1 <- plot_total.pc_fit(x)
p2 <- plot_components.pc_fit(x)

# 使用 gridExtra 包的 arrangeGrob 函数来组合图形
combined_plot <- gridExtra::arrangeGrob(p1, p2, ncol = 2)

# 在新的设备上显示组合后的图形
grid::grid.newpage()
grid::grid.draw(combined_plot)

# 返回图形对象列表
invisible(list(total = p1, components = p2))
}
5 changes: 2 additions & 3 deletions R/convertSignatureToValue.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#' Convert Signature to Predicted Values
#'
#' This function calculates predicted values of a series based on its previous value and predicted signature changes. It starts with an initial value from a historical series and sequentially adds predicted signature changes to generate a sequence of predicted values.
#' @title Convert Signature to Value
#' @description This function calculates predicted values of a series based on its previous value and predicted signature changes. It starts with an initial value from a historical series and sequentially adds predicted signature changes to generate a sequence of predicted values.
#'
#' @param E Integer, the length of the series for which predictions are needed.
#' @param tau Integer, the time delay used in the system dynamics (not used in this function but typically relevant in the broader context of time series prediction).
Expand Down
37 changes: 0 additions & 37 deletions R/convertSignatureToValueOutOfSample.R

This file was deleted.

17 changes: 6 additions & 11 deletions R/data.R
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
#' Climate index
#'
#' This is a time series of climate index.
#'
#' @title Climate Index
#' @description This is a time series of climate index.
#'
#' @examples
#' head(climate_indices)
"climate_indices"

#' Dow Jones stock price
#'
#' It includes 29 time series of stock series in Dow Jones.
#' @title Dow Jones Stock Price
#' @description It includes 29 time series of stock series in Dow Jones.
#'
#'
#' @examples
#' head(DJS)
"DJS"

#' A data from Illapel
#'
#' Raw rodent and rainfall data from the study site at Las Chinchillas National Reserve near the city of Illapel, Coquimbo Region of Chil.
#'
#' @title A data from Illapel
#' @description Raw rodent and rainfall data from the study site at Las Chinchillas National Reserve near the city of Illapel, Coquimbo Region of Chil.
#'
#' @examples
#' head(AUCO)
Expand Down
2 changes: 1 addition & 1 deletion R/dataBank.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' @title Data Bank Initialization Function
#' @title Create Data Bank
#' @description Initializes various data structures for storing and managing data within a complex systems analysis framework.
#
#' @param type A character string specifying the type of data structure to initialize: "array", "vector", "matrix", or
Expand Down
51 changes: 3 additions & 48 deletions R/distanceMatrix.R
Original file line number Diff line number Diff line change
@@ -1,63 +1,18 @@
#' Compute Distance Matrix for an Embedded Matrix
#' @title Calculate Distance Matrix
#'
#' This function computes the distance matrix from a given embedded matrix, `M`, using a specified metric. The distance matrix is essential for exploring the underlying structure in complex systems by quantifying the distances between different points (or states) in the embedded space. This matrix can be crucial for further analysis like clustering, nearest neighbor searches, or causality inference in complex systems.
#' @description This function computes the distance matrix from a given embedded matrix, `M`, using a specified metric. The distance matrix is essential for exploring the underlying structure in complex systems by quantifying the distances between different points (or states) in the embedded space. This matrix can be crucial for further analysis like clustering, nearest neighbor searches, or causality inference in complex systems.
#'
#' @param M Numeric matrix, the embedded state space matrix where each row represents a point in the reconstructed state space of a time series or any multidimensional data.
#' @param metric Character, the distance metric to be used for computing distances. Common metrics include "euclidean", "maximum", "manhattan", "canberra", "binary" or "minkowski".
#'
#' @return An object of class `dist`, representing the distance matrix of the embedded matrix `M`. This distance matrix can optionally be converted to a full matrix format if needed for subsequent analyses.
#' @export
#' @examples
#' # Assume M is an already constructed state space matrix of a time series
#' M <- matrix(rnorm(100), nrow = 10)
#' distanceMat <- distanceMatrix(M, "euclidean")
#' print(distanceMat) # Optionally convert to a full matrix for display
distanceMatrix <- function(M, metric) {
# d <- dist(M, metric, upper = TRUE)
d <- as.matrix(stats::dist(M, metric, upper = T))
return(d)
}

#' Calculate Generalized Minkowski Distance Between Two Vectors
#'
#' This function calculates the generalized Minkowski distance of order 'n' between two numeric vectors. This distance is a metric in a normed vector space which generalizes the Euclidean and Manhattan distances. It is used for various data science applications, particularly in clustering, optimization, and outlier detection in complex systems.
#'
#' @param vec1 Numeric vector, the first vector for which the distance will be calculated.
#' @param vec2 Numeric vector, the second vector for which the distance will be calculated.
#' @param n Integer, the order of the Minkowski distance. When n=2, it becomes the Euclidean distance; when n=1, it becomes the Manhattan distance.
#'
#' @return Numeric, the computed Minkowski distance between the two vectors.
#'
#' @export
#' @examples
#' vec1 <- c(1, 2, 3)
#' vec2 <- c(4, 5, 6)
#' n <- 2
#' distance <- metricDistance(vec1, vec2, n)
#' print(distance)
metricDistance <- function(vec1, vec2, n) {
res <- as.numeric(vec1 - vec2)
distance <- (sum(abs(res)^n))^(1 / n)
return(distance)
}

#' Calculate Distances Between a Reference Point and Multiple Candidates
#'
#' This function applies the 'metricDistance' function to calculate distances from a given reference point to each row in a matrix of candidate nearest neighbors. It is particularly useful in the situation between matrix and a vector
#'
#' @param point Numeric vector, the reference point from which distances are calculated.
#' @param candidateNNs Matrix, rows represent candidate points to which distance from the reference point is calculated.
#' @param n Integer, the order of the Minkowski distance to use.
#'
#' @return Numeric vector, distances from the reference point to each of the candidate points.
#'
#' @export
#' @examples
#' point <- c(1, 2, 3)
#' candidateNNs <- matrix(c(4, 5, 6, 7, 8, 9), nrow = 2, byrow = TRUE)
#' n <- 2
#' distances <- distanceVector(point, candidateNNs, n)
#' print(distances)
distanceVector <- function(point, candidateNNs, n) {
apply(X = candidateNNs, MARGIN = 1, FUN = metricDistance, vec2 = point, n = n)
}
}
7 changes: 1 addition & 6 deletions R/fillPCMatrix.R
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
#' Fill Pattern Causality Matrix with Causality Strengths
#' @title Fill Pattern Causality Matrix
#'
#' This function calculates and fills the causality strengths between predicted and real patterns and signatures
#' for a complex system analysis. It evaluates the accuracy of predictions and computes the strength of causal
#' relationships based on norm vectors and optionally weights these strengths using the error function (erf).
#'
#' @title Calculate and Record Causality Strengths
#' @description Computes the causality strengths based on the comparison between predicted and real patterns
#' and signatures in a system's dynamic model. It applies a normalization function to measure the intensity of
#' causal influences and uses an error function for weighting if required.
Expand Down
2 changes: 1 addition & 1 deletion R/firstCausalityPoint.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' @title First Causality Point Function
#' @title Find First Causality Point
#' @description Calculates the earliest index in a time series from which causality analysis can begin,
#' based on the embedding dimension, time delay, prediction horizon, and the length of the series. It ensures
#' that there are enough data points for conducting a causality analysis without running out of data.
Expand Down
2 changes: 1 addition & 1 deletion R/firstCausalityPointCHECK.R
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#' @title First Causality Point Check Function
#' @title Check First Causality Point
#' @description Checks if the time series data length is sufficient to perform causality analysis based on
#' the provided embedding dimension, time delay, and prediction horizon. This function returns a Boolean
#' indicating the feasibility of conducting the analysis.
Expand Down
Loading

0 comments on commit c6a911a

Please sign in to comment.