#!/bin/bash

# This script fits a  maxent model
#
# Predicting the locations of Conservation area-like forests in Central Finland.
#
# maxent.jar can't be distributed here due to copyright. Get it from https://www.cs.princeton.edu/~schapire/maxent/
#
# You will need to manually remove lines with missing data from conserved_swd.csv and background.csv
# and give them the names samplesnomissing.csv and backgroundnomissing.csv.
#
# Both csv's need to have the same headers. (fixed with sed -i "1iheaders")


# create a random sample of the background pixels

echo "Creating background samples..."
HEADER=$(head -1 backgroundnomissing.csv)

sed "1d" backgroundnomissing.csv | shuf -n 1000000 > backgroundsample.csv
sed -i "1i$HEADER" backgroundsample.csv


# Fit the model for product features
# Make predictions on the background samples as well.

echo "Product..."
date

mkdir -p outputs_product

java -mx32000m -jar maxent.jar outputdirectory=./ pictures=false samplesfile="samplesnomissing.csv" environmentallayers='backgroundsample.csv' randomseed=true warnings=false tooltips=false askoverwrite=true writeclampgrid=false writemess=false randomtestpoints=0 betamultiplier=1 replicates=1 writebackgroundpredictions=false linear=true quadratic=true product=true threshold=false hinge=false addsamplestobackground=false visible=false autofeature=false doclamp=false outputgrids=false maximumiterations=50000 threads=4 projectionlayers="backgroundnomissing.csv" defaultprevalence=0.5 autorun=true

# Project the data

java -cp maxent.jar density.Project conservation.lambdas backgroundnomissing.csv projection_product.csv outputformat=logistic tooltips=false askoverwrite=false removeduplicates=false writeclampgrid=false writemess=false fadebyclamping=false extrapolate=true doclamp=false

sed -i "1d" projection_product.csv
sed -i "1ix,y,product_fit" projection_product.csv

echo "Done."



exit 0;
