  filter.class = function(x, type) {

    # sex codes
    male = 0
    female = 1
    sex.unknown = 2

    # maturity codes
    immature = 0
    mature = 1
    mat.unknown = 2

    i=NULL

    if (type=="all") i = c(1:dim(x)[1])

    if (type=="mat")  i = which(x$mat==mature)
    if (type=="imm")  i = which(x$mat==immature)

    if (type=="male")  i = which(x$sex==male)
    if (type=="female")  i = which(x$sex==female)

    if (type=="m.mat")  i = which(x$sex==male & x$mat==mature)
    if (type=="m.imm")  i = which(x$sex==male & x$mat==immature)

    if (type=="m.com")  i = which(x$sex==male & x$cw>=95 & x$cw<200 )  # commerical size crab
    if (type=="m.ncom") i = which(x$sex==male & x$cw< 95 )

    if (type=="R0") { # "fishable" biomass (by sex, size, carapace condition and shell hardness) -- mature only
      i = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 &  x$shell %in% c(3,4) )
      j = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 &  x$shell==2 & x$durometer>=68 )
      k = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 & !is.finite(x$shell) & x$durometer>=68)
      i = sort(unique(c(i,j,k)))
      # i = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 & x$shell %in% c(3,4,5) )
    }

    if (type=="R1"){  # terminally moulted soft-shells (new recruits), mature only
      i = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 &  x$shell==1 )
      j = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 &  x$shell==2 & x$durometer<68 )
      k = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 & !is.finite(x$shell) & x$durometer<68)
      i = sort(unique(c(i,j,k)))
      # i = which(x$sex==male & x$mat==mature & x$cw>=95 & x$cw<200 & x$shell %in% c(1,2) )
    }

    if (type=="R2") i = which(x$sex==male & x$mat==immature & x$cw>=mb(8) & x$cw<95 )
    if (type=="R3") i = which(x$sex==male & x$mat==immature & x$cw>=mb(7) & x$cw<mb(8) )
    if (type=="R4") i = which(x$sex==male & x$mat==immature & x$cw<=mb(6) & x$cw<mb(7))
    if (type=="R5p") i = which(x$sex==male & x$mat==immature & x$cw<=mb(5) & x$cw<mb(6))

    if (type=="skip.moulter") i = which(x$sex==male & x$mat==immature & x$cw<=200 & (x$shell %in% c(3,4,5) ) )
    if (type=="m.dwarf") i = which(x$sex==male & x$mat==mature & x$cw<95 )

    if (type=="mi123") i = which(x$sex==male & x$mat==immature & x$cw<mb(1) )
    if (type=="mi4") i = which(x$sex==male & x$mat==immature & x$cw>=mb(1) & x$cw<mb(2))
    if (type=="mi5") i = which(x$sex==male & x$mat==immature & x$cw>=mb(2) & x$cw<mb(3)) # poor data beyond this point
    if (type=="mi6") i = which(x$sex==male & x$mat==immature & x$cw>=mb(3) & x$cw<mb(4)) # R7
    if (type=="mi7") i = which(x$sex==male & x$mat==immature & x$cw>=mb(4) & x$cw<mb(5)) # R6
    if (type=="mi8") i = which(x$sex==male & x$mat==immature & x$cw>=mb(5) & x$cw<mb(6)) # R5
    if (type=="mi9") i = which(x$sex==male & x$mat==immature & x$cw>=mb(6) & x$cw<mb(7)) # R4
    if (type=="mi10") i = which(x$sex==male & x$mat==immature & x$cw>=mb(7) & x$cw<mb(8)) # same as "R3"
    if (type=="mi11") i = which(x$sex==male & x$mat==immature & x$cw>=mb(8) & x$cw<mb(9)) # R0, R1 and R2
    if (type=="mi12") i = which(x$sex==male & x$mat==immature & x$cw>=mb(9) & x$cw<mb(10))# R0

    if (type=="mi9.skip.moulter") i = which(x$sex==male & x$mat==immature & x$cw>=mb(6) & x$cw<mb(7) & x$shell %in% c(3,4,5) ) # R4/5
    if (type=="mi10.skip.moulter") i = which(x$sex==male & x$mat==immature & x$cw>=mb(7) & x$cw<mb(8) & x$shell %in% c(3,4,5) ) # same as "R3/4"
    if (type=="mi11.skip.moulter") i = which(x$sex==male & x$mat==immature & x$cw>=mb(8) & x$cw<mb(9) & x$shell %in% c(3,4,5) ) # R0/1, R1/2 and R2/3
    if (type=="mi12.skip.moulter") i = which(x$sex==male & x$mat==immature & x$cw>=mb(9) & x$cw<mb(10) & x$shell %in% c(3,4,5) ) # R0/1

    if (type=="ma9") i = which(x$sex==male & x$mat==mature & x$cw>=mb(6) & x$cw<mb(7)) # dwarves
    if (type=="ma10") i = which(x$sex==male & x$mat==mature & x$cw>=mb(7) & x$cw<mb(8)) # dwarves
    if (type=="ma11") i = which(x$sex==male & x$mat==mature & x$cw>=mb(8) & x$cw<mb(9)) # mostly dwarves
    if (type=="ma12") i = which(x$sex==male & x$mat==mature & x$cw>=mb(9) & x$cw<mb(10))
    if (type=="ma13") i = which(x$sex==male & x$mat==mature & x$cw>=mb(10) )

    if (type=="ma9.CC1to2") i = which(x$sex==male & x$mat==mature & x$cw>=mb(6) & x$cw<mb(7) & (x$shell %in% c(1,2) ) )
    if (type=="ma10.CC1to2") i = which(x$sex==male & x$mat==mature & x$cw>=mb(7) & x$cw<mb(8) & (x$shell %in% c(1,2) ) )
    if (type=="ma11.CC1to2") i = which(x$sex==male & x$mat==mature & x$cw>=mb(8) & x$cw<mb(9) & (x$shell %in% c(1,2) ) )
    if (type=="ma12.CC1to2") i = which(x$sex==male & x$mat==mature & x$cw>=mb(9) & x$cw<mb(10) & (x$shell %in% c(1,2) ) )
    if (type=="ma13.CC1to2") i = which(x$sex==male & x$mat==mature & x$cw>=mb(10) & (x$shell %in% c(1,2) ) )

    if (type=="ma9.CC3to4") i = which(x$sex==male & x$mat==mature & x$cw>=mb(6) & x$cw<mb(7) & x$shell %in% c(3,4) )
    if (type=="ma10.CC3to4") i = which(x$sex==male & x$mat==mature & x$cw>=mb(7) & x$cw<mb(8) & x$shell %in% c(3,4) )
    if (type=="ma11.CC3to4") i = which(x$sex==male & x$mat==mature & x$cw>=mb(8) & x$cw<mb(9) & x$shell %in% c(3,4) )
    if (type=="ma12.CC3to4") i = which(x$sex==male & x$mat==mature & x$cw>=mb(9)  & x$cw<mb(10) & x$shell %in% c(3,4) )
    if (type=="ma13.CC3to4") i = which(x$sex==male & x$mat==mature & x$cw>=mb(10) & x$shell %in% c(3,4) )

    if (type=="ma9.CC5") i = which(x$sex==male & x$mat==mature & x$cw>=mb(6) & x$cw<mb(7) & x$shell %in% c(5) )
    if (type=="ma10.CC5") i = which(x$sex==male & x$mat==mature & x$cw>=mb(7) & x$cw<mb(8) & x$shell %in% c(5) )
    if (type=="ma11.CC5") i = which(x$sex==male & x$mat==mature & x$cw>=mb(8) & x$cw<mb(9) & x$shell %in% c(5) )
    if (type=="ma12.CC5") i = which(x$sex==male & x$mat==mature & x$cw>=mb(9) & x$cw<mb(10) & x$shell %in% c(5)  )
    if (type=="ma13.CC5") i = which(x$sex==male & x$mat==mature & x$cw>=mb(10) & x$shell %in% c(5)  )

    if (type=="fi1234") i = which(x$sex==female & x$mat==immature & x$cw<fb(1) )
    if (type=="fi5") i = which(x$sex==female & x$mat==immature & x$cw>=fb(1) & x$cw<fb(2))

    if (type=="fi6") i = which(x$sex==female & x$mat==immature & x$cw>=fb(2) & x$cw<fb(3))
    if (type=="fi7") i = which(x$sex==female & x$mat==immature & x$cw>=fb(3) & x$cw<fb(4))
    if (type=="fi8") i = which(x$sex==female & x$mat==immature & x$cw>=fb(4) & x$cw<fb(5))
    if (type=="fi9") i = which(x$sex==female & x$mat==immature & x$cw>=fb(5) & x$cw<fb(6))
    if (type=="fi10") i = which(x$sex==female & x$mat==immature & x$cw>=fb(6) )

    if (type=="fi6.adolescent") i = which(x$sex==female & x$mat==immature & x$cw>=fb(2) & x$cw<fb(3) & x$gonad<=2)
    if (type=="fi7.adolescent") i = which(x$sex==female & x$mat==immature & x$cw>=fb(3) & x$cw<fb(4) & x$gonad<=2)
    if (type=="fi8.adolescent") i = which(x$sex==female & x$mat==immature & x$cw>=fb(4) & x$cw<fb(5) & x$gonad<=2)
    if (type=="fi9.adolescent") i = which(x$sex==female & x$mat==immature & x$cw>=fb(5) & x$cw<fb(6) & x$gonad<=2)
    if (type=="fi10.adolescent") i = which(x$sex==female & x$mat==immature & x$cw>=fb(6) & x$gonad<=2 )

    if (type=="fi6.preprimiparous") i = which(x$sex==female & x$mat==immature & x$cw>=fb(2) & x$cw<fb(3) & x$gonad==3)
    if (type=="fi7.preprimiparous") i = which(x$sex==female & x$mat==immature & x$cw>=fb(3) & x$cw<fb(4) & x$gonad==3)
    if (type=="fi8.preprimiparous") i = which(x$sex==female & x$mat==immature & x$cw>=fb(4) & x$cw<fb(5) & x$gonad==3)
    if (type=="fi9.preprimiparous") i = which(x$sex==female & x$mat==immature & x$cw>=fb(5) & x$cw<fb(6) & x$gonad==3)
    if (type=="fi10.preprimiparous") i = which(x$sex==female & x$mat==immature & x$cw>=fb(6) & x$gonad==3 )

    if (type=="fa7") i = which(x$sex==female & x$mat==mature & x$cw>=fb(3) & x$cw<fb(4))
    if (type=="fa8") i = which(x$sex==female & x$mat==mature & x$cw>=fb(4) & x$cw<fb(5))
    if (type=="fa9") i = which(x$sex==female & x$mat==mature & x$cw>=fb(5) & x$cw<fb(6))
    if (type=="fa10") i = which(x$sex==female & x$mat==mature & x$cw>=fb(6) )

    if (type=="fa7.berried") i = which(x$sex==female & x$mat==mature & x$cw>=fb(3) & x$cw<fb(4) & x$eggPr %in% c(1:4) )
    if (type=="fa8.berried") i = which(x$sex==female & x$mat==mature & x$cw>=fb(4) & x$cw<fb(5) & x$eggPr %in% c(1:4) )
    if (type=="fa9.berried") i = which(x$sex==female & x$mat==mature & x$cw>=fb(5) & x$cw<fb(6) & x$eggPr %in% c(1:4) )
    if (type=="fa10.berried") i = which(x$sex==female & x$mat==mature & x$cw>=fb(6) & x$eggPr %in% c(1:4)  )

    if (type=="fa7.primiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(3) & x$cw<fb(4) & x$shell<=2  )
    if (type=="fa8.primiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(4) & x$cw<fb(5) & x$shell<=2   )
    if (type=="fa9.primiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(5) & x$cw<fb(6) & x$shell<=2   )
    if (type=="fa10.primiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(6) & x$shell<=2 )

    if (type=="fa7.multiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(3) & x$cw<fb(4) & x$shell>=3  )
    if (type=="fa8.multiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(4) & x$cw<fb(5) & x$shell>=3  )
    if (type=="fa9.multiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(5) & x$cw<fb(6) & x$shell>=3  )
    if (type=="fa10.multiparous") i = which(x$sex==female & x$mat==mature & x$cw>=fb(6) & x$shell>=3   )

    if (type=="fa7.senile") i = which(x$sex==female & x$mat==mature & x$cw>=fb(3) & x$cw<fb(4) & x$shell >=4 & x$eggPr <=1 )
    if (type=="fa8.senile") i = which(x$sex==female & x$mat==mature & x$cw>=fb(4) & x$cw<fb(5) & x$shell >=4 & x$eggPr <=1 )
    if (type=="fa9.senile") i = which(x$sex==female & x$mat==mature & x$cw>=fb(5) & x$cw<fb(6) & x$shell >=4 & x$eggPr <=1 )
    if (type=="fa10.senile") i = which(x$sex==female & x$mat==mature & x$cw>=fb(6) & x$shell >=4 & x$eggPr <=1  )

    if (type=="pre.recruit") i = which(x$sex==male & x$mat==immature & x$cw>56 & x$cw<95)  # Koeller's request

    if (type=="f7" ) i = which(x$sex==female &x$cw>=fb(3) & x$cw<fb(4))
    if (type=="f8" ) i = which(x$sex==female &x$cw>=fb(4) & x$cw<fb(5))
    if (type=="f9" ) i = which(x$sex==female &x$cw>=fb(5) & x$cw<fb(6))
    if (type=="f10" ) i = which(x$sex==female &x$cw>=fb(6) )

    if (type=="m7" ) i = which(x$sex==male &x$cw>=mb(4) & x$cw<mb(5))
    if (type=="m8" ) i = which(x$sex==male &x$cw>=mb(5) & x$cw<mb(6))
    if (type=="m9" ) i = which(x$sex==male &x$cw>=mb(6) & x$cw<mb(7))
    if (type=="m10" ) i = which(x$sex==male &x$cw>=mb(7) & x$cw<mb(8))
    if (type=="m11" ) i = which(x$sex==male &x$cw>=mb(8) & x$cw<mb(9))
    if (type=="m12" ) i = which(x$sex==male &x$cw>=mb(9) & x$cw<mb(10))
    if (type=="m13" ) i = which(x$sex==male &x$cw>=mb(10) )

    if (type=="f.mat")   i = which(x$sex==female & x$mat==mature )
    if (type=="f.imm")   i = which(x$sex==female & x$mat==immature )

    if (type=="f.berried")  i = which(x$sex==female & x$eggPr %in% c(1:4) )
    if (type=="primiparous") i = which(x$sex==female & x$mat==mature & x$shell<=2 )
    if (type=="multiparous") i = which(x$sex==female & x$mat==mature & x$shell>=3 )
    if (type=="senile") i = which(x$sex==female & x$mat==mature & x$shell >=4 & x$eggPr <=1 )
    if (type=="adolescent") i = which(x$sex==female & x$mat==immature & x$gonad<=2)
    if (type=="preprimiparous") i = which(x$sex==female & x$mat==immature & x$gonad==3)

    if (type=="f.soft") {
      i = which(x$sex==female & x$shell==1)
      j = which(x$sex==female & !is.finite(x$shell))
      i = sort(unique(c(i,j)))
    }

    if (type=="f.hard") {
      i = which(x$sex==female & x$shell>1)
      j = which(x$sex==female & !is.finite(x$shell))
      i = sort(unique(c(i,j)))
    }

    if (type=="m.soft") {
      i = which(x$sex==male & x$shell==1)
      j = which(x$sex==male & !is.finite(x$shell))
      i = sort(unique(c(i,j)))
    }

    if (type=="m.hard") {
      i = which(x$sex==male & x$shell>1)
      j = which(x$sex==male & !is.finite(x$shell))
      i = sort(unique(c(i,j)))
    }

    if (type=="male.small") i = which(x$sex==male & x$cw<mb(8) )
    if (type=="male.large") i = which(x$sex==male & x$cw>=mb(8) )
    if (type=="female.small") i = which(x$sex==female & x$cw<fb(4) )
    if (type=="female.large") i = which(x$sex==female & x$cw>=fb(4) )

    if (type=="m.CC1to2") i = which(x$sex==male & x$cw>=95 & x$cw<=200 & (x$shell %in% c(1,2) ))
    if (type=="m.CC3to4") i = which(x$sex==male & x$cw>=95 & x$cw<=200 & (x$shell %in% c(3,4) ))
    if (type=="m.CC1") {  # legal comercial males, carapace condition 1
      j = which(x$sex==male & x$cw>=95 & x$cw<200 & x$shell ==1 )
      k = which(x$sex==male & x$cw>=95 & x$cw<200 & !is.finite(x$shell))
      i = sort(unique(c(j,k)))
    }
    if (type=="m.CC2") i = which(x$sex==male & x$cw>=95 & x$cw<=200 & x$shell==2 )
    if (type=="m.CC3") i = which(x$sex==male & x$cw>=95 & x$cw<=200 & x$shell==3 )
    if (type=="m.CC4") i = which(x$sex==male & x$cw>=95 & x$cw<=200 & x$shell==4 )
    if (type=="m.CC5") i = which(x$sex==male & x$cw>=95 & x$cw<=200 & x$shell==5 )

    if (type=="f.CC1to2") i = which(x$sex==female & (x$shell %in% c(1,2) ))
    if (type=="f.CC3to4") i = which(x$sex==female  & (x$shell %in% c(3,4) ))
    if (type=="f.CC3") i = which(x$sex==female & (x$shell %in% c(3) ))
    if (type=="f.CC4") i = which(x$sex==female & (x$shell %in% c(4) ))
    if (type=="f.CC5") i = which(x$sex==female & x$shell==5 )

    return(i)
  }


## 1. INITIALISATION ##
  library(tidyverse)
  cat(file=stderr(), 'Starting run_BASGRA_Scott.r', "\n")

  ## 1. GENERAL INITIALISATION ##
  cat(file=stderr(), 'Initialising BASGRA', "\n")
  source('scripts/initialise_BASGRA_general.R')
  BASGRA_DLL <- "model/BASGRA_WG.DLL" # use _WG version to use own PET
  dyn.load(BASGRA_DLL)

  ## 2. SITE CONDITIONS ##
  cat(file=stderr(), 'Setting up simulation', "\n")

  # run model for this period
  # Scott weather data is 2010-1 to 2017-318 (14 Nov)
  year_start     <- as.integer(2011)
  doy_start      <- as.integer(244) # 1 Sept
  year_stop      <- year_start + 2
  doy_stop       <- doy_start - 1

  # calculate sim length --- WARNING this needs to fit within weather data!
  NDAYS          <- as.integer(difftime(
    as.Date(doy_stop -1, origin=paste(year_stop ,1,1,sep='-')),
    as.Date(doy_start-1, origin=paste(year_start,1,1,sep='-')),
    units="days")) + 1L

  # specify weather file
  stop("NEED TO FIX DIRECTORIES")
  file_weather   <- 'model_inputs/weather_Scott.txt'

  # specify  parameter set
  # file_params    <- 'model_inputs/parameters_Scott.txt' # default parameters
  file_params    <- 'model_outputs/BASGRA_parModes_MAP1.txt' # optimised parameters
  parcol       <- 1 # which one are we going to use? (row names are ignored)

  # read harvest days (Simon) which are set up in make_weather1.r
  days_harvest   <- as.matrix(read.table(file="model_inputs/harvest_Scott_3.txt", sep='\t'))

  ## 3. CREATE HARVEST CALENDAR AND WEATHER INPUT ##
  days_harvest   <- as.integer(days_harvest)
  matrix_weather <- read_weather_WG(year_start,doy_start,NDAYS,file_weather)

  ## 4. CREATE VECTOR "PARAMS" ##
  df_params      <- read.table(file_params,header=T,sep="\t",row.names=1)
  params         <- df_params[,parcol]

  ## 5. CREATE EMPTY MATRIX y ##
  y              <- matrix(0,NDAYS,NOUT)

## 2. RUNNING ##
  cat(file=stderr(), 'Calling run_model()', "\n")
   output <- run_model()

## 3. OUTPUT ##
   cat(file=stderr(), 'Calling export_output()', "\n")
   export_output()

   # unload model
   dyn.unload(BASGRA_DLL)

   # prepare output for plotting
   output <- as.data.frame(output)
   names(output) <- outputNames
   x <- output$Time
   # plot(x,output$TILTOT)
   # plot(x,output$DEBUG)


suppressPackageStartupMessages({
    source("../../../.Rprofile", chdir = TRUE)
    library(Signac)
    library(Seurat)
    library(GenomeInfoDb)
    library(EnsDb.Mmusculus.v79)
    library(ggplot2)
    library(patchwork)
})
set.seed(1234)

counts <- Read10X_h5('atac_v1_adult_brain_fresh_5k_filtered_peak_bc_matrix.h5')
metadata <- read.csv(
  file = 'atac_v1_adult_brain_fresh_5k_singlecell.csv',
  header = TRUE,
  row.names = 1
)

brain_assay <- CreateChromatinAssay(
  counts = counts,
  sep = c(":", "-"),
  genome = "mm10",
  fragments = 'atac_v1_adult_brain_fresh_5k_fragments.tsv.gz',
  min.cells = 1
)

brain <- CreateSeuratObject(
  counts = brain_assay,
  assay = 'peaks',
  project = 'ATAC',
  meta.data = metadata
)

# extract gene annotations from EnsDb
annotations <- GetGRangesFromEnsDb(ensdb = EnsDb.Mmusculus.v79)

# change to UCSC style since the data was mapped to hg19
seqlevelsStyle(annotations) <- 'UCSC'
genome(annotations) <- "mm10"

# add the gene information to the object
Annotation(brain) <- annotations

brain <- NucleosomeSignal(object = brain)

brain$nucleosome_group <- ifelse(brain$nucleosome_signal > 4, 'NS > 4', 'NS < 4')
FragmentHistogram(object = brain, group.by = 'nucleosome_group', region = 'chr1-1-10000000')

brain <- TSSEnrichment(brain, fast = FALSE)

brain$high.tss <- ifelse(brain$TSS.enrichment > 2, 'High', 'Low')
TSSPlot(brain, group.by = 'high.tss') + NoLegend()

brain$pct_reads_in_peaks <- brain$peak_region_fragments / brain$passed_filters * 100
brain$blacklist_ratio <- brain$blacklist_region_fragments / brain$peak_region_fragments

VlnPlot(
  object = brain,
  features = c('pct_reads_in_peaks', 'peak_region_fragments',
               'TSS.enrichment', 'blacklist_ratio', 'nucleosome_signal'),
  pt.size = 0.1,
  ncol = 5
)

brain <- subset(
  x = brain,
  subset = peak_region_fragments > 3000 &
    peak_region_fragments < 100000 &
    pct_reads_in_peaks > 40 &
    blacklist_ratio < 0.025 &
    nucleosome_signal < 4 &
    TSS.enrichment > 2
)
brain

brain <- RunTFIDF(brain)
brain <- FindTopFeatures(brain, min.cutoff = 'q0')
brain <- RunSVD(object = brain)

DepthCor(brain)

brain <- RunUMAP(
  object = brain,
  reduction = 'lsi',
  dims = 2:30
)
brain <- FindNeighbors(
  object = brain,
  reduction = 'lsi',
  dims = 2:30
)
brain <- FindClusters(
  object = brain,
  algorithm = 3,
  resolution = 1.2,
  verbose = FALSE
)

DimPlot(object = brain, label = TRUE) + NoLegend()

# compute gene activities
gene.activities <- GeneActivity(brain)

# add the gene activity matrix to the Seurat object as a new assay
brain[['RNA']] <- CreateAssayObject(counts = gene.activities)
brain <- NormalizeData(
  object = brain,
  assay = 'RNA',
  normalization.method = 'LogNormalize',
  scale.factor = median(brain$nCount_RNA)
)

DefaultAssay(brain) <- 'RNA'
FeaturePlot(
  object = brain,
  features = c('Sst','Pvalb',"Gad2","Neurod6","Rorb","Syt6"),
  pt.size = 0.1,
  max.cutoff = 'q95',
  ncol = 3
)

# Load the pre-processed scRNA-seq data
allen_rna <- readRDS("allen_brain.rds")
allen_rna <- FindVariableFeatures(
  object = allen_rna,
  nfeatures = 5000
)

transfer.anchors <- FindTransferAnchors(
  reference = allen_rna,
  query = brain,
  reduction = 'cca',
  dims = 1:40
)

predicted.labels <- TransferData(
  anchorset = transfer.anchors,
  refdata = allen_rna$subclass,
  weight.reduction = brain[['lsi']],
  dims = 2:30
)

brain <- AddMetaData(object = brain, metadata = predicted.labels)

plot1 <- DimPlot(allen_rna, group.by = 'subclass', label = TRUE, repel = TRUE) + NoLegend() + ggtitle('scRNA-seq')
plot2 <- DimPlot(brain, group.by = 'predicted.id', label = TRUE, repel = TRUE) + NoLegend() + ggtitle('scATAC-seq')
plot1 + plot2

# replace each label with its most likely prediction
for(i in levels(brain)) {
  cells_to_reid <- WhichCells(brain, idents = i)
  newid <- names(sort(table(brain$predicted.id[cells_to_reid]),decreasing=TRUE))[1]
  Idents(brain, cells = cells_to_reid) <- newid
}

write.csv(brain@meta.data, "signac_meta_data.csv", quote=FALSE)

brain.idents <- as.data.frame(Idents(brain))
colnames(brain.idents) <- "Idents"
write.csv(brain.idents, "signac_idents.csv", quote=FALSE)

DimPlot(brain, label = TRUE, repel = TRUE)

#switch back to working with peaks instead of gene activities
DefaultAssay(brain) <- 'peaks'

da_peaks <- FindMarkers(
  object = brain,
  ident.1 = c("L2/3 IT"),
  ident.2 = c("L4", "L5 IT", "L6 IT"),
  min.pct = 0.4,
  test.use = 'LR',
  latent.vars = 'peak_region_fragments'
)

head(da_peaks)

plot1 <- VlnPlot(
  object = brain,
  features = rownames(da_peaks)[1],
  pt.size = 0.1,
  idents = c("L4","L5 IT","L2/3 IT")
)
plot2 <- FeaturePlot(
  object = brain,
  features = rownames(da_peaks)[1],
  pt.size = 0.1,
  max.cutoff = 'q95'
)
plot1 | plot2

open_l23 <- rownames(da_peaks[da_peaks$avg_logFC > 0.25, ])
open_l456 <- rownames(da_peaks[da_peaks$avg_logFC < -0.25, ])
closest_l23 <- ClosestFeature(brain, open_l23)
closest_l456 <- ClosestFeature(brain, open_l456)
head(closest_l23)

head(closest_l456)

# set plotting order
levels(brain) <- c("L2/3 IT","L4","L5 IT","L5 PT","L6 CT", "L6 IT","NP","Sst","Pvalb","Vip","Lamp5","Meis2","Oligo","Astro","Endo","VLMC","Macrophage")

CoveragePlot(
  object = brain,
  region = c("Neurod6", "Gad2"),
  extend.upstream = 1000,
  extend.downstream = 1000,
  ncol = 1
)


  get.annual.timeseries = function( p, sex, outtype="yearclass", region="cfanorth") {

    # kriged data
    K = kriging.db( DS="UK.conditional.simulation.K.complete", p=p )
    K = factor2character(K, c("vars","region","vario.model"))

    K$vars = as.character(K$vars)
    K$region  = as.character(K$region)

    cl = make.classes (sex)
    yclass = cl$yclass
    cats = cl$cats
    varmap = cl$varmap
    yrs =  as.character( sort( unique( K$yr[K$yr>=1998] )) ) # years with reliable data

    ir = which( K$region %in% region )
    out = get.structured.data (yclass, yrs, cats, varmap, K[ir,], outvar="total")
    out.lbound = get.structured.data (yclass, yrs, cats, varmap, K[ir,], outvar="lbound")
    out.ubound = get.structured.data (yclass, yrs, cats, varmap, K[ir,], outvar="ubound")
    out.sd =  (out.ubound - out.lbound)  # this gives the 95% CI
    out.sd = out.sd / 4  # 1/2 range estimates 2 SD; 1/4 range est of 1 SD

    if (outtype=="yearclass") {
      OO = list(TS=out, TS.lb=out.lbound, TS.ub=out.ubound, TS.sd=out.sd)
    }
    if (outtype=="cohorts") {
      OO = get.cohort.data (yclass, yrs, cats, varmap, out, outvar="total")
    }

    return(OO)
  }