var exports={};var getImagesLib=exports;var vizParamsFalse={min:0.1,max:[0.5,0.6,0.6],bands:"swir2,nir,red",gamma:1.6,};var vizParamsFalse10k={min:0.1*10000,max:[0.5*10000,0.6*10000,0.6*10000],bands:"swir2,nir,red",gamma:1.6,};var vizParamsTrue={min:0,max:[0.2,0.2,0.2],bands:"red,green,blue",};var vizParamsTrue10k={min:0,max:[0.2*10000,0.2*10000,0.2*10000],bands:"red,green,blue",};var common_projections={};common_projections["NLCD_CONUS"]={crs:'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["latitude_of_center",23],PARAMETER["longitude_of_center",-96],PARAMETER["standard_parallel_1",29.5],PARAMETER["standard_parallel_2",45.5],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1],AXIS["Easting",EAST],AXIS["Northing",NORTH]]',transform:[30,0,-2361915.0,0,-30,3177735.0],};common_projections["NLCD_AK"]={crs:'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9108"]],AUTHORITY["EPSG","4326"]],PROJECTION["Albers_Conic_Equal_Area"],PARAMETER["standard_parallel_1",55],PARAMETER["standard_parallel_2",65],PARAMETER["latitude_of_center",50],PARAMETER["longitude_of_center",-154],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["meters",1]]',transform:[30,0,-48915.0,0,-30,1319415.0],};common_projections["NLCD_HI"]={crs:'PROJCS["Albers_Conical_Equal_Area",GEOGCS["WGS 84",DATUM["WGS_1984", SPHEROID["WGS 84", 6378137.0, 298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich", 0.0], UNIT["degree", 0.017453292519943295], AXIS["Longitude", EAST], AXIS["Latitude", NORTH], AUTHORITY["EPSG","4326"]], PROJECTION["Albers_Conic_Equal_Area"], PARAMETER["central_meridian", -157.0],PARAMETER["latitude_of_origin", 3.0],PARAMETER["standard_parallel_1", 8.0],PARAMETER["false_easting", 0.0],PARAMETER["false_northing", 0.0],PARAMETER["standard_parallel_2", 18.0],UNIT["m", 1.0],AXIS["x", EAST],AXIS["y", NORTH]]',transform:[30,0,-342585,0,-30,2127135],};var changeDirDict={blue:1,green:1,red:1,nir:-1,swir1:1,swir2:1,temp:1,NDVI:-1,NBR:-1,NDMI:-1,NDSI:1,brightness:1,greenness:-1,wetness:-1,fourth:-1,fifth:1,sixth:-1,ND_blue_green:-1,ND_blue_red:-1,ND_blue_nir:1,ND_blue_swir1:-1,ND_blue_swir2:-1,ND_green_red:-1,ND_green_nir:1,ND_green_swir1:-1,ND_green_swir2:-1,ND_red_swir1:-1,ND_red_swir2:-1,ND_nir_red:-1,ND_nir_swir1:-1,ND_nir_swir2:-1,ND_swir1_swir2:-1,R_swir1_nir:1,R_red_swir1:-1,EVI:-1,SAVI:-1,IBI:1,tcAngleBG:-1,tcAngleGW:-1,tcAngleBW:-1,tcDistBG:1,tcDistGW:1,tcDistBW:1,NIRv:-1,NDCI:-1,NDGI:-1,};var preComputedCloudScoreOffset=ee.ImageCollection("projects/lcms-tcc-shared/assets/CS-TDOM-Stats/cloudScore").mosaic();var preComputedTDOMStats=ee.ImageCollection("projects/lcms-tcc-shared/assets/CS-TDOM-Stats/TDOM").mosaic().divide(10000);exports.preComputedCloudScoreOffset=preComputedCloudScoreOffset;exports.preComputedTDOMStats=preComputedTDOMStats;exports.getPrecomputedCloudScoreOffsets=function(cloudScorePctl){return{landsat:preComputedCloudScoreOffset.select(["Landsat_CloudScore_p"+cloudScorePctl.toString(),]),sentinel2:preComputedCloudScoreOffset.select(["Sentinel2_CloudScore_p"+cloudScorePctl.toString(),]),};};exports.getPrecomputedTDOMStats=function(cloudScorePctl){return{landsat:{mean:preComputedTDOMStats.select(["Landsat_nir_mean","Landsat_swir1_mean",]),stdDev:preComputedTDOMStats.select(["Landsat_nir_stdDev","Landsat_swir1_stdDev",]),},sentinel2:{mean:preComputedTDOMStats.select(["Sentinel2_nir_mean","Sentinel2_swir1_mean",]),stdDev:preComputedTDOMStats.select(["Sentinel2_nir_stdDev","Sentinel2_swir1_stdDev",]),},};};exports.getPrecomputedTDOMStatsAK=function(cloudScorePctl){return{landsat:{mean:preComputedTDOMStatsAK.select(["Landsat_nir_mean","Landsat_swir1_mean",]),stdDev:preComputedTDOMStatsAK.select(["Landsat_nir_stdDev","Landsat_swir1_stdDev",]),},sentinel2:{mean:preComputedTDOMStatsAK.select(["Sentinel2_nir_mean","Sentinel2_swir1_mean",]),stdDev:preComputedTDOMStatsAK.select(["Sentinel2_nir_stdDev","Sentinel2_swir1_stdDev",]),},};};exports.getPrecomputedTDOMStatsHI=function(cloudScorePctl){return{sentinel2:{mean:preComputedTDOMStatsHI.select(["Sentinel2_nir_mean","Sentinel2_swir1_mean",]),stdDev:preComputedTDOMStatsHI.select(["Sentinel2_nir_stdDev","Sentinel2_swir1_stdDev",]),},};};function prepArgumentsObject(args,defaultArgs){var argList=[].slice.call(args);var outArgs={};var firstArgumentIsEEObj=false;var argsAreObject=false;try{var t=argList[0].serialize();firstArgumentIsEEObj=true;}catch(err){}
if(typeof argList[0]==="object"&&argList.length===1&&!firstArgumentIsEEObj){argsAreObject=true;outArgs=argList[0];}
Object.keys(defaultArgs).forEach(function(key,i){var value;if(argsAreObject){value=argList[0][key];}else{value=argList[i];}
if(value===undefined||value===null){value=defaultArgs[key];}
outArgs[key]=value;});return outArgs;}
function copyObj(obj){var out={};Object.keys(obj).map(function(k){out[k]=obj[k];});return out;}
function reverseObj(obj){var out={};Object.keys(obj).map(function(k){let v=obj[k];out[v]=k;});return out;}
function range(start,stop,step){start=parseInt(start);stop=parseInt(stop);if(typeof stop=="undefined"){stop=start;start=0;}
if(typeof step=="undefined"){step=1;}
if((step>0&&start>=stop)||(step<0&&start<=stop)){return[];}
var result=[];for(var i=start;step>0?i<stop:i>stop;i+=step){result.push(i);}
return result;}
var eeObjectTypes={Image:ee.Image,ImageCollection:ee.ImageCollection,Geometry:ee.Geometry,Feature:ee.Feature,FeatureCollection:ee.FeatureCollection,Array:ee.Array,List:ee.List,String:ee.String,Date:ee.Date,DateRange:ee.DateRange,Dictionary:ee.Dictionary,Filter:ee.Filter,Join:ee.Join,Kernel:ee.Kernel,Number:ee.Number,Projection:ee.Projection,Reducer:ee.Reducer,};function getObjType(obj,message){let t;Object.keys(eeObjectTypes).map(function(k){if(obj instanceof eeObjectTypes[k]){t=k;}});return t;}
function eeObjInfo(eeObj,objType,addTime,timeFormat,timePropNameIn,timePropNameOut){objType=objType||getObjType(eeObj,"info");addTime=addTime||false;timeFormat=timeFormat||"YYYY";timePropNameIn=timePropNameIn||"system:time_start";timePropNameOut=timePropNameOut||objType=="ImageCollection"||objType==="FeatureCollection"?"dates":"date";eeObj=objType==="Geometry"?ee.Feature(eeObj):eeObj;var size;var props=ee.Dictionary();var bandNames;if(objType.indexOf("Collection")>-1){size=eeObj.size();if(objType==="ImageCollection"){bandNames=ee.Image(ee.ImageCollection(eeObj).first()).bandNames();props=ee.Image(ee.ImageCollection(eeObj).first()).toDictionary();}
if(addTime){eeObj=eeObj.map(function(img){return img.set(timePropNameOut,ee.Date(img.get(timePropNameIn)).format(timeFormat));});var dates=eeObj.aggregate_histogram(timePropNameOut).keys();}}else{if(objType==="Image"){bandNames=ee.Image(eeObj).bandNames();props=ee.Image(eeObj).toDictionary();}
if(addTime){var dates=ee.Date(eeObj.get(timePropNameIn)).format(timeFormat);}}
props=props.set("layerType",objType);props=bandNames!==undefined?props.set("bandNames",bandNames):props;props=size!==undefined?props.set("size",size):props;if(addTime){props=props.set(timePropNameOut,dates);}
return props;}
function eeObjServerSide(obj){return getObjType(obj,"is server side")!==undefined;}
function setNoData(){var defaultArgs={image:null,noDataValue:null,};var args=prepArgumentsObject(arguments,defaultArgs);return args.image.unmask(args.noDataValue,false).set(args);}
function sieve(){var defaultArgs={image:null,mmu:4,};var args=prepArgumentsObject(arguments,defaultArgs);var connected=args.image.connectedPixelCount(args.mmu+20);var elim=connected.gt(args.mmu);var mode=args.image.focal_mode(args.mmu/2,"circle");mode=mode.mask(args.image.mask());var filled=args.image.where(elim.not(),mode);return filled.set(args);}
var harmonizationRoy=function(oli){var slopes=ee.Image.constant([0.9785,0.9542,0.9825,1.0073,1.0171,0.9949,]);var itcp=ee.Image.constant([-0.0095,-0.0016,-0.0022,-0.0021,-0.003,0.0029,]);var bns=oli.bandNames();var includeBns=["blue","green","red","nir","swir1","swir2"];var otherBns=bns.removeAll(includeBns);var y=oli.select(includeBns).float()
.subtract(itcp).divide(slopes).set("system:time_start",oli.get("system:time_start"));y=y.addBands(oli.select(otherBns)).select(bns);return y.float();};var chastainBandNames=["blue","green","red","nir","swir1","swir2"];var msiOLISlopes=[1.0946,1.0043,1.0524,0.8954,1.0049,1.0002];var msiOLIIntercepts=[-0.0107,0.0026,-0.0015,0.0033,0.0065,0.0046];var msiETMSlopes=[1.10601,0.99091,1.05681,1.0045,1.03611,1.04011];var msiETMIntercepts=[-0.0139,0.00411,-0.0024,-0.0076,0.00411,0.00861];var oliETMSlopes=[1.03501,1.00921,1.01991,1.14061,1.04351,1.05271];var oliETMIntercepts=[-0.0055,-0.0008,-0.0021,-0.0163,-0.0045,0.00261];var chastainCoeffDict={MSI_OLI:[msiOLISlopes,msiOLIIntercepts,1],MSI_ETM:[msiETMSlopes,msiETMIntercepts,1],OLI_ETM:[oliETMSlopes,oliETMIntercepts,1],OLI_MSI:[msiOLISlopes,msiOLIIntercepts,0],ETM_MSI:[msiETMSlopes,msiETMIntercepts,0],ETM_OLI:[oliETMSlopes,oliETMIntercepts,0],};function dir0Regression(img,slopes,intercepts){var bns=img.bandNames();var nonCorrectBands=bns.removeAll(chastainBandNames);var nonCorrectedBands=img.select(nonCorrectBands);var corrected=img.select(chastainBandNames).multiply(slopes).add(intercepts);var out=corrected.addBands(nonCorrectedBands).select(bns);return out;}
function dir1Regression(img,slopes,intercepts){var bns=img.bandNames();var nonCorrectBands=bns.removeAll(chastainBandNames);var nonCorrectedBands=img.select(nonCorrectBands);var corrected=img.select(chastainBandNames).subtract(intercepts).divide(slopes);var out=corrected.addBands(nonCorrectedBands).select(bns);return out;}
function harmonizationChastain(){var defaultArgs={image:null,fromSensor:null,toSensor:null,};var args=prepArgumentsObject(arguments,defaultArgs);args.fromSensor=args.fromSensor.toUpperCase();args.toSensor=args.toSensor.toUpperCase();args.comboKey=args.fromSensor+"_"+args.toSensor;args.coeffList=chastainCoeffDict[args.comboKey];var slopes=args.coeffList[0];var intercepts=args.coeffList[1];var direction=ee.Number(args.coeffList[2]);var out=ee.Algorithms.If(direction.eq(0),dir0Regression(args.image,slopes,intercepts),dir1Regression(args.image,slopes,intercepts));out=ee.Image(out).copyProperties(args.image).copyProperties(args.image,["system:time_start"]);out=out.set(args);return ee.Image(out);}
function collectionToImage(collection){var stack=ee.Image(collection.iterate(function(img,prev){return ee.Image(prev).addBands(img);},ee.Image(1)));stack=stack.select(ee.List.sequence(1,stack.bandNames().size().subtract(1)));return stack;}
function compositeDates(images,composite,bandNames){if(bandNames===null||bandNames===undefined){bandNames=ee.Image(images.first()).bandNames();}else{images=images.select(bandNames);composite=composite.select(bandNames);}
var bns=ee.Image(images.first()).bandNames().map(function(bn){return ee.String(bn).cat("_diff");});function getDiff(img,composite){var out=img.subtract(composite).abs().multiply(-1).rename(bns);return img.addBands(out);}
images=images.map(function(img){return getDiff(img,composite);});images=images.map(addDateBand);var out=bandNames.map(function(bn){bn=ee.String(bn);var t=images.select([bn,bn.cat("_diff"),"year"]).qualityMosaic(bn.cat("_diff"));return t.select(["year"]).rename(["YYYYDD"]);});out=collectionToImage(ee.ImageCollection(out));return out;}
function fillEmptyCollections(inCollection,dummyImage){var dummyCollection=ee.ImageCollection([dummyImage.mask(ee.Image(0))]);var imageCount=inCollection.toList(1).length();return ee.ImageCollection(ee.Algorithms.If(imageCount.gt(0),inCollection,dummyCollection));}
function addSensorBand(img,whichProgram,toaOrSR){var sensorDict=ee.Dictionary({LANDSAT_4:4,LANDSAT_5:5,LANDSAT_7:7,LANDSAT_8:8,LANDSAT_9:9,"Sentinel-2A":21,"Sentinel-2B":22,"Sentinel-2C":23,});var sensorPropDict=ee.Dictionary({C1_landsat:{TOA:"SPACECRAFT_ID",SR:"SATELLITE"},C2_landsat:{TOA:"SPACECRAFT_ID",SR:"SPACECRAFT_ID"},sentinel2:{TOA:"SPACECRAFT_NAME",SR:"SPACECRAFT_NAME"},});toaOrSR=toaOrSR.toUpperCase();var sensorProp=ee.Dictionary(sensorPropDict.get(whichProgram)).get(toaOrSR);var sensorName=img.get(sensorProp);img=img.addBands(ee.Image.constant(sensorDict.get(sensorName)).rename(["sensor"]).byte()).set("sensor",sensorName);return img;}
function addDateBand(img,maskTime){if(maskTime===null||maskTime===undefined){maskTime=false;}
var d=ee.Date(img.get("system:time_start"));var y=d.get("year");d=y.add(d.getFraction("year"));var db=ee.Image.constant(d).rename(["year"]).float();if(maskTime){db=db.updateMask(img.select([0]).mask());}
return img.addBands(db);}
function addYearFractionBand(img){var d=ee.Date(img.get("system:time_start"));var y=d.get("year");d=d.getFraction("year");var db=ee.Image.constant(d).rename(["year"]).float();db=db;return img.addBands(db);}
function addYearYearFractionBand(img){var d=ee.Date(img.get("system:time_start"));var y=d.get("year");d=d.getFraction("year");var db=ee.Image.constant(y).add(ee.Image.constant(d)).rename(["year"]).float();db=db;return img.addBands(db);}
function addYearBand(img){var d=ee.Date(img.get("system:time_start"));var y=d.get("year");var db=ee.Image.constant(y).rename(["year"]).float();db=db;return img.addBands(db).float();}
function addJulianDayBand(img){var d=ee.Date(img.get("system:time_start"));var julian=ee.Image(ee.Number.parse(d.format("DD"))).rename(["julianDay"]);return img.addBands(julian).float();}
function addYearJulianDayBand(img){var d=ee.Date(img.get("system:time_start"));var yj=ee.Image(ee.Number.parse(d.format("YYDD"))).rename(["yearJulian"]);return img.addBands(yj).float();}
function addFullYearJulianDayBand(img){var d=ee.Date(img.get("system:time_start"));var julian=ee.Number(d.getRelative("day","year")).add(1).format("%03d");var y=ee.String(d.get("year"));var yj=(yj=ee.Image(ee.Number.parse(d.format("YYYYDD"))).rename(["yearJulian"]).int64());return img.addBands(yj).float();}
function offsetImageDate(img,n,unit){var date=ee.Date(img.get("system:time_start"));date=date.advance(n,unit);return img.set("system:time_start",date.millis());}
var fringeCountThreshold=279;var k=ee.Kernel.fixed(41,41,[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],[0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,],]);function defringeLandsat(img){var m=img.mask().reduce(ee.Reducer.min());var sum=m.reduceNeighborhood(ee.Reducer.sum(),k,"kernel");sum=sum.gte(fringeCountThreshold);img=img.mask(sum);return img;}
function uniqueValues(collection,field){var values=ee.Dictionary(collection.reduceColumns(ee.Reducer.frequencyHistogram(),[field]).get("histogram")).keys();return values;}
function dailyMosaics(imgs){imgs=imgs.map(function(img){var d=ee.String(img.date().format("YYYY-MM-dd"));var orbit=ee.Number(img.get("SENSING_ORBIT_NUMBER")).int16().format();return img.set({"date-orbit":d.cat(ee.String("_")).cat(orbit),date:d});});var dayOrbits=ee.Dictionary(imgs.aggregate_histogram("date-orbit")).keys();print("Day-Orbits:",dayOrbits);function getMosaic(d){var date=ee.Date(ee.String(d).split("_").get(0));var orbit=ee.Number.parse(ee.String(d).split("_").get(1));var t=imgs.filterDate(date,date.advance(1,"day")).filter(ee.Filter.eq("SENSING_ORBIT_NUMBER",orbit));var f=ee.Image(t.first());t=t.mosaic();t=t.set("system:time_start",date.millis());t=t.copyProperties(f);return t;}
imgs=dayOrbits.map(getMosaic);imgs=ee.ImageCollection.fromImages(imgs);print("N s2 mosaics:",imgs.size());return imgs;}
function toNatural(img){return ee.Image(10.0).pow(img.select(0).divide(10.0));}
function toDB(img){return ee.Image(img).log10().multiply(10.0);}
function RefinedLee(img){var weights3=ee.List.repeat(ee.List.repeat(1,3),3);var kernel3=ee.Kernel.fixed(3,3,weights3,1,1,false);var mean3=img.reduceNeighborhood(ee.Reducer.mean(),kernel3);var variance3=img.reduceNeighborhood(ee.Reducer.variance(),kernel3);var sample_weights=ee.List([[0,0,0,0,0,0,0],[0,1,0,1,0,1,0],[0,0,0,0,0,0,0],[0,1,0,1,0,1,0],[0,0,0,0,0,0,0],[0,1,0,1,0,1,0],[0,0,0,0,0,0,0],]);var sample_kernel=ee.Kernel.fixed(7,7,sample_weights,3,3,false);var sample_mean=mean3.neighborhoodToBands(sample_kernel);var sample_var=variance3.neighborhoodToBands(sample_kernel);var gradients=sample_mean.select(1).subtract(sample_mean.select(7)).abs();gradients=gradients.addBands(sample_mean.select(6).subtract(sample_mean.select(2)).abs());gradients=gradients.addBands(sample_mean.select(3).subtract(sample_mean.select(5)).abs());gradients=gradients.addBands(sample_mean.select(0).subtract(sample_mean.select(8)).abs());var max_gradient=gradients.reduce(ee.Reducer.max());var gradmask=gradients.eq(max_gradient);var gradmask=gradmask.addBands(gradmask);var directions=sample_mean.select(1).subtract(sample_mean.select(4)).gt(sample_mean.select(4).subtract(sample_mean.select(7))).multiply(1);directions=directions.addBands(sample_mean.select(6).subtract(sample_mean.select(4)).gt(sample_mean.select(4).subtract(sample_mean.select(2))).multiply(2));directions=directions.addBands(sample_mean.select(3).subtract(sample_mean.select(4)).gt(sample_mean.select(4).subtract(sample_mean.select(5))).multiply(3));directions=directions.addBands(sample_mean.select(0).subtract(sample_mean.select(4)).gt(sample_mean.select(4).subtract(sample_mean.select(8))).multiply(4));var directions=directions.addBands(directions.select(0).not().multiply(5));directions=directions.addBands(directions.select(1).not().multiply(6));directions=directions.addBands(directions.select(2).not().multiply(7));directions=directions.addBands(directions.select(3).not().multiply(8));directions=directions.updateMask(gradmask);directions=directions.reduce(ee.Reducer.sum());var sample_stats=sample_var.divide(sample_mean.multiply(sample_mean));var sigmaV=sample_stats.toArray().arraySort().arraySlice(0,0,5).arrayReduce(ee.Reducer.mean(),[0]);var rect_weights=ee.List.repeat(ee.List.repeat(0,7),3).cat(ee.List.repeat(ee.List.repeat(1,7),4));var diag_weights=ee.List([[1,0,0,0,0,0,0],[1,1,0,0,0,0,0],[1,1,1,0,0,0,0],[1,1,1,1,0,0,0],[1,1,1,1,1,0,0],[1,1,1,1,1,1,0],[1,1,1,1,1,1,1],]);var rect_kernel=ee.Kernel.fixed(7,7,rect_weights,3,3,false);var diag_kernel=ee.Kernel.fixed(7,7,diag_weights,3,3,false);var dir_mean=img.reduceNeighborhood(ee.Reducer.mean(),rect_kernel).updateMask(directions.eq(1));var dir_var=img.reduceNeighborhood(ee.Reducer.variance(),rect_kernel).updateMask(directions.eq(1));dir_mean=dir_mean.addBands(img.reduceNeighborhood(ee.Reducer.mean(),diag_kernel).updateMask(directions.eq(2)));dir_var=dir_var.addBands(img.reduceNeighborhood(ee.Reducer.variance(),diag_kernel).updateMask(directions.eq(2)));for(var i=1;i<4;i++){dir_mean=dir_mean.addBands(img.reduceNeighborhood(ee.Reducer.mean(),rect_kernel.rotate(i)).updateMask(directions.eq(2*i+1)));dir_var=dir_var.addBands(img.reduceNeighborhood(ee.Reducer.variance(),rect_kernel.rotate(i)).updateMask(directions.eq(2*i+1)));dir_mean=dir_mean.addBands(img.reduceNeighborhood(ee.Reducer.mean(),diag_kernel.rotate(i)).updateMask(directions.eq(2*i+2)));dir_var=dir_var.addBands(img.reduceNeighborhood(ee.Reducer.variance(),diag_kernel.rotate(i)).updateMask(directions.eq(2*i+2)));}
dir_mean=dir_mean.reduce(ee.Reducer.sum());dir_var=dir_var.reduce(ee.Reducer.sum());var varX=dir_var.subtract(dir_mean.multiply(dir_mean).multiply(sigmaV)).divide(sigmaV.add(1.0));var b=varX.divide(dir_var);var result=dir_mean.add(b.multiply(img.subtract(dir_mean)));return result.arrayFlatten([["sum"]]);}
function getS1(studyArea,startYear,endYear,startJulian,endJulian,polarization,pass_direction){if(polarization===undefined||polarization===null){polarization="VV";}
if(pass_direction===undefined||pass_direction===null){pass_direction="ASCENDING";}
var collection=ee.ImageCollection("COPERNICUS/S1_GRD").filter(ee.Filter.calendarRange(startYear,endYear,"year")).filter(ee.Filter.calendarRange(startJulian,endJulian)).filter(ee.Filter.eq("instrumentMode","IW")).filter(ee.Filter.listContains("transmitterReceiverPolarisation",polarization)).filter(ee.Filter.eq("orbitProperties_pass",pass_direction)).filter(ee.Filter.eq("resolution_meters",10)).filterBounds(studyArea).select([polarization]);return collection;}
function getS2(){var defaultArgs={studyArea:null,startDate:null,endDate:null,startJulian:null,endJulian:null,resampleMethod:"aggregate",toaOrSR:"TOA",convertToDailyMosaics:true,addCloudProbability:false,addCloudScorePlus:true,cloudScorePlusScore:"cs",};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();var s2CollectionDict={TOA:"COPERNICUS/S2_HARMONIZED",SR:"COPERNICUS/S2_SR_HARMONIZED",};var sensorBandDict={SR:["B1","B2","B3","B4","B5","B6","B7","B8","B8A","B9","B11","B12",],TOA:["B1","B2","B3","B4","B5","B6","B7","B8","B8A","B9","B10","B11","B12",],};var sensorBandNameDict={SR:["cb","blue","green","red","re1","re2","re3","nir","nir2","waterVapor","swir1","swir2",],TOA:["cb","blue","green","red","re1","re2","re3","nir","nir2","waterVapor","cirrus","swir1","swir2",],};var s2_continuous_bands=sensorBandNameDict[args.toaOrSR];var s2s=ee.ImageCollection(s2CollectionDict[args.toaOrSR]).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).map(function(img){var t=img.select(sensorBandDict[args.toaOrSR]).divide(10000);return img.addBands(t,null,true);}).select(["QA60"].concat(sensorBandDict[args.toaOrSR]),["QA60"].concat(sensorBandNameDict[args.toaOrSR]));if(args.addCloudProbability){print("Joining pre-computed cloud probabilities from: COPERNICUS/S2_CLOUD_PROBABILITY");var cloudProbabilities=ee.ImageCollection("COPERNICUS/S2_CLOUD_PROBABILITY").filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).select(["probability"],["cloud_probability"]);var cloudProbabilitiesIds=ee.List(ee.Dictionary(cloudProbabilities.aggregate_histogram("system:index")).keys());var s2sIds=ee.List(ee.Dictionary(s2s.aggregate_histogram("system:index")).keys());var missing=s2sIds.removeAll(cloudProbabilitiesIds);print("Missing cloud probability ids:",missing);print("N s2 images before joining with cloud prob:",s2s.size());s2s=s2s.linkCollection(cloudProbabilities,["cloud_probability"]);print("N s2 images after joining with cloud prob:",s2s.size());}
if(args.addCloudScorePlus){print("Joining pre-computed cloudScore+ from: GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED");var cloudScorePlus=ee.ImageCollection("GOOGLE/CLOUD_SCORE_PLUS/V1/S2_HARMONIZED")
.select([args.cloudScorePlusScore],["cloudScorePlus"]);var cloudScorePlusIds=ee.List(ee.Dictionary(cloudScorePlus.aggregate_histogram("system:index")).keys());var s2sIds=ee.List(ee.Dictionary(s2s.aggregate_histogram("system:index")).keys());var missing=s2sIds.removeAll(cloudScorePlusIds);print("Missing cloud probability ids:",missing);print("N s2 images before joining with cloudScore+:",s2s.size());s2s=s2s.linkCollection(cloudScorePlus,["cloudScorePlus"]);print("N s2 images after joining with cloudScore+:",s2s.size());}
if(["bilinear","bicubic"].indexOf(args.resampleMethod)>-1){print("Setting resample method to ",args.resampleMethod);s2s=s2s.map(function(img){return img.addBands(img.select(s2_continuous_bands).resample(args.resampleMethod),null,true);});}else if(args.resampleMethod==="aggregate"){print("Setting to aggregate instead of resample ");s2s=s2s.map(function(img){return img.addBands(img.select(s2_continuous_bands).reduceResolution(ee.Reducer.mean(),true,64),null,true);});}
if(args.convertToDailyMosaics){print("Converting S2 data to daily orbit mosaics");s2s=dailyMosaics(s2s);}
s2s=s2s.map(function(img){return img.updateMask(img.select(sensorBandNameDict[args.toaOrSR]).mask().reduce(ee.Reducer.min()));});return s2s.set(args);}
var getSentinel2=getS2;var landsat_C2_L2_rescale_dict={C1:{refl_mult:0.0001,refl_add:0,temp_mult:0.1,temp_add:0},C2:{refl_mult:0.0000275,refl_add:-0.2,temp_mult:0.00341802,temp_add:149.0,},};var landsat_continuous_bands=["blue","green","red","nir","swir1","temp","swir2",];var landsatSensorBandDict={C1_L4_TOA:["B1","B2","B3","B4","B5","B6","B7","BQA"],C2_L4_TOA:["B1","B2","B3","B4","B5","B6","B7","QA_PIXEL"],C1_L5_TOA:["B1","B2","B3","B4","B5","B6","B7","BQA"],C2_L5_TOA:["B1","B2","B3","B4","B5","B6","B7","QA_PIXEL"],C1_L7_TOA:["B1","B2","B3","B4","B5","B6_VCID_1","B7","BQA"],C2_L7_TOA:["B1","B2","B3","B4","B5","B6_VCID_1","B7","QA_PIXEL"],C1_L8_TOA:["B2","B3","B4","B5","B6","B10","B7","BQA"],C2_L8_TOA:["B2","B3","B4","B5","B6","B10","B7","QA_PIXEL"],C2_L9_TOA:["B2","B3","B4","B5","B6","B10","B7","QA_PIXEL"],C1_L4_SR:["B1","B2","B3","B4","B5","B6","B7","pixel_qa"],C2_L4_SR:["SR_B1","SR_B2","SR_B3","SR_B4","SR_B5","ST_B6","SR_B7","QA_PIXEL",],C1_L5_SR:["B1","B2","B3","B4","B5","B6","B7","pixel_qa"],C2_L5_SR:["SR_B1","SR_B2","SR_B3","SR_B4","SR_B5","ST_B6","SR_B7","QA_PIXEL",],C1_L7_SR:["B1","B2","B3","B4","B5","B6","B7","pixel_qa"],C2_L7_SR:["SR_B1","SR_B2","SR_B3","SR_B4","SR_B5","ST_B6","SR_B7","QA_PIXEL",],C1_L8_SR:["B2","B3","B4","B5","B6","B10","B7","pixel_qa"],C2_L8_SR:["SR_B2","SR_B3","SR_B4","SR_B5","SR_B6","ST_B10","SR_B7","QA_PIXEL",],C2_L9_SR:["SR_B2","SR_B3","SR_B4","SR_B5","SR_B6","ST_B10","SR_B7","QA_PIXEL",],};var landsatSensorBandNameDict={C1_TOA:["blue","green","red","nir","swir1","temp","swir2","BQA"],C1_SR:["blue","green","red","nir","swir1","temp","swir2","pixel_qa"],C1_SRFMASK:["pixel_qa"],C2_TOA:["blue","green","red","nir","swir1","temp","swir2","QA_PIXEL"],C2_SR:["blue","green","red","nir","swir1","temp","swir2","QA_PIXEL"],};var landsatCollectionDict={C1_L8_TOA:"LANDSAT/LC08/C01/T1",C1_L7_TOA:"LANDSAT/LE07/C01/T1",C1_L5_TOA:"LANDSAT/LT05/C01/T1",C1_L4_TOA:"LANDSAT/LT04/C01/T1",C1_L8_SR:"LANDSAT/LC08/C01/T1_SR",C1_L7_SR:"LANDSAT/LE07/C01/T1_SR",C1_L5_SR:"LANDSAT/LT05/C01/T1_SR",C1_L4_SR:"LANDSAT/LT04/C01/T1_SR",C2_L9_TOA:"LANDSAT/LC09/C02/T1",C2_L8_TOA:"LANDSAT/LC08/C02/T1",C2_L7_TOA:"LANDSAT/LE07/C02/T1",C2_L5_TOA:"LANDSAT/LT05/C02/T1",C2_L4_TOA:"LANDSAT/LT04/C02/T1",C2_L9_SR:"LANDSAT/LC09/C02/T1_L2",C2_L8_SR:"LANDSAT/LC08/C02/T1_L2",C2_L7_SR:"LANDSAT/LE07/C02/T1_L2",C2_L5_SR:"LANDSAT/LT05/C02/T1_L2",C2_L4_SR:"LANDSAT/LT04/C02/T1_L2",};var landsatFmaskBandNameDict={C1:"pixel_qa",C2:"QA_PIXEL"};function applyScaleFactors(image,landsatCollectionVersion){var factor_dict=landsat_C2_L2_rescale_dict[landsatCollectionVersion];var opticalBands=image.select("blue","green","red","nir","swir1","swir2").multiply(factor_dict["refl_mult"]).add(factor_dict["refl_add"]).float();var thermalBands=image.select("temp").multiply(factor_dict["temp_mult"]).add(factor_dict["temp_add"]).float();return image.addBands(opticalBands,null,true).addBands(thermalBands,null,true);}
function getLandsat(){var defaultArgs={studyArea:null,startDate:null,endDate:null,startJulian:null,endJulian:null,toaOrSR:"SR",includeSLCOffL7:false,defringeL5:false,addPixelQA:false,resampleMethod:"near",landsatCollectionVersion:"C1",};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();function getLandsatCollection(landsatCollectionVersion,whichC,toaOrSR){var c=ee.ImageCollection(landsatCollectionDict[landsatCollectionVersion+"_"+whichC+"_"+toaOrSR]).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).filter(ee.Filter.lte("WRS_ROW",120));if(args.toaOrSR.toLowerCase()==="toa"){c=c.map(ee.Algorithms.Landsat.TOA);}
c=c.select(landsatSensorBandDict[landsatCollectionVersion+"_"+whichC+"_"+toaOrSR],landsatSensorBandNameDict[landsatCollectionVersion+"_"+toaOrSR]);if(args.toaOrSR.toLowerCase()==="sr"){c=c.map(function(image){return applyScaleFactors(image,landsatCollectionVersion);});}
return c;}
function getLandsatCollections(toaOrSR,landsatCollectionVersion){var l4s=getLandsatCollection(landsatCollectionVersion,"L4",toaOrSR);var l5s=getLandsatCollection(landsatCollectionVersion,"L5",toaOrSR);if(args.defringeL5){print("Defringing L4 and L5");l4s=l4s.map(defringeLandsat);l5s=l5s.map(defringeLandsat);}
var l8s=getLandsatCollection(landsatCollectionVersion,"L8",toaOrSR);var ls;var l7s;if(args.includeSLCOffL7){print("Including All Landsat 7");l7s=getLandsatCollection(landsatCollectionVersion,"L7",toaOrSR);}else{print("Only including SLC On Landsat 7");l7s=getLandsatCollection(landsatCollectionVersion,"L7",toaOrSR).filterDate(ee.Date.fromYMD(1998,1,1),ee.Date.fromYMD(2003,5,31).advance(1,"day"));}
ls=ee.ImageCollection(l4s.merge(l5s).merge(l7s).merge(l8s));if(landsatCollectionVersion.toLowerCase()==="c2"){var l9s=getLandsatCollection(landsatCollectionVersion,"L9",toaOrSR);ls=ee.ImageCollection(ls.merge(l9s));}
return ls;}
var ls=getLandsatCollections(args.toaOrSR,args.landsatCollectionVersion);if(args.toaOrSR.toLowerCase()==="toa"&&args.addPixelQA===true&&args.landsatCollectionVersion.toLowerCase()=="c1"){print("Acquiring SR qa bands for applying Fmask to TOA data");var l4sTOAFMASK=ee.ImageCollection(landsatCollectionDict["C1_L4_SR"]).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).filter(ee.Filter.lte("WRS_ROW",120)).select(landsatSensorBandNameDict["C1_SRFMASK"]);var l5sTOAFMASK=ee.ImageCollection(landsatCollectionDict["C1_L5_SR"]).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).filter(ee.Filter.lte("WRS_ROW",120)).select(landsatSensorBandNameDict["C1_SRFMASK"]);var l8sTOAFMASK=ee.ImageCollection(landsatCollectionDict["C1_L8_SR"]).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).filter(ee.Filter.lte("WRS_ROW",120)).select(landsatSensorBandNameDict["C1_SRFMASK"]);var lsTOAFMASK;if(args.includeSLCOffL7){print("Including All Landsat 7 for TOA QA");var l7sTOAFMASK=ee.ImageCollection(landsatCollectionDict["C1_L7_SR"]).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).filter(ee.Filter.lte("WRS_ROW",120)).select(landsatSensorBandNameDict["C1_SRFMASK"]);}else{print("Only including SLC On Landsat 7 for TOA QA");var l7sTOAFMASK=ee.ImageCollection(landsatCollectionDict["C1_L7_SR"]).filterDate(ee.Date.fromYMD(1998,1,1),ee.Date.fromYMD(2003,5,31).advance(1,"day")).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).filterBounds(args.studyArea).filter(ee.Filter.lte("WRS_ROW",120)).select(landsatSensorBandNameDict["C1_SRFMASK"]);}
lsTOAFMASK=ee.ImageCollection(l4sTOAFMASK.merge(l5sTOAFMASK).merge(l7sTOAFMASK).merge(l8sTOAFMASK));print("Joining TOA with SR QA bands");print(ls.size(),lsTOAFMASK.size());ls=joinCollections(ls.select([0,1,2,3,4,5,6]),lsTOAFMASK,false,"system:index");print("ls images:",ls);}
ls=ls.map(function(img){img=img.updateMask(img.select(["blue","green","red","nir","swir1","swir2"]).mask().reduce(ee.Reducer.min()));return img;});if(["bilinear","bicubic"].indexOf(args.resampleMethod)>-1){print("Setting resample method to ",args.resampleMethod);ls=ls.map(function(img){return img.addBands(img.select(landsat_continuous_bands).resample(args.resampleMethod),null,true);});}else if(args.resampleMethod==="aggregate"){print("Setting to aggregate instead of resample ");ls=ls.map(function(img){return img.addBands(img.select(landsat_continuous_bands).reduceResolution(ee.Reducer.mean(),true,64),null,true);});}
return ls.set(args);}
var getImageCollection=getLandsat;function rescale(img,exp,thresholds){return img.expression(exp,{img:img}).subtract(thresholds[0]).divide(thresholds[1]-thresholds[0]);}
function projectShadows(cloudMask,image,irSumThresh,contractPixels,dilatePixels,cloudHeights,yMult){if(yMult===undefined||yMult===null){yMult=ee.Algorithms.If(ee.Algorithms.IsEqual(image.select([3]).projection(),ee.Projection("EPSG:4326")),1,-1);}
var meanAzimuth=image.get("MEAN_SOLAR_AZIMUTH_ANGLE");var meanZenith=image.get("MEAN_SOLAR_ZENITH_ANGLE");var darkPixels=image.select(["nir","swir1","swir2"]).reduce(ee.Reducer.sum()).lt(irSumThresh).focal_min(contractPixels).focal_max(dilatePixels);var nominalScale=cloudMask.projection().nominalScale();var azR=ee.Number(meanAzimuth).add(180).multiply(Math.PI).divide(180.0);var zenR=ee.Number(meanZenith).multiply(Math.PI).divide(180.0);var shadows=cloudHeights.map(function(cloudHeight){cloudHeight=ee.Number(cloudHeight);var shadowCastedDistance=zenR.tan().multiply(cloudHeight);var x=azR.sin().multiply(shadowCastedDistance).divide(nominalScale);var y=azR.cos().multiply(shadowCastedDistance).divide(nominalScale).multiply(yMult);return cloudMask.changeProj(cloudMask.projection(),cloudMask.projection().translate(x,y));});var shadowMask=ee.ImageCollection.fromImages(shadows).max();shadowMask=shadowMask.and(cloudMask.not());shadowMask=shadowMask.and(darkPixels).focal_min(contractPixels).focal_max(dilatePixels);var cloudShadowMask=shadowMask.or(cloudMask);image=image.updateMask(cloudShadowMask.not()).addBands(shadowMask.rename(["cloudShadowMask"]));return image;}
function projectShadowsWrapper(){var defaultArgs={img:null,cloudThresh:20,irSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,cloudHeights:ee.List.sequence(500,10000,500),};var args=prepArgumentsObject(arguments,defaultArgs);var cloudMask=sentinel2CloudScore(args.img).gt(args.cloudThresh).focal_min(args.contractPixels).focal_max(args.dilatePixels);var img=projectShadows(cloudMask,args.img,args.irSumThresh,args.contractPixels,args.dilatePixels,args.cloudHeights);return img.set(args);}
function maskS2clouds(image){var qa=image.select("QA60").int16();var cloudBitMask=Math.pow(2,10);var cirrusBitMask=Math.pow(2,11);var mask=qa.bitwiseAnd(cloudBitMask).eq(0).and(qa.bitwiseAnd(cirrusBitMask).eq(0));return image.updateMask(mask);}
function landsatCloudScore(img){var score=ee.Image(1.0);score=score.min(rescale(img,"img.blue",[0.1,0.3]));score=score.min(rescale(img,"img.red + img.green + img.blue",[0.2,0.8]));score=score.min(rescale(img,"img.nir + img.swir1 + img.swir2",[0.3,0.8]));var tempUnmasked=img.select(["temp"]).unmask(270);score=score.min(rescale(tempUnmasked,"img",[300,290]));var ndsi=img.normalizedDifference(["green","swir1"]);score=score.min(rescale(ndsi,"img",[0.8,0.6]));score=score.multiply(100).byte();score=score.clamp(0,100);return score;}
function applyCloudScoreAlgorithm(collection,cloudScoreFunction,cloudScoreThresh,cloudScorePctl,contractPixels,dilatePixels,performCloudScoreOffset,preComputedCloudScoreOffset){if(performCloudScoreOffset===undefined||performCloudScoreOffset===null){performCloudScoreOffset=true;}
if(preComputedCloudScoreOffset===undefined||preComputedCloudScoreOffset===null){preComputedCloudScoreOffset=null;}
var collection=collection.map(function(img){var cs=cloudScoreFunction(img).rename(["cloudScore"]);return img.addBands(cs);});if(performCloudScoreOffset){var minCloudScore;if(preComputedCloudScoreOffset===null){print("Computing cloudScore offset");minCloudScore=collection.select(["cloudScore"]).reduce(ee.Reducer.percentile([cloudScorePctl]));}else{print("Using pre-computed cloudScore offset");minCloudScore=preComputedCloudScoreOffset.rename(["cloudScore"]);}}else{print("Not computing cloudScore offset");var minCloudScore=ee.Image(0).rename(["cloudScore"]);}
var collection=collection.map(function(img){var cloudMask=img.select(["cloudScore"]).subtract(minCloudScore).lt(cloudScoreThresh).focal_max(contractPixels).focal_min(dilatePixels).rename("cloudMask");return img.updateMask(cloudMask);});return collection;}
var fmaskBitDict={C1:{cloud:5,shadow:3,snow:4,},C2:{cloud:3,shadow:4,snow:5,},};function cFmask(img,fmaskClass,bitMaskBandName){if(bitMaskBandName===undefined||bitMaskBandName===null){bitMaskBandName="QA_PIXEL";}
var qa=img.select("pixel_qa").int16();if(fmaskClass=="high_confidence_cloud"){var m=qa.bitwiseAnd(ee.Image(1<<6)).neq(0).And(qa.bitwiseAnd(1<<7).neq(0));}else if(fmaskClass=="med_confidence_cloud"){var m=qa.bitwiseAnd(ee.Image(1<<7)).neq(0);}else{var m=qa.bitwiseAnd(fmaskBitDict[fmaskClass]).neq(0);}
return img.updateMask(m.not());}
function applyBitMask(img,bit,bitMaskBandName){if(bitMaskBandName===undefined||bitMaskBandName===null){bitMaskBandName="QA_PIXEL";}
var m=img.select([bitMaskBandName]).uint16();m=m.bitwiseAnd(ee.Image(1<<bit)).neq(0);return img.updateMask(m.not());}
function cFmaskCloud(img,landsatCollectionVersion,bitMaskBandName){if(bitMaskBandName===undefined||bitMaskBandName===null){bitMaskBandName="QA_PIXEL";}
return applyBitMask(img,fmaskBitDict[landsatCollectionVersion]["cloud"],bitMaskBandName);}
function cFmaskCloudShadow(img,landsatCollectionVersion,bitMaskBandName){if(bitMaskBandName===undefined||bitMaskBandName===null){bitMaskBandName="QA_PIXEL";}
return applyBitMask(img,fmaskBitDict[landsatCollectionVersion]["shadow"],bitMaskBandName);}
function simpleTDOM2(){var defaultArgs={collection:null,zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,shadowSumBands:["nir","swir1"],preComputedTDOMIRMean:null,preComputedTDOMIRStdDev:null,};var args=prepArgumentsObject(arguments,defaultArgs);var irMean;var irStdDev;if(args.preComputedTDOMIRMean===null||args.preComputedTDOMIRMean===undefined){print("Computing irMean for TDOM");irMean=args.collection.select(args.shadowSumBands).mean();}else{print("Using pre-computed irMean for TDOM");irMean=args.preComputedTDOMIRMean;}
if(args.preComputedTDOMIRStdDev===null||args.preComputedTDOMIRStdDev===undefined){print("Computing irStdDev for TDOM");irStdDev=args.collection.select(args.shadowSumBands).reduce(ee.Reducer.stdDev());}else{print("Using pre-computed irStdDev for TDOM");irStdDev=args.preComputedTDOMIRStdDev;}
var collection=args.collection.map(function(img){var zScore=img.select(args.shadowSumBands).subtract(irMean).divide(irStdDev);var irSum=img.select(args.shadowSumBands).reduce(ee.Reducer.sum());var TDOMMask=zScore.lt(args.zScoreThresh).reduce(ee.Reducer.sum()).eq(args.shadowSumBands.length).and(irSum.lt(args.shadowSumThresh));TDOMMask=TDOMMask.focal_min(args.contractPixels).focal_max(args.dilatePixels);return img.updateMask(TDOMMask.not());});return collection.set(args);}
function addIndices(img){img=img.addBands(img.normalizedDifference(["blue","green"]).rename("ND_blue_green"));img=img.addBands(img.normalizedDifference(["blue","red"]).rename("ND_blue_red"));img=img.addBands(img.normalizedDifference(["blue","nir"]).rename("ND_blue_nir"));img=img.addBands(img.normalizedDifference(["blue","swir1"]).rename("ND_blue_swir1"));img=img.addBands(img.normalizedDifference(["blue","swir2"]).rename("ND_blue_swir2"));img=img.addBands(img.normalizedDifference(["green","red"]).rename("ND_green_red"));img=img.addBands(img.normalizedDifference(["green","nir"]).rename("ND_green_nir"));img=img.addBands(img.normalizedDifference(["green","swir1"]).rename("ND_green_swir1"));img=img.addBands(img.normalizedDifference(["green","swir2"]).rename("ND_green_swir2"));img=img.addBands(img.normalizedDifference(["red","swir1"]).rename("ND_red_swir1"));img=img.addBands(img.normalizedDifference(["red","swir2"]).rename("ND_red_swir2"));img=img.addBands(img.normalizedDifference(["nir","red"]).rename("ND_nir_red"));img=img.addBands(img.normalizedDifference(["nir","swir1"]).rename("ND_nir_swir1"));img=img.addBands(img.normalizedDifference(["nir","swir2"]).rename("ND_nir_swir2"));img=img.addBands(img.normalizedDifference(["swir1","swir2"]).rename("ND_swir1_swir2"));img=img.addBands(img.select("swir1").divide(img.select("nir")).rename("R_swir1_nir"));img=img.addBands(img.select("red").divide(img.select("swir1")).rename("R_red_swir1"));var evi=img.expression("2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",{NIR:img.select("nir"),RED:img.select("red"),BLUE:img.select("blue"),}).float();img=img.addBands(evi.rename("EVI"));var savi=img.expression("(NIR - RED) * (1 + 0.5)/(NIR + RED + 0.5)",{NIR:img.select("nir"),RED:img.select("red"),}).float();img=img.addBands(savi.rename("SAVI"));var ibi_a=img.expression("2*SWIR1/(SWIR1 + NIR)",{SWIR1:img.select("swir1"),NIR:img.select("nir"),}).rename("IBI_A");var ibi_b=img.expression("(NIR/(NIR + RED)) + (GREEN/(GREEN + SWIR1))",{NIR:img.select("nir"),RED:img.select("red"),GREEN:img.select("green"),SWIR1:img.select("swir1"),}).rename("IBI_B");ibi_a=ibi_a.addBands(ibi_b);var ibi=ibi_a.normalizedDifference(["IBI_A","IBI_B"]);img=img.addBands(ibi.rename("IBI"));return img;}
function addSAVIandEVI(img){var evi=img.expression("2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",{NIR:img.select("nir"),RED:img.select("red"),BLUE:img.select("blue"),}).float();img=img.addBands(evi.rename("EVI"));var savi=img.expression("(NIR - RED) * (1 + 0.5)/(NIR + RED + 0.5)",{NIR:img.select("nir"),RED:img.select("red"),}).float();var NIRv=img.select(["NDVI"]).subtract(0.08).multiply(img.select(["nir"]));img=img.addBands(savi.rename("SAVI")).addBands(NIRv.rename("NIRv"));return img;}
function simpleAddIndices(in_image){in_image=in_image.addBands(in_image.normalizedDifference(["nir","red"]).select([0],["NDVI"]));in_image=in_image.addBands(in_image.normalizedDifference(["nir","swir2"]).select([0],["NBR"]));in_image=in_image.addBands(in_image.normalizedDifference(["nir","swir1"]).select([0],["NDMI"]));in_image=in_image.addBands(in_image.normalizedDifference(["green","swir1"]).select([0],["NDSI"]));return in_image;}
function addSoilIndices(img){img=img.addBands(img.normalizedDifference(["red","green"]).rename("NDCI"));img=img.addBands(img.normalizedDifference(["red","swir2"]).rename("NDII"));img=img.addBands(img.normalizedDifference(["swir1","nir"]).rename("NDFI"));var bsi=img.expression("((SWIR1 + RED) - (NIR + BLUE)) / ((SWIR1 + RED) + (NIR + BLUE))",{BLUE:img.select("blue"),RED:img.select("red"),NIR:img.select("nir"),SWIR1:img.select("swir1"),}).float();img=img.addBands(bsi.rename("BSI"));var hi=img.expression("SWIR1 / SWIR2",{SWIR1:img.select("swir1"),SWIR2:img.select("swir2"),}).float();img=img.addBands(hi.rename("HI"));return img.float();}
function getTasseledCap(image){var bands=ee.List(["blue","green","red","nir","swir1","swir2"]);var coefficients=ee.Array([[0.2043,0.4158,0.5524,0.5741,0.3124,0.2303],[-0.1603,-0.2819,-0.4934,0.794,-0.0002,-0.1446],[0.0315,0.2021,0.3102,0.1594,-0.6806,-0.6109],[-0.2117,-0.0284,0.1302,-0.1007,0.6529,-0.7078],[-0.8669,-0.1835,0.3856,0.0408,-0.1132,0.2272],[0.3677,-0.82,0.4354,0.0518,-0.0066,-0.0104],]);var arrayImage1D=image.select(bands).toArray();var arrayImage2D=arrayImage1D.toArray(1);var componentsImage=ee.Image(coefficients).matrixMultiply(arrayImage2D)
.arrayProject([0])
.arrayFlatten([["brightness","greenness","wetness","fourth","fifth","sixth"],]).float();return image.addBands(componentsImage);}
function simpleGetTasseledCap(image){var bands=ee.List(["blue","green","red","nir","swir1","swir2"]);var coefficients=ee.Array([[0.2043,0.4158,0.5524,0.5741,0.3124,0.2303],[-0.1603,-0.2819,-0.4934,0.794,-0.0002,-0.1446],[0.0315,0.2021,0.3102,0.1594,-0.6806,-0.6109],]);var arrayImage1D=image.select(bands).toArray();var arrayImage2D=arrayImage1D.toArray(1);var componentsImage=ee.Image(coefficients).matrixMultiply(arrayImage2D)
.arrayProject([0])
.arrayFlatten([["brightness","greenness","wetness"]]).float();return image.addBands(componentsImage);}
function addTCAngles(image){var brightness=image.select(["brightness"]);var greenness=image.select(["greenness"]);var wetness=image.select(["wetness"]);var tcAngleBG=brightness.atan2(greenness).divide(Math.PI).rename("tcAngleBG");var tcAngleGW=greenness.atan2(wetness).divide(Math.PI).rename("tcAngleGW");var tcAngleBW=brightness.atan2(wetness).divide(Math.PI).rename("tcAngleBW");var tcDistBG=brightness.hypot(greenness).rename("tcDistBG");var tcDistGW=greenness.hypot(wetness).rename("tcDistGW");var tcDistBW=brightness.hypot(wetness).rename("tcDistBW");image=image.addBands(tcAngleBG).addBands(tcAngleGW).addBands(tcAngleBW).addBands(tcDistBG).addBands(tcDistGW).addBands(tcDistBW);return image;}
function simpleAddTCAngles(image){var brightness=image.select(["brightness"]);var greenness=image.select(["greenness"]);var wetness=image.select(["wetness"]);var tcAngleBG=brightness.atan2(greenness).divide(Math.PI).rename("tcAngleBG");return image.addBands(tcAngleBG);}
function addZenithAzimuth(img,toaOrSR,zenithDict,azimuthDict){if(zenithDict===undefined||zenithDict===null){zenithDict={TOA:"SUN_ELEVATION",SR:"SOLAR_ZENITH_ANGLE",};}
if(azimuthDict===undefined||azimuthDict===null){azimuthDict={TOA:"SUN_AZIMUTH",SR:"SOLAR_AZIMUTH_ANGLE",};}
var zenith=ee.Image.constant(img.get(zenithDict[toaOrSR])).multiply(Math.PI).divide(180).float().rename("zenith");var azimuth=ee.Image.constant(img.get(azimuthDict[toaOrSR])).multiply(Math.PI).divide(180).float().rename("azimuth");return img.addBands(zenith).addBands(azimuth);}
function medoidMosaicMSD(inCollection,medoidIncludeBands){if(medoidIncludeBands===undefined||medoidIncludeBands===null){medoidIncludeBands=ee.Image(inCollection.first()).bandNames();}
var median=inCollection.select(medoidIncludeBands).median();var medoid=inCollection.map(function(img){var diff=ee.Image(img).select(medoidIncludeBands).subtract(median).pow(2);img=addYearBand(img);img=addJulianDayBand(img);return diff.reduce("sum").multiply(-1).addBands(img);});medoid=medoid.qualityMosaic("sum");medoid=medoid.select(medoid.bandNames().remove("sum"));return medoid;}
function exportToAssetWrapper(imageForExport,assetName,assetPath,pyramidingPolicyObject,roi,scale,crs,transform){imageForExport=imageForExport.clip(roi);assetName=assetName.replace(/\s+/g,"-");if(pyramidingPolicyObject===null||pyramidingPolicyObject===undefined){pyramidingPolicyObject={".default":"mean"};}else if(typeof pyramidingPolicyObject==="string"){pyramidingPolicyObject={".default":pyramidingPolicyObject};}
print("Exporting:",assetName);Export.image.toAsset(imageForExport,assetName,assetPath,pyramidingPolicyObject,null,roi,scale,crs,transform,1e13);}
var exportToAssetWrapper2=exportToAssetWrapper;var exportToAssetWrapper3=exportToAssetWrapper;function exportToDriveWrapper(imageForExport,outputName,driveFolderName,roi,scale,crs,transform,outputNoData){if(outputNoData===null||outputNoData===undefined){outputNoData=-32768;}
imageForExport=imageForExport.clip(roi).unmask(outputNoData,false);outputName=outputName.replace("/s+/g","-");try{roi=roi.geometry();}catch(e){var x=e;}
var outRegion=roi.bounds(100,crs);print("Exporting:",outputName);Export.image.toDrive(imageForExport,outputName,driveFolderName,outputName,null,outRegion,scale,crs,transform,1e13);}
function exportToCloudStorageWrapper(imageForExport,outputName,bucketName,roi,scale,crs,transform,outputNoData){if(outputNoData===null||outputNoData===undefined){outputNoData=-32768;}
imageForExport=imageForExport.clip(roi).unmask(outputNoData,false);outputName=outputName.replace("/s+/g","-");try{roi=roi.geometry();}catch(e){var x=e;}
var outRegion=roi.bounds(100,crs);print("Exporting:",outputName);Export.image.toCloudStorage(imageForExport,outputName,bucketName,outputName,null,outRegion,scale,crs,transform,1e13);}
function wrapDates(startJulian,endJulian){var wrapOffset=0;var yearWithMajority=0;if(startJulian>endJulian){wrapOffset=365;var y1NDays=365-startJulian;var y2NDays=endJulian;if(y2NDays>y1NDays){yearWithMajority=1;}}
return[wrapOffset,yearWithMajority];}
function compositeTimeSeries(){var defaultArgs={ls:null,startYear:null,endYear:null,startJulian:null,endJulian:null,timebuffer:null,weights:null,compositingMethod:null,compositingReducer:null,};var args=prepArgumentsObject(arguments,defaultArgs);print(args);var dummyImage=ee.Image(args.ls.first());args.dateWrapping=wrapDates(args.startJulian,args.endJulian);args.wrapOffset=args.dateWrapping[0];args.yearWithMajority=args.dateWrapping[1];var ts=range(args.startYear+args.timebuffer,args.endYear-args.timebuffer+1).map(function(year){var startYearT=year-args.timebuffer;var endYearT=year+args.timebuffer;var startDateT=ee.Date.fromYMD(startYearT,1,1).advance(args.startJulian-1,"day");var endDateT=ee.Date.fromYMD(endYearT,1,1).advance(args.endJulian-1+args.wrapOffset,"day");var yearsT=ee.List.sequence(startYearT,endYearT);var z=yearsT.zip(args.weights);var yearsTT=z.map(function(i){i=ee.List(i);return ee.List.repeat(i.get(0),i.get(1));}).flatten();var images=yearsTT.map(function(yr){var startDateT=ee.Date.fromYMD(yr,1,1).advance(args.startJulian-1,"day");var endDateT=ee.Date.fromYMD(yr,1,1).advance(args.endJulian-1+args.wrapOffset,"day");var lsT=args.ls.filterDate(startDateT,endDateT.advance(1,"day"));lsT=fillEmptyCollections(lsT,dummyImage);return lsT;});var lsT=ee.ImageCollection(ee.FeatureCollection(images).flatten());var count=lsT.select([0]).count().rename(["compositeObsCount"]);var composite;if(args.compositingReducer!==undefined&&args.compositingReducer!==null){composite=lsT.reduce(args.compositingReducer);}else if(args.compositingMethod.toLowerCase()==="median"){composite=lsT.median();}else{composite=medoidMosaicMSD(lsT,["green","red","nir","swir1","swir2",]);}
composite=composite.addBands(count).float();return composite.set({"system:time_start":ee.Date.fromYMD(year+args.yearWithMajority,6,1).millis(),startDate:startDateT.millis(),endDate:endDateT.millis(),startJulian:args.startJulian,endJulian:args.endJulian,yearBuffer:args.timebuffer,yearWeights:listToString(args.weights),yrOriginal:year,yrUsed:year+args.yearWithMajority,});});return ee.ImageCollection(ts).set(args);}
function illuminationCondition(img){var SZ_rad=img.select("zenith");var SA_rad=img.select("azimuth");var dem=ee.Image("USGS/NED");var slp=ee.Terrain.slope(dem);var slp_rad=ee.Terrain.slope(dem).multiply(Math.PI).divide(180);var asp_rad=ee.Terrain.aspect(dem).multiply(Math.PI).divide(180);var cosZ=SZ_rad.cos();var cosS=slp_rad.cos();var slope_illumination=cosS.expression("cosZ * cosS",{cosZ:cosZ,cosS:cosS.select("slope"),});var sinZ=SZ_rad.sin();var sinS=slp_rad.sin();var cosAziDiff=SA_rad.subtract(asp_rad).cos();var aspect_illumination=sinZ.expression("sinZ * sinS * cosAziDiff",{sinZ:sinZ,sinS:sinS,cosAziDiff:cosAziDiff,});var ic=slope_illumination.add(aspect_illumination);return img.addBands(ic.rename("IC")).addBands(cosZ.rename("cosZ")).addBands(cosS.rename("cosS")).addBands(slp.rename("slope"));}
function illuminationCorrection(img,scale,studyArea,bandList){if(bandList===null||bandList===undefined){bandList=["blue","green","red","nir","swir1","swir2","temp"];}
var props=img.toDictionary();var st=img.get("system:time_start");var img_plus_ic=img;var mask2=img_plus_ic.select("slope").gte(5).and(img_plus_ic.select("IC").gte(0)).and(img_plus_ic.select("nir").gt(-0.1));var img_plus_ic_mask2=ee.Image(img_plus_ic.updateMask(mask2));var compositeBands=img.bandNames();var nonCorrectBands=img.select(compositeBands.removeAll(bandList));function apply_SCSccorr(bandList){var method="SCSc";var out=img_plus_ic_mask2.select("IC",bandList).reduceRegion({reducer:ee.Reducer.linearFit(),geometry:studyArea,scale:scale,maxPixels:1e13,});var out_a=ee.Number(out.get("scale"));var out_b=ee.Number(out.get("offset"));var out_c=out_b.divide(out_a);var SCSc_output=img_plus_ic_mask2.expression("((image * (cosB * cosZ + cvalue)) / (ic + cvalue))",{image:img_plus_ic_mask2.select(bandList),ic:img_plus_ic_mask2.select("IC"),cosB:img_plus_ic_mask2.select("cosS"),cosZ:img_plus_ic_mask2.select("cosZ"),cvalue:out_c,});return SCSc_output;}
var img_SCSccorr=ee.Image(bandList.map(apply_SCSccorr)).addBands(img_plus_ic.select("IC"));var bandList_IC=ee.List([bandList,"IC"]).flatten();img_SCSccorr=img_SCSccorr.unmask(img_plus_ic.select(bandList_IC)).select(bandList);return img_SCSccorr.addBands(nonCorrectBands).setMulti(props).set("system:time_start",st);}
function listToString(list,space){if(space===undefined){space=" ";}
var out="";list.map(function(s){out=out+s.toString()+space;});out=out.slice(0,out.length-space.length);return out;}
var maskEmptyPixels=function(image){var withObs=image.select("num_observations_1km").gt(0);return image.mask(image.mask().and(withObs));};var getQABits=function(image,start,end,newName){var pattern=0;for(var i=start;i<=end;i++){pattern+=Math.pow(2,i);}
return image.select([0],[newName]).bitwiseAnd(pattern).rightShift(start);};var maskCloudsWQA=function(image){var QA=image.select("state_1km");var internalCloud=getQABits(QA,10,10,"internal_cloud_algorithm_flag");return image.mask(image.mask().and(internalCloud.eq(0)));};function modisCloudScore(img){var useTempInCloudMask=true;var rescale=function(img,exp,thresholds){return img.expression(exp,{img:img}).subtract(thresholds[0]).divide(thresholds[1]-thresholds[0]);};var score=ee.Image(1.0);var vizSum=rescale(img,"img.red + img.green + img.blue",[0.2,0.8]);score=score.min(vizSum);var irSum=rescale(img,"img.nir  + img.swir2 + img.swir2",[0.3,0.8]);score=score.min(irSum);var ndsi=img.normalizedDifference(["green","swir2"]);var snowScore=rescale(ndsi,"img",[0.8,0.6]);score=score.min(snowScore);if(useTempInCloudMask===true){score=score.where(img.select(["temp"]).mask().not(),1);}
score=score.multiply(100);score=score.clamp(0,100).byte();return score.rename(["cloudScore"]);}
function sentinel2CloudScore(img){var score=ee.Image(1);var blueCirrusScore=ee.Image(0);blueCirrusScore=blueCirrusScore.max(rescale(img,"img.blue",[0.1,0.5]));blueCirrusScore=blueCirrusScore.max(rescale(img,"img.cb",[0.1,0.5]));score=score.min(blueCirrusScore);score=score.min(rescale(img,"img.red + img.green + img.blue",[0.2,0.8]));score=score.min(rescale(img,"img.nir + img.swir1 + img.swir2",[0.3,0.8]));var ndsi=img.normalizedDifference(["green","swir1"]);score=score.min(rescale(ndsi,"img",[0.8,0.6]));score=score.multiply(100).byte();score=score.clamp(0,100).rename(["cloudScore"]);return score;}
function sentinel2SnowMask(img,dilatePixels){var ndsi=img.normalizedDifference(["green","swir1"]);var snowOpenLand=ndsi.gt(0.4).and(img.select(["nir"]).gt(0.11));var snowForest=ndsi.gt(0.1).and(ndsi.lt(0.4));var fsc=ndsi.multiply(1.45).subtract(0.01);if(dilatePixels===undefined||dilatePixels===null){dilatePixels=3.5;}
var snowMask=snowOpenLand.or(snowForest).not().focal_min(dilatePixels);return img.updateMask(snowMask);}
var modis250SelectBands=["sur_refl_b01","sur_refl_b02"];var modis250BandNames=["red","nir"];var modis500SelectBands=["sur_refl_b03","sur_refl_b04","sur_refl_b06","sur_refl_b07",];var modis500BandNames=["blue","green","swir1","swir2"];var combinedModisBandNames=["red","nir","blue","green","swir1","swir2"];var dailyViewAngleBandNames=["SensorZenith","SensorAzimuth","SolarZenith","SolarAzimuth",];var compositeViewAngleBandNames=["SolarZenith","ViewZenith","RelativeAzimuth",];var modisCDict={eightDayNDVIA:"MODIS/006/MYD13Q1",eightDayNDVIT:"MODIS/006/MOD13Q1",eightDaySR250A:"MODIS/006/MYD09Q1",eightDaySR250T:"MODIS/006/MOD09Q1",eightDaySR500A:"MODIS/006/MYD09A1",eightDaySR500T:"MODIS/006/MOD09A1",eightDayLST1000A:"MODIS/006/MYD11A2",eightDayLST1000T:"MODIS/006/MOD11A2",dailySR250A:"MODIS/006/MYD09GQ",dailySR250T:"MODIS/006/MOD09GQ",dailySR500A:"MODIS/006/MYD09GA",dailySR500T:"MODIS/006/MOD09GA",dailyLST1000A:"MODIS/006/MYD11A1",dailyLST1000T:"MODIS/006/MOD11A1",};var multModisDict={tempNoAngleDaily:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001,0.02,1,1]),["blue","green","red","nir","swir1","temp","swir2","Emis_31","Emis_32",],],tempNoAngleComposite:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001,0.02,1,1]),["blue","green","red","nir","swir1","temp","swir2","Emis_31","Emis_32",],],tempAngleDaily:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001,1,1,1,1,0.02,1,1,]),["blue","green","red","nir","swir1","temp","swir2","SensorZenith","SensorAzimuth","SolarZenith","SolarAzimuth","Emis_31","Emis_32",],],tempAngleComposite:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001,1,1,1,0.02,1,1,]),["blue","green","red","nir","swir1","temp","swir2","SolarZenith","ViewZenith","RelativeAzimuth","Emis_31","Emis_32",],],noTempNoAngleDaily:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001]),["blue","green","red","nir","swir1","swir2"],],noTempNoAngleComposite:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001]),["blue","green","red","nir","swir1","swir2"],],noTempAngleDaily:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001,1,1,1,1]),["blue","green","red","nir","swir1","swir2","SensorZenith","SensorAzimuth","SolarZenith","SolarAzimuth",],],noTempAngleComposite:[ee.Image([0.0001,0.0001,0.0001,0.0001,0.0001,0.0001,1,1,1]),["blue","green","red","nir","swir1","swir2","SolarZenith","ViewZenith","RelativeAzimuth",],],};function joinCollections(c1,c2,maskAnyNullValues,property,propertySecondary){if(maskAnyNullValues===undefined||maskAnyNullValues===null){maskAnyNullValues=true;}
if(property===undefined||property===null){property="system:time_start";}
if(propertySecondary===undefined||propertySecondary===null){propertySecondary=property;}
var MergeBands=function(element){return ee.Image.cat(element.get("primary"),element.get("secondary"));};var join=ee.Join.inner();var filter=ee.Filter.equals(property,null,propertySecondary);var joined=ee.ImageCollection(join.apply(c1,c2,filter));joined=ee.ImageCollection(joined.map(MergeBands));if(maskAnyNullValues){joined=joined.map(function(img){return img.mask(img.mask().and(img.reduce(ee.Reducer.min()).neq(0)));});}
return joined;}
function smartJoin(primary,secondary,hourDiff){var millis=hourDiff*60*60*1000;var maxDiffFilter=ee.Filter.maxDifference({difference:millis,leftField:"system:time_start",rightField:"system:time_start",});var saveBestJoin=ee.Join.saveBest({matchKey:"bestImage",measureKey:"timeDiff",});var MergeBands=function(element){return ee.Image.cat(element,element.get("bestImage"));};var joined=saveBestJoin.apply(primary,secondary,maxDiffFilter);joined=joined.map(MergeBands);return joined;}
function spatioTemporalJoin(primary,secondary,hourDiff,outKey){if(outKey===undefined||outKey===null){outKey="secondary";}
if(hourDiff===undefined||hourDiff===null){hourDiff=24;}
var time=hourDiff*60*60*1000;var outBns=ee.Image(secondary.first()).bandNames().map(function(bn){return ee.String(bn).cat("_").cat(outKey);});var spatioTemporalFilter=ee.Filter.and(ee.Filter.maxDifference({difference:time,leftField:"system:time_start",rightField:"system:time_start",}),ee.Filter.intersects({leftField:".geo",rightField:".geo",maxError:10,}));var saveBestJoin=ee.Join.saveBest({matchKey:outKey,measureKey:"timeDiff",});var joined=saveBestJoin.apply(primary,secondary,spatioTemporalFilter);var MergeBands=function(element){return ee.Image.cat(element,ee.Image(element.get(outKey)).rename(outBns));};joined=joined.map(MergeBands);return joined;}
function joinFeatureCollections(primary,secondary,fieldName,fieldNameSecondary){if(fieldNameSecondary===undefined||fieldNameSecondary===null){fieldNameSecondary=fieldName;}
var f=ee.Filter.equals({leftField:fieldName,rightField:fieldNameSecondary,});var innerJoin=ee.Join.inner("primary","secondary");var joined=innerJoin.apply(primary,secondary,f);joined=joined.map(function(f){var p=ee.Feature(f.get("primary"));var s=ee.Feature(f.get("secondary"));return p.copyProperties(s);});return joined;}
function despikeCollection(c,absoluteSpike,bandNo){c=c.toList(10000,0);var first=c.slice(0,1);var last=c.slice(-1,null);var left=c.slice(0,-2);var center=c.slice(1,-1);var right=c.slice(2,null);var seq=ee.List.sequence(0,left.length().subtract(1));var outCollection=seq.map(function(i){var lt=ee.Image(left.get(i));var rt=ee.Image(right.get(i));var ct=ee.Image(center.get(i));var time_start=ct.get("system:time_start");var time_end=ct.get("system:time_end");var si=ct.get("system:index");var diff1=ct.select([bandNo]).add(1).subtract(lt.select([bandNo]).add(1));var diff2=ct.select([bandNo]).add(1).subtract(rt.select([bandNo]).add(1));var highSpike=diff1.gt(absoluteSpike).and(diff2.gt(absoluteSpike));var lowSpike=diff1.lt(-absoluteSpike).and(diff2.lt(-absoluteSpike));var BinarySpike=highSpike.or(lowSpike);var doNotMask=lt.mask().not().or(rt.mask().not());var lrMean=lt.add(rt);lrMean=lrMean.divide(2);var out=ct.where(BinarySpike.eq(1).and(doNotMask.not()),lrMean);return out.set("system:index",si).set("system:time_start",time_start).set("system:time_end",time_end);});outCollection=ee.List([first,outCollection,last]).flatten();return ee.ImageCollection.fromImages(outCollection);}
function getModisData(args){var defaultArgs={startYear:null,endYear:null,startJulian:null,endJulian:null,daily:true,maskWQA:false,zenithThresh:90,useTempInCloudMask:true,addLookAngleBands:false,resampleMethod:"bicubic",};var args=prepArgumentsObject(arguments,defaultArgs);var a250C;var t250C;var a500C;var t500C;var a1000C;var t1000C;var a250CV6;var t250CV6;var a500CV6;var t500CV6;var a1000CV6;var t1000CV6;var viewAngleBandNames;if(args.daily===false){a250C=modisCDict.eightDaySR250A;t250C=modisCDict.eightDaySR250T;a500C=modisCDict.eightDaySR500A;t500C=modisCDict.eightDaySR500T;a1000C=modisCDict.eightDayLST1000A;t1000C=modisCDict.eightDayLST1000T;viewAngleBandNames=compositeViewAngleBandNames;}else{a250C=modisCDict.dailySR250A;t250C=modisCDict.dailySR250T;a500C=modisCDict.dailySR500A;t500C=modisCDict.dailySR500T;a1000C=modisCDict.dailyLST1000A;t1000C=modisCDict.dailyLST1000T;viewAngleBandNames=dailyViewAngleBandNames;}
var a250=ee.ImageCollection(a250C).filter(ee.Filter.calendarRange(args.startYear,args.endYear,"year")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).select(modis250SelectBands,modis250BandNames);var t250=ee.ImageCollection(t250C).filter(ee.Filter.calendarRange(args.startYear,args.endYear,"year")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).select(modis250SelectBands,modis250BandNames);function get500(c){var images=ee.ImageCollection(c).filter(ee.Filter.calendarRange(args.startYear,args.endYear,"year")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian));if(args.daily===true){if(args.maskWQA===true){print("Masking with QA band:",c);}
images=images.map(function(img){img=img.mask(img.mask().and(img.select(["SolarZenith"]).lt(args.zenithThresh*100)));if(args.maskWQA===true){img=maskCloudsWQA(img);}
return img;});}
if(args.addLookAngleBands){images=images.select(ee.List(modis500SelectBands).cat(viewAngleBandNames),ee.List(modis500BandNames).cat(viewAngleBandNames));}else{images=images.select(modis500SelectBands,modis500BandNames);}
return images;}
var a500=get500(a500C);var t500=get500(t500C);if(args.useTempInCloudMask===true){var t1000=ee.ImageCollection(t1000C).filter(ee.Filter.calendarRange(args.startYear,args.endYear,"year")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).select([0,8,9],["temp","Emis_31","Emis_32"]);var a1000=ee.ImageCollection(a1000C).filter(ee.Filter.calendarRange(args.startYear,args.endYear,"year")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian)).select([0,8,9],["temp","Emis_31","Emis_32"]);}
var a;var t;var tSelectOrder;var tStdNames;a=joinCollections(a250,a500,false);t=joinCollections(t250,t500,false);if(args.useTempInCloudMask===true){a=joinCollections(a,a1000,false);t=joinCollections(t,t1000,false);}
a=a.map(function(img){return img.set({platform:"aqua"});});t=t.map(function(img){return img.set({platform:"terra"});});var joined=ee.ImageCollection(a.merge(t));var dailyPiece;var tempPiece;var anglePiece;if(args.daily){dailyPiece="Daily";}else{dailyPiece="Composite";}
if(args.useTempInCloudMask){tempPiece="temp";}else{tempPiece="noTemp";}
if(args.addLookAngleBands){anglePiece="Angle";}else{anglePiece="NoAngle";}
var multKey=tempPiece+anglePiece+dailyPiece;var mult=multModisDict[multKey];var multImage=mult[0];var multNames=mult[1];joined=joined.map(function(img){return img.multiply(multImage).float().select(multNames).copyProperties(img,["system:time_start","system:time_end","system:index",]).copyProperties(img);});if(["bilinear","bicubic"].indexOf(args.resampleMethod)>-1){print("Setting resampling method",args.resampleMethod);joined=ee.ImageCollection(joined).map(function(img){return img.resample(args.resampleMethod);});}else if(args.resampleMethod==="aggregate"){print("Setting to aggregate instead of resample ");joined=joined.map(function(img){return img.reduceResolution(ee.Reducer.mean(),true,64);});}
return joined.set(args);}
function getProcessedModis(args){var defaultArgs={startYear:null,endYear:null,startJulian:null,endJulian:null,zenithThresh:90,addLookAngleBands:true,applyCloudScore:true,applyTDOM:true,useTempInCloudMask:true,cloudScoreThresh:20,performCloudScoreOffset:true,cloudScorePctl:10,zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:0,dilatePixels:2.5,shadowSumBands:["nir","swir2"],resampleMethod:"bicubic",preComputedCloudScoreOffset:null,preComputedTDOMIRMean:null,preComputedTDOMIRStdDev:null,addToMap:true,crs:"EPSG:4326",scale:250,transform:null,};var args=prepArgumentsObject(arguments,defaultArgs);print(args);args.toaOrSR="SR";args.origin="MODIS";args.daily=true;args.maskWQA=false;var modisImages=getModisData(args);if(args.addToMap){Map.addLayer(modisImages.median().reproject(args.crs,args.transform,args.scale),vizParamsFalse,"Raw Median");}
if(args.applyCloudScore){print("Applying cloudScore");modisImages=applyCloudScoreAlgorithm(modisImages,modisCloudScore,args.cloudScoreThresh,args.cloudScorePctl,args.contractPixels,args.dilatePixels,args.performCloudScoreOffset,args.preComputedCloudScoreOffset);if(args.addToMap){Map.addLayer(modisImages.median().reproject(args.crs,args.transform,args.scale),vizParamsFalse,"Cloud Masked Median",false);Map.addLayer(modisImages.min().reproject(args.crs,args.transform,args.scale),vizParamsFalse,"Cloud Masked Min",false);}}
if(args.applyTDOM){print("Applying TDOM");modisImages=simpleTDOM2(modisImages,args.zScoreThresh,args.shadowSumThresh,args.contractPixels,args.dilatePixels,args.shadowSumBands,args.preComputedTDOMIRMean,args.preComputedTDOMIRStdDev);if(args.addToMap){Map.addLayer(modisImages.median().reproject(args.crs,args.transform,args.scale),vizParamsFalse,"Cloud/Cloud Shadow Masked Median",false);Map.addLayer(modisImages.min().reproject(args.crs,args.transform,args.scale),vizParamsFalse,"Cloud/Cloud Shadow Masked Min",false);}}
modisImages=modisImages.map(simpleAddIndices);modisImages=modisImages.map(function(img){return img.float();});return modisImages.set(args);}
function nDayComposites(images,startYear,endYear,startJulian,endJulian,compositePeriod){var dummyImage=ee.Image(images.first());function getYrImages(yr){var yr=ee.Number(yr).int16();var yrImages=images.filter(ee.Filter.calendarRange(yr,yr,"year"));yrImages=fillEmptyCollections(yrImages,dummyImage);return yrImages;}
function getJdImages(yr,yrImages,start){yr=ee.Number(yr).int16();start=ee.Number(start).int16();var date=ee.Date.fromYMD(yr,1,1).advance(start.subtract(1),"day");var index=date.format("yyyy-MM-dd");var end=start.add(compositePeriod-1).int16();var jdImages=yrImages.filter(ee.Filter.calendarRange(start,end));var jdImages=fillEmptyCollections(jdImages,dummyImage);var composite=jdImages.median();return composite.set({"system:index":index,"system:time_start":date.millis(),});}
function jdWrapper(yr,yrImages){return ee.FeatureCollection(ee.List.sequence(startJulian,endJulian,compositePeriod).map(function(start){return getJdImages(yr,yrImages,start);}));}
function yrWrapper(yr){var yrImages=getYrImages(yr);return jdWrapper(yr,yrImages);}
var composites=ee.FeatureCollection(ee.List.sequence(startYear,endYear).map(function(yr){return yrWrapper(yr);}));composites=ee.ImageCollection(composites.flatten());return composites;}
function exportCollection(exportPathRoot,outputName,studyArea,crs,transform,scale,collection,startYear,endYear,startJulian,endJulian,compositingReducer,timebuffer,exportBands){var dateWrapping=wrapDates(startJulian,endJulian);var wrapOffset=dateWrapping[0];var yearWithMajority=dateWrapping[1];outputName=outputName.replace(/\s+/g,"-");outputName=outputName.replace(/\//g,"-");collection=collection.select(exportBands);range(startYear+timebuffer,endYear-timebuffer+1).map(function(year){print("Exporting:",year);var startYearT=year-timebuffer;var endYearT=year+timebuffer+yearWithMajority;var composite=collection.filter(ee.Filter.calendarRange(year+yearWithMajority,year+yearWithMajority,"year"));composite=ee.Image(composite.first()).clip(studyArea);composite=composite.set({"system:time_start":ee.Date.fromYMD(year+yearWithMajority,6,1).millis(),yearBuffer:timebuffer,});var exportName=outputName+
"_"+
startYearT+
"_"+
endYearT+
"_"+
startJulian+
"_"+
endJulian;var exportPath=exportPathRoot+"/"+exportName;exportToAssetWrapper(composite,exportName,exportPath,"mean",studyArea,null,crs,transform);});}
function exportCompositeCollection(){var defaultArgs={exportPathRoot:null,outputName:null,studyArea:null,crs:null,transform:null,scale:null,collection:null,startYear:null,endYear:null,startJulian:null,endJulian:null,compositingMethod:null,timebuffer:null,exportBands:null,toaOrSR:null,weights:null,applyCloudScore:null,applyFmaskCloudMask:null,applyTDOM:null,applyFmaskCloudShadowMask:null,applyFmaskSnowMask:null,includeSLCOffL7:null,correctIllumination:null,nonDivideBands:["temp"],resampleMethod:"near",origin:"Landsat",applyCloudProbability:null,};var args=prepArgumentsObject(arguments,defaultArgs);args.pyramidingPolicy="mean";args.collection=args.collection.select(args.exportBands);print("Export bands:",args.exportBands);print("Non divide bands:",args.nonDivideBands);args.dateWrapping=wrapDates(args.startJulian,args.endJulian);args.wrapOffset=args.dateWrapping[0];args.yearWithMajority=args.dateWrapping[1];args.outputName=args.outputName.replace(/\s+/g,"-");args.outputName=args.outputName.replace(/\//g,"-");var years=range(args.startYear+args.timebuffer,args.endYear-args.timebuffer+1).map(function(year){var startYearT=year-args.timebuffer;var endYearT=year+args.timebuffer+args.yearWithMajority;var composite=args.collection.filter(ee.Filter.calendarRange(year+args.yearWithMajority,year+args.yearWithMajority,"year"));composite=ee.Image(composite.first());var compositeBands=composite.bandNames();if(args.nonDivideBands!==null){var composite10k=composite.select(compositeBands.removeAll(args.nonDivideBands)).multiply(10000);composite=composite10k.addBands(composite.select(args.nonDivideBands)).select(compositeBands).int16();}else{composite=composite.multiply(10000).int16();}
args.startYearComposite=startYearT;args.endYearComposite=endYearT;args.systemTimeStartYear=year+args.yearWithMajority;args.yearOriginal=year;args.yearUsed=args.systemTimeStartYear;args["system:time_start"]=ee.Date.fromYMD(args.systemTimeStartYear,6,1).millis();args.exportName=args.outputName+
"_"+
args.toaOrSR+
"_"+
args.compositingMethod+
"_"+
startYearT+
"_"+
endYearT+
"_"+
args.startJulian+
"_"+
args.endJulian;args.exportPath=args.exportPathRoot+"/"+args.exportName;composite=composite.set(args);Map.addLayer(composite,vizParamsTrue10k,args.yearUsed.toString()+" True Color "+args.toaOrSR,false);Map.addLayer(composite,vizParamsFalse10k,args.yearUsed.toString()+" False Color "+args.toaOrSR,false);print("Exporting:",composite);exportToAssetWrapper(composite,args.exportName,args.exportPath,args.pyramidingPolicy,args.studyArea,args.scale,args.crs,args.transform);});}
function getLandsatWrapper(){var defaultArgs={studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,timebuffer:0,weights:[1],compositingMethod:"medoid",toaOrSR:"SR",includeSLCOffL7:false,defringeL5:false,applyCloudScore:false,applyFmaskCloudMask:true,applyTDOM:false,applyFmaskCloudShadowMask:true,applyFmaskSnowMask:false,cloudScoreThresh:10,performCloudScoreOffset:true,cloudScorePctl:10,zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,correctIllumination:false,correctScale:250,exportComposites:false,outputName:"Landsat-Composite",exportPathRoot:"users/ianhousman/test",crs:"EPSG:5070",transform:[30,0,-2361915.0,0,-30,3177735.0],scale:null,resampleMethod:"near",harmonizeOLI:false,preComputedCloudScoreOffset:null,preComputedTDOMIRMean:null,preComputedTDOMIRStdDev:null,landsatCollectionVersion:"C2",};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();args.origin="Landsat";args.wrapOffset=0;if(args.startJulian>args.endJulian){args.wrapOffset=365;}
args.startDate=ee.Date.fromYMD(args.startYear,1,1).advance(args.startJulian-1,"day");args.endDate=ee.Date.fromYMD(args.endYear,1,1).advance(args.endJulian-1+args.wrapOffset,"day");print("Start and end dates:",args.startDate,args.endDate);var ls=getProcessedLandsatScenes(args);if(args.correctIllumination){print("Adding zenith and azimuth for terrain correction");ls=ls.map(function(img){return addZenithAzimuth(img,args.toaOrSR);});}
args.ls=ls;var ts=compositeTimeSeries(args);if(args.correctIllumination){var f=ee.Image(ts.first());Map.addLayer(f,vizParamsFalse,"First-non-illuminated",false);print("Correcting illumination");ts=ts.map(illuminationCondition).map(function(img){return illuminationCorrection(img,args.correctScale,args.studyArea);});var f=ee.Image(ts.first());Map.addLayer(f,vizParamsFalse,"First-illuminated",false);}
args.collection=ts;if(args.exportComposites){if(args.compositingMethod=="medoid"){args.exportBands=["blue","green","red","nir","swir1","swir2","temp","compositeObsCount","sensor","year","julianDay",];args.nonDivideBands=["temp","compositeObsCount","sensor","year","julianDay",];}else{args.exportBands=["blue","green","red","nir","swir1","swir2","temp","compositeObsCount",];args.nonDivideBands=["temp","compositeObsCount"];}
print("Args:",args);exportCompositeCollection(args);}
args.processedScenes=ls;args.processedComposites=ts;return args;}
function getProcessedLandsatScenes(){var defaultArgs={studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,toaOrSR:"SR",includeSLCOffL7:false,defringeL5:false,applyCloudScore:false,applyFmaskCloudMask:true,applyTDOM:false,applyFmaskCloudShadowMask:true,applyFmaskSnowMask:false,cloudScoreThresh:10,performCloudScoreOffset:true,cloudScorePctl:10,zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,resampleMethod:"near",harmonizeOLI:false,preComputedCloudScoreOffset:null,preComputedTDOMIRMean:null,preComputedTDOMIRStdDev:null,landsatCollectionVersion:"C2",};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();args.origin="Landsat";args.wrapOffset=0;if(args.startJulian>args.endJulian){args.wrapOffset=365;}
args.startDate=ee.Date.fromYMD(args.startYear,1,1).advance(args.startJulian-1,"day");args.endDate=ee.Date.fromYMD(args.endYear,1,1).advance(args.endJulian-1+args.wrapOffset,"day");print("Start and end dates:",args.startDate,args.endDate);args.addPixelQA;if(args.toaOrSR.toLowerCase()==="toa"&&args.landsatCollectionVersion.toLowerCase()=="c1"&&(args.applyFmaskCloudMask===true||args.applyFmaskCloudShadowMask===true||args.applyFmaskSnowMask===true)){args.addPixelQA=true;}else{args.addPixelQA=false;}
var ls=getLandsat(args);if(args.applyCloudScore){print("Applying cloudScore");ls=applyCloudScoreAlgorithm(ls,landsatCloudScore,args.cloudScoreThresh,args.cloudScorePctl,args.contractPixels,args.dilatePixels,args.performCloudScoreOffset,args.preComputedCloudScoreOffset);}
if(args.applyFmaskCloudMask){print("Applying Fmask cloud mask");ls=ls.map(function(img){return applyBitMask(img,fmaskBitDict[args.landsatCollectionVersion]["cloud"],landsatFmaskBandNameDict[args.landsatCollectionVersion]);});}
if(args.applyTDOM){print("Applying TDOM");args.collection=ls;ls=simpleTDOM2(args);}
if(args.applyFmaskCloudShadowMask){print("Applying Fmask shadow mask");ls=ls.map(function(img){return applyBitMask(img,fmaskBitDict[args.landsatCollectionVersion]["shadow"],landsatFmaskBandNameDict[args.landsatCollectionVersion]);});}
if(args.applyFmaskSnowMask){print("Applying Fmask snow mask");ls=ls.map(function(img){return applyBitMask(img,fmaskBitDict[args.landsatCollectionVersion]["snow"],landsatFmaskBandNameDict[args.landsatCollectionVersion]);});}
ls=ls.map(simpleAddIndices).map(getTasseledCap).map(simpleAddTCAngles);ls=ls.map(function(img){return addSensorBand(img,args.landsatCollectionVersion+"_landsat",args.toaOrSR);});return ls.set(args);}
function getProcessedSentinel2Scenes(){var defaultArgs={studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,applyQABand:false,applyCloudScore:false,applyShadowShift:false,applyTDOM:false,cloudScoreThresh:20,performCloudScoreOffset:false,cloudScorePctl:10,cloudHeights:ee.List.sequence(500,10000,500),zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,resampleMethod:"aggregate",toaOrSR:"TOA",convertToDailyMosaics:true,applyCloudProbability:false,preComputedCloudScoreOffset:null,preComputedTDOMIRMean:null,preComputedTDOMIRStdDev:null,cloudProbThresh:40,applyCloudScorePlus:true,cloudScorePlusThresh:0.6,cloudScorePlusScore:"cs",};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();args.origin="Sentinel2";args.addCloudProbability=args.applyCloudProbability;args.addCloudScorePlus=args.applyCloudScorePlus;print(args);args.wrapOffset=0;if(args.startJulian>args.endJulian){args.wrapOffset=365;}
args.startDate=ee.Date.fromYMD(args.startYear,1,1).advance(args.startJulian-1,"day");args.endDate=ee.Date.fromYMD(args.endYear,1,1).advance(args.endJulian-1+args.wrapOffset,"day");print("Start and end dates:",args.startDate,args.endDate);var s2s=getS2(args);if(args.applyQABand){print("Applying QA band cloud mask");s2s=s2s.map(maskS2clouds);}
if(args.applyCloudScore){print("Applying cloudScore");s2s=applyCloudScoreAlgorithm(s2s,sentinel2CloudScore,args.cloudScoreThresh,args.cloudScorePctl,args.contractPixels,args.dilatePixels,args.performCloudScoreOffset,args.preComputedCloudScoreOffset);}
if(args.applyCloudProbability){print("Applying cloud probability");s2s=s2s.map(function(img){return img.updateMask(img.select(["cloud_probability"]).lte(args.cloudProbThresh));});}
if(args.applyCloudScorePlus){print("Applying cloudScore+");s2s=s2s.map(function(img){return img.updateMask(img.select(["cloudScorePlus"]).gte(args.cloudScorePlusThresh));});}
if(args.applyShadowShift){print("Applying shadow shift");s2s=s2s.map(function(img){return projectShadowsWrapper(img,cloudScoreThresh,shadowSumThresh,contractPixels,dilatePixels,cloudHeights);});}
if(args.applyTDOM){print("Applying TDOM");args.collection=s2s;s2s=simpleTDOM2(args);}
s2s=s2s.map(simpleAddIndices).map(getTasseledCap).map(simpleAddTCAngles);s2s=s2s.map(function(img){return addSensorBand(img,"sentinel2",args.toaOrSR);});return s2s.set(args);}
function getSentinel2Wrapper(){var defaultArgs={studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,timebuffer:0,weights:[1],compositingMethod:"medoid",applyQABand:false,applyCloudScore:false,applyShadowShift:false,applyTDOM:false,cloudScoreThresh:20,performCloudScoreOffset:true,cloudScorePctl:10,cloudHeights:ee.List.sequence(500,10000,500),zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,correctIllumination:false,correctScale:250,exportComposites:false,outputName:"Sentinel2-Composite",exportPathRoot:"users/iwhousman/test",crs:"EPSG:5070",transform:[10,0,-2361915.0,0,-10,3177735.0],scale:null,resampleMethod:"aggregate",toaOrSR:"TOA",convertToDailyMosaics:true,applyCloudProbability:false,preComputedCloudScoreOffset:null,preComputedTDOMIRMean:null,preComputedTDOMIRStdDev:null,cloudProbThresh:40,applyCloudScorePlus:true,cloudScorePlusThresh:0.6,};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();args.origin="Sentinel2";var s2s=getProcessedSentinel2Scenes(args);args.ls=s2s;var ts=compositeTimeSeries(args);print("ts",ts);args.collection=ts;if(args.exportComposites){var exportBandDict={SR_medoid:["cb","blue","green","red","re1","re2","re3","nir","nir2","waterVapor","swir1","swir2","compositeObsCount","sensor","year","julianDay",],SR_median:["cb","blue","green","red","re1","re2","re3","nir","nir2","waterVapor","swir1","swir2","compositeObsCount",],TOA_medoid:["cb","blue","green","red","re1","re2","re3","nir","nir2","waterVapor","cirrus","swir1","swir2","compositeObsCount","sensor","year","julianDay",],TOA_median:["cb","blue","green","red","re1","re2","re3","nir","nir2","waterVapor","cirrus","swir1","swir2","compositeObsCount",],};var nonDivideBandDict={medoid:["compositeObsCount","sensor","year","julianDay"],median:["compositeObsCount"],};args.exportBands=exportBandDict[args.toaOrSR+"_"+args.compositingMethod];args.nonDivideBands=nonDivideBandDict[args.compositingMethod];exportCompositeCollection(args);}
args.processedScenes=s2s;args.processedComposites=ts;return args;return args;}
function getProcessedLandsatAndSentinel2Scenes(){var defaultArgs={studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,toaOrSR:"TOA",includeSLCOffL7:false,defringeL5:false,applyQABand:false,applyCloudProbability:false,applyShadowShift:false,applyCloudScoreLandsat:false,applyCloudScoreSentinel2:false,applyTDOMLandsat:true,applyTDOMSentinel2:false,applyFmaskCloudMask:true,applyFmaskCloudShadowMask:true,applyFmaskSnowMask:false,cloudHeights:ee.List.sequence(500,10000,500),cloudScoreThresh:20,performCloudScoreOffset:true,cloudScorePctl:10,zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,landsatResampleMethod:"near",sentinel2ResampleMethod:"aggregate",convertToDailyMosaics:true,runChastainHarmonization:true,correctIllumination:false,correctScale:250,preComputedLandsatCloudScoreOffset:null,preComputedLandsatTDOMIRMean:null,preComputedLandsatTDOMIRStdDev:null,preComputedSentinel2CloudScoreOffset:null,preComputedSentinel2TDOMIRMean:null,preComputedSentinel2TDOMIRStdDev:null,cloudProbThresh:40,landsatCollectionVersion:"C2",applyCloudScorePlus:true,cloudScorePlusThresh:0.6,};var args=prepArgumentsObject(arguments,defaultArgs);args.toaOrSR=args.toaOrSR.toUpperCase();if(args.toaOrSR==="SR"){args.runChastainHarmonization=false;}
print("initial args:",typeof args,args);args.preComputedCloudScoreOffset=args.preComputedLandsatCloudScoreOffset;args.preComputedTDOMIRMean=args.preComputedLandsatTDOMIRMean;args.preComputedTDOMIRStdDev=args.preComputedSentinel2TDOMIRStdDev;args.applyCloudScore=args.applyCloudScoreLandsat;args.applyTDOM=args.applyTDOMLandsat;args.resampleMethod=args.landsatResampleMethod;var ls=getProcessedLandsatScenes(args);args.preComputedCloudScoreOffset=args.preComputedSentinel2CloudScoreOffset;args.preComputedTDOMIRMean=args.preComputedSentinel2TDOMIRMean;args.preComputedTDOMIRStdDev=args.preComputedSentinel2TDOMIRStdDev;args.applyCloudScore=args.applyCloudScoreSentinel2;args.applyTDOM=args.applyTDOMSentinel2;args.resampleMethod=args.sentinel2ResampleMethod;var s2s=getProcessedSentinel2Scenes(args);var commonBands=["blue","green","red","nir","swir1","swir2","sensor"];ls=ls.select(commonBands);s2s=s2s.select(commonBands);var dummyImage=ee.Image(ee.ImageCollection(ee.Algorithms.If(ls.toList(1).length().gt(0),ls,s2s)).first());ls=fillEmptyCollections(ls,dummyImage);s2s=fillEmptyCollections(s2s,dummyImage);if(args.runChastainHarmonization&&args.toaOrSR==="TOA"){var tm=ls.filter(ee.Filter.inList("SENSOR_ID",["TM","ETM"]));var oli=ls.filter(ee.Filter.eq("SENSOR_ID","OLI_TIRS"));var msi=s2s;tm=fillEmptyCollections(tm,ee.Image(ls.first()));oli=fillEmptyCollections(oli,ee.Image(ls.first()));print("Running Chastain et al 2019 harmonization");oli=oli.map(function(img){return harmonizationChastain(img,"OLI","ETM");});msi=msi.map(function(img){return harmonizationChastain(img,"MSI","ETM");});s2s=msi;ls=ee.ImageCollection(tm.merge(oli));}
var merged=ls.merge(s2s);merged=merged.map(simpleAddIndices).map(getTasseledCap).map(simpleAddTCAngles);args.origin="Landsat-Sentinel2-Hybrid";merged=merged.set(args);print("Total s2s:",s2s.size());print("Total landsats:",ls.size());print("Total merged:",merged.size());print(merged.aggregate_histogram("sensor"));return merged;}
function coRegisterCollection(images,referenceBands){if(referenceBands===undefined||referenceBands===null){referenceBands=["nir"];}
var referenceImageIndex=0;var referenceImage=ee.Image(images.toList(referenceImageIndex+1).get(referenceImageIndex)).select(referenceBands);function registerImage(image){var displacement_params={referenceImage:referenceImage,maxOffset:20.0,projection:null,patchWidth:20.0,stiffness:5,};var displacement=image.select(referenceBands).displacement(displacement_params);return image.displace(displacement);}
var out=ee.ImageCollection(ee.ImageCollection(images.toList(10000,1)).map(registerImage));out=ee.ImageCollection(images.limit(1).merge(out));return out;}
function coRegisterGroups(imgs,fieldName,fieldIsNumeric){if(fieldName===undefined||fieldName===null){fieldName="SENSING_ORBIT_NUMBER";}
if(fieldIsNumeric===undefined||fieldIsNumeric===null){fieldIsNumeric=true;}
var groups=ee.Dictionary(imgs.aggregate_histogram(fieldName)).keys();if(fieldIsNumeric){groups=groups.map(function(n){return ee.Number.parse(n);});}
var out=ee.ImageCollection(ee.FeatureCollection(groups.map(function(group){return coRegisterCollection(imgs.filter(ee.Filter.eq(fieldName,group)));})).flatten());return out;}
function getLandsatAndSentinel2HybridWrapper(){var defaultArgs={studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,timebuffer:0,weights:[1],compositingMethod:"medoid",toaOrSR:"TOA",includeSLCOffL7:false,defringeL5:false,applyQABand:false,applyCloudProbability:false,applyShadowShift:false,applyCloudScoreLandsat:false,applyCloudScoreSentinel2:false,applyTDOMLandsat:true,applyTDOMSentinel2:false,applyFmaskCloudMask:true,applyFmaskCloudShadowMask:true,applyFmaskSnowMask:false,cloudHeights:ee.List.sequence(500,10000,500),cloudScoreThresh:20,performCloudScoreOffset:true,cloudScorePctl:10,zScoreThresh:-1,shadowSumThresh:0.35,contractPixels:1.5,dilatePixels:3.5,landsatResampleMethod:"near",sentinel2ResampleMethod:"aggregate",convertToDailyMosaics:true,runChastainHarmonization:true,correctIllumination:false,correctScale:250,exportComposites:false,outputName:"Landsat-Sentinel2-Hybrid",exportPathRoot:"users/iwhousman/test/compositeCollection",crs:"EPSG:5070",transform:[30,0,-2361915.0,0,-30,3177735.0],scale:null,preComputedLandsatCloudScoreOffset:null,preComputedLandsatTDOMIRMean:null,preComputedLandsatTDOMIRStdDev:null,preComputedSentinel2CloudScoreOffset:null,preComputedSentinel2TDOMIRMean:null,preComputedSentinel2TDOMIRStdDev:null,cloudProbThresh:40,landsatCollectionVersion:"C2",applyCloudScorePlusSentinel2:true,cloudScorePlusThresh:0.6,};var args=prepArgumentsObject(arguments,defaultArgs);args.applyCloudScorePlus=args.applyCloudScorePlusSentinel2;var merged=getProcessedLandsatAndSentinel2Scenes(args);print("Merged",merged);args.ls=merged;var composites=compositeTimeSeries(args);args.collection=composites;args.origin="Landsat-Sentinel2-Hybrid";print(composites);if(args.exportComposites){var exportBandDict={medoid:["blue","green","red","nir","swir1","swir2","compositeObsCount","sensor","year","julianDay",],median:["blue","green","red","nir","swir1","swir2","compositeObsCount",],};var nonDivideBandDict={medoid:["compositeObsCount","sensor","year","julianDay"],median:["compositeObsCount"],};args.exportBands=exportBandDict[args.compositingMethod];args.nonDivideBands=nonDivideBandDict[args.compositingMethod];print("Args:",args);exportCompositeCollection(args);}
args.processedScenes=merged;args.processedComposites=composites;return args;}
function getHarmonicList(yearDateImg,transformBandName,harmonicList){var t=yearDateImg.select([transformBandName]);var selectBands=ee.List.sequence(0,harmonicList.length-1);var sinNames=harmonicList.map(function(h){var ht=h*100;return ee.String("sin_").cat(ht.toString()).cat("_").cat(transformBandName);});var cosNames=harmonicList.map(function(h){var ht=h*100;return ee.String("cos_").cat(ht.toString()).cat("_").cat(transformBandName);});var multipliers=ee.Image(harmonicList).multiply(ee.Number(Math.PI).float());var sinInd=t.multiply(ee.Image(multipliers)).sin().select(selectBands,sinNames).float();var cosInd=t.multiply(ee.Image(multipliers)).cos().select(selectBands,cosNames).float();return yearDateImg.addBands(sinInd.addBands(cosInd));}
function getHarmonics2(collection,transformBandName,harmonicList,detrend){if(detrend===undefined||detrend===null){detrend=false;}
var depBandNames=ee.Image(collection.first()).bandNames().remove(transformBandName);var depBandNumbers=depBandNames.map(function(dbn){return depBandNames.indexOf(dbn);});var out=collection.map(function(img){var outT=getHarmonicList(img,transformBandName,harmonicList).copyProperties(img,["system:time_start","system:time_end"]);return outT;});if(!detrend){var outBandNames=ee.Image(out.first()).bandNames().removeAll(["year"]);out=out.select(outBandNames);}
var indBandNames=ee.Image(out.first()).bandNames().removeAll(depBandNames);var indBandNumbers=indBandNames.map(function(ind){return ee.Image(out.first()).bandNames().indexOf(ind);});out=out.set({indBandNames:indBandNames,depBandNames:depBandNames,indBandNumbers:indBandNumbers,depBandNumbers:depBandNumbers,});return out;}
function newRobustMultipleLinear2(dependentsIndependents){var dependentBands=ee.List(dependentsIndependents.get("depBandNumbers"));var independentBands=ee.List(dependentsIndependents.get("indBandNumbers"));var bns=ee.Image(dependentsIndependents.first()).bandNames();var dependents=ee.List(dependentsIndependents.get("depBandNames"));var independents=ee.List(dependentsIndependents.get("indBandNames"));var noIndependents=independents.length().add(1);var noDependents=dependents.length();var outNames=ee.List(["intercept"]).cat(independents);var forFit=dependentsIndependents.map(function(img){var out=img.addBands(ee.Image(1).select([0],["constant"]));out=out.select(ee.List(["constant",independents]).flatten());return out.addBands(img.select(dependents));});var reducerOut=forFit.reduce(ee.Reducer.linearRegression(noIndependents,noDependents));reducerOut=reducerOut.select([0],["coefficients"]).arrayTranspose().arrayFlatten([dependents,outNames]);reducerOut=reducerOut.set({noDependents:ee.Number(noDependents),modelLength:ee.Number(noIndependents),});return reducerOut;}
var monthRemap=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,];var monthDayRemap=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,];var julianDay=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,];function getPeakDate(coeffs,peakDirection){if(peakDirection===null||peakDirection===undefined){peakDirection=1;}
var sin=coeffs.select([0]);var cos=coeffs.select([1]);var greenDate=sin.divide(cos).atan().divide(2*Math.PI).rename(["peakDate"]);var greenDateLater=greenDate.add(0.5);var predicted1=coeffs.select([0]).add(sin.multiply(greenDate.multiply(2*Math.PI).sin())).add(cos.multiply(greenDate.multiply(2*Math.PI).cos())).rename("predicted").multiply(ee.Image.constant(peakDirection)).addBands(greenDate);var predicted2=coeffs.select([0]).add(sin.multiply(greenDateLater.multiply(2*Math.PI).sin())).add(cos.multiply(greenDateLater.multiply(2*Math.PI).cos())).rename("predicted").multiply(ee.Image.constant(peakDirection)).addBands(greenDateLater);var finalGreenDate=ee.ImageCollection([predicted1,predicted2]).qualityMosaic("predicted").select(["peakDate"]).rename(["peakJulianDay"]);finalGreenDate=finalGreenDate.where(finalGreenDate.lt(0),greenDate.add(1)).multiply(365).int16();var greenMonth=finalGreenDate.remap(julianDay,monthRemap).rename(["peakMonth"]);var greenMonthDay=finalGreenDate.remap(julianDay,monthDayRemap).rename(["peakDayOfMonth"]);var greenStack=finalGreenDate.addBands(greenMonth).addBands(greenMonthDay);return greenStack;}
function getAreaUnderCurve(harmCoeffs,t0,t1){if(t0===null||t0===undefined){t0=0;}
if(t1===null||t1===undefined){t1=1;}
var amplitude=harmCoeffs.select([1]).hypot(harmCoeffs.select([0]));var intereceptNormalized=amplitude;var sin=harmCoeffs.select([0]);var cos=harmCoeffs.select([1]);var sum0=intereceptNormalized.multiply(t0).subtract(sin.divide(2*Math.PI).multiply(Math.sin(2*Math.PI*t0))).add(cos.divide(2*Math.PI).multiply(Math.cos(2*Math.PI*t0)));var sum1=intereceptNormalized.multiply(t1).subtract(sin.divide(2*Math.PI).multiply(Math.sin(2*Math.PI*t1))).add(cos.divide(2*Math.PI).multiply(Math.cos(2*Math.PI*t1)));var leftSum=sum1.subtract(sum0).rename(["AUC"]);return leftSum;}
function getPhaseAmplitudePeak(coeffs,t0,t1){if(t0===null||t0===undefined){t0=0;}
if(t1===null||t1===undefined){t1=1;}
var bandNames=coeffs.bandNames();var bandNumber=bandNames.length();var noDependents=ee.Number(coeffs.get("noDependents"));var modelLength=ee.Number(coeffs.get("modelLength"));var interceptBands=ee.List.sequence(0,bandNumber.subtract(1),modelLength);var models=ee.List.sequence(0,noDependents.subtract(1));var parsedModel=models.map(function(mn){mn=ee.Number(mn);return bandNames.slice(mn.multiply(modelLength),mn.multiply(modelLength).add(modelLength));});var phaseAmplitude=parsedModel.map(function(pm){pm=ee.List(pm);var modelCoeffs=coeffs.select(pm);var intercept=modelCoeffs.select(".*_intercept");var harmCoeffs=modelCoeffs.select(".*_200_year");var outName=ee.String(ee.String(pm.get(1)).split("_").get(0));var sign=ee.Number(ee.Dictionary(changeDirDict).get(outName)).multiply(-1);var amplitude=harmCoeffs.select([1]).hypot(harmCoeffs.select([0])).multiply(2).rename([outName.cat("_amplitude")]);var phase=harmCoeffs.select([0]).atan2(harmCoeffs.select([1])).unitScale(-Math.PI,Math.PI).rename([outName.cat("_phase")]);var peakDate=getPeakDate(harmCoeffs,sign);var peakDateBandNames=peakDate.bandNames();peakDateBandNames=peakDateBandNames.map(function(bn){return outName.cat(ee.String("_").cat(ee.String(bn)));});var leftSum=getAreaUnderCurve(harmCoeffs,t0,t1);var leftSumBandNames=leftSum.bandNames();leftSumBandNames=leftSumBandNames.map(function(bn){return outName.cat(ee.String("_").cat(ee.String(bn)));});return amplitude.addBands(phase).addBands(peakDate.rename(peakDateBandNames)).addBands(leftSum.rename(leftSumBandNames));});phaseAmplitude=ee.ImageCollection.fromImages(phaseAmplitude);phaseAmplitude=ee.Image(collectionToImage(phaseAmplitude)).float().copyProperties(coeffs,["system:time_start"]);return phaseAmplitude;}
function newPredict(coeffs,harmonics){var bandNames=coeffs.bandNames();var bandNumber=bandNames.length();var noDependents=ee.Number(coeffs.get("noDependents"));var modelLength=ee.Number(coeffs.get("modelLength"));var interceptBands=ee.List.sequence(0,bandNumber.subtract(1),modelLength);var timeBand=ee.List(harmonics.get("indBandNames")).get(0);var actualBands=harmonics.get("depBandNumbers");var indBands=harmonics.get("indBandNumbers");var indBandNames=ee.List(harmonics.get("indBandNames"));var depBandNames=ee.List(harmonics.get("depBandNames"));var predictedBandNames=depBandNames.map(function(depbnms){return ee.String(depbnms).cat("_predicted");});var predictedBandNumbers=ee.List.sequence(0,predictedBandNames.length().subtract(1));var models=ee.List.sequence(0,noDependents.subtract(1));var parsedModel=models.map(function(mn){mn=ee.Number(mn);return bandNames.slice(mn.multiply(modelLength),mn.multiply(modelLength).add(modelLength));});var predicted=harmonics.map(function(img){var time=img.select(timeBand);var actual=img.select(actualBands).float();var predictorBands=img.select(indBandNames);var predictedList=parsedModel.map(function(pm){pm=ee.List(pm);var modelCoeffs=coeffs.select(pm);var outName=ee.String(pm.get(1)).cat("_predicted");var intercept=modelCoeffs.select(modelCoeffs.bandNames().slice(0,1));var others=modelCoeffs.select(modelCoeffs.bandNames().slice(1,null));predicted=predictorBands.multiply(others).reduce(ee.Reducer.sum()).add(intercept).float();return predicted.float();});predictedList=ee.ImageCollection.fromImages(predictedList);var predictedImage=collectionToImage(predictedList).select(predictedBandNumbers,predictedBandNames);var out=actual.addBands(predictedImage.float()).copyProperties(img,["system:time_start","system:time_end"]);return out;});predicted=ee.ImageCollection(predicted);return predicted;}
function getDateStack(startYear,endYear,startJulian,endJulian,frequency){var years=ee.List.sequence(startYear,endYear);var dates=ee.List.sequence(startJulian,endJulian,frequency);var dateSets=years.map(function(yr){var ds=dates.map(function(d){return ee.Date.fromYMD(yr,1,1).advance(d,"day");});return ds;});var l=range(1,indexNames.length+1);l=l.map(function(i){return i%i;});var c=ee.Image(l).rename(indexNames);c=c.divide(c);dateSets=dateSets.flatten();var stack=dateSets.map(function(dt){dt=ee.Date(dt);var y=dt.get("year");var d=dt.getFraction("year");var i=ee.Image(y.add(d)).float().select([0],["year"]);i=c.addBands(i).float().set("system:time_start",dt.millis()).set("system:time_end",dt.advance(frequency,"day").millis());return i;});stack=ee.ImageCollection.fromImages(stack);return stack;}
function getHarmonicCoefficientsAndFit(allImages,indexNames,whichHarmonics,detrend){if(detrend===undefined||detrend===null){detrend=false;}
if(whichHarmonics===undefined||whichHarmonics===null){whichHarmonics=[2];}
var allIndices=allImages.select(indexNames);if(detrend){allIndices=allIndices.map(addDateBand);}else{allIndices=allIndices.map(addYearFractionBand);}
var withHarmonics=getHarmonics2(allIndices,"year",whichHarmonics,detrend);var withHarmonicsBns=ee.Image(withHarmonics.first()).bandNames().slice(indexNames.length+1,null);var coeffs=newRobustMultipleLinear2(withHarmonics);var predicted=newPredict(coeffs,withHarmonics);return[coeffs,predicted];}
function synthImage(coeffs,dateImage,indexNames,harmonics,detrend){var constImage=ee.Image(1);if(detrend){constImage=constImage.addBands(dateImage);}
harmonics.map(function(harm){constImage=constImage.addBands(ee.Image([dateImage.multiply(harm*Math.PI).sin()])).addBands(ee.Image([dateImage.multiply(harm*Math.PI).cos()]));});var out=ee.Image(1);out=ee.Image(ee.List(indexNames).iterate(function(bn,out){bn=ee.String(bn);var coeffssBn=coeffs.select(ee.String(bn).cat(".*"));var predicted=constImage.multiply(coeffssBn).reduce("sum").rename(bn);return ee.Image(out).addBands(predicted);},out));out=out.select(ee.List.sequence(1,out.bandNames().size().subtract(1)));return out;}
function getClimateWrapper(collectionName,studyArea,startYear,endYear,startJulian,endJulian,timebuffer,weights,compositingReducer,exportComposites,exportPathRoot,crs,transform,scale,exportBands){var defaultArgs={collectionName:"NASA/ORNL/DAYMET_V4",studyArea:null,startYear:null,endYear:null,startJulian:null,endJulian:null,timebuffer:0,weights:[1],compositingReducer:ee.Reducer.mean(),exportComposites:false,exportPathRoot:"users/iwhousman/test/climate-test",crs:"EPSG:5070",transform:[30,0,-2361915.0,0,-30,3177735.0],scale:null,exportBands:null,};var args=prepArgumentsObject(arguments,defaultArgs);print(args);args.wrapOffset=0;if(args.startJulian>args.endJulian){args.wrapOffset=365;}
args.startDate=ee.Date.fromYMD(args.startYear,1,1).advance(args.startJulian-1,"day");args.endDate=ee.Date.fromYMD(args.endYear,1,1).advance(args.endJulian-1+args.wrapOffset,"day");print("Start and end dates:",args.startDate,args.endDate);print("Julian days are:",args.startJulian,args.endJulian);var c=ee.ImageCollection(args.collectionName).filterBounds(args.studyArea).filterDate(args.startDate,args.endDate.advance(1,"day")).filter(ee.Filter.calendarRange(args.startJulian,args.endJulian));c=c.map(function(img){return img.resample("bicubic");});var ts=compositeTimeSeries(c,args.startYear,args.endYear,args.startJulian,args.endJulian,args.timebuffer,args.weights,null,args.compositingReducer);if(args.exportComposites){if(args.exportBands===null||args.exportBands===undefined){args.exportBands=ee.Image(ts.first()).bandNames();}
print("Export bands are:",args.exportBands);exportCollection(args.exportPathRoot,args.collectionName,args.studyArea,args.crs,args.transform,args.scale,ts,args.startYear,args.endYear,args.startJulian,args.endJulian,args.compositingReducer,args.timebuffer,args.exportBands);}
return ts;}
var addAbsDiff=function(inCollection,qualityBand,percentile,sign){var bestQuality=inCollection.select([qualityBand]).reduce(ee.Reducer.percentile([percentile]));var out=inCollection.map(function(image){var delta=image.select([qualityBand]).subtract(bestQuality).abs().multiply(sign);return image.addBands(delta.select([0],["delta"]));});return out;};var customQualityMosaic=function(inCollection,qualityBand,percentile){var inCollectionDelta=addAbsDiff(inCollection,qualityBand,percentile,-1);return inCollectionDelta.qualityMosaic("delta");};function simpleWaterMask(img,contractPixels,slope_thresh,elevationImagePath,elevationFocalMeanRadius){if(contractPixels===null||contractPixels===undefined){contractPixels=0;}
if(slope_thresh===null||slope_thresh===undefined){slope_thresh=10;}
if(elevationImagePath===null||elevationImagePath===undefined){elevationImagePath="USGS/NED";}
if(elevationFocalMeanRadius===null||elevationFocalMeanRadius===undefined){elevationFocalMeanRadius=5.5;}
img=addTCAngles(img);var ned=ee.Image(elevationImagePath).resample("bicubic");var slope=ee.Terrain.slope(ned.focal_mean(elevationFocalMeanRadius));var flat=slope.lte(slope_thresh);var waterMask=img.select(["tcAngleBW"]).gte(-0.05).and(img.select(["tcAngleBG"]).lte(0.05)).and(img.select(["brightness"]).lt(0.3)).and(flat).focal_min(contractPixels);return waterMask.rename(["waterMask"]);}
var HoCalcGreenness=function(img){var r=img.select(["red"]);var g=img.select(["green"]);var b=img.select(["blue"]);var I=r.add(g).add(b).rename(["I"]);var mins=r.min(g).min(b).rename(["mins"]);var H=mins.where(mins.eq(r),b.subtract(r).divide(I.subtract(r.multiply(3))).add(1));H=H.where(mins.eq(g),r.subtract(g).divide(I.subtract(g.multiply(3))).add(2));H=H.where(mins.eq(b),g.subtract(b).divide(I.subtract(b.multiply(3))));var Hthresh=H.lte(1.6);return H.rename("H");};exports.HoCalcAlgorithm1=function(image){var truecolor=1;var testThresh=false;var bloomThreshold=0.02346;var greenessThreshold=1.6;image=image.addBands(HoCalcGreenness(image));var bloom1=image.select("nir").subtract(image.select("swir1").multiply(1.03)).rename("bloom1");var bloom1_mask=image.select("H").lte(greenessThreshold).rename(["bloom1_mask"]);return image.addBands(bloom1).addBands(bloom1_mask);};exports.HoCalcAlgorithm2=function(image){var bloom2=image.select("green").divide(image.select("blue")).rename(["bloom2"]);return image.addBands(bloom2);};exports.eeObjInfo=eeObjInfo;exports.getObjType=getObjType;exports.eeObjServerSide=eeObjServerSide;exports.sieve=sieve;exports.setNoData=setNoData;exports.addSensorBand=addSensorBand;exports.addJulianDayBand=addJulianDayBand;exports.addYearYearFractionBand=addYearYearFractionBand;exports.addYearBand=addYearBand;exports.addDateBand=addDateBand;exports.addYearJulianDayBand=addYearJulianDayBand;exports.offsetImageDate=offsetImageDate;exports.addFullYearJulianDayBand=addFullYearJulianDayBand;exports.wrapDates=wrapDates;exports.collectionToImage=collectionToImage;exports.getImageCollection=getImageCollection;exports.getLandsat=getLandsat;exports.getS2=getS2;exports.getSentinel2=getSentinel2;exports.getS1=getS1;exports.RefinedLee=RefinedLee;exports.vizParamsFalse=vizParamsFalse;exports.vizParamsTrue=vizParamsTrue;exports.vizParamsFalse10k=vizParamsFalse10k;exports.vizParamsTrue10k=vizParamsTrue10k;exports.rescale=rescale;exports.landsatCloudScore=landsatCloudScore;exports.sentinel2CloudScore=sentinel2CloudScore;exports.sentinel2SnowMask=sentinel2SnowMask;exports.projectShadowsWrapper=projectShadowsWrapper;exports.applyCloudScoreAlgorithm=applyCloudScoreAlgorithm;exports.cFmask=cFmask;exports.applyBitMask=applyBitMask;exports.simpleTDOM2=simpleTDOM2;exports.medoidMosaicMSD=medoidMosaicMSD;exports.addIndices=addIndices;exports.addSAVIandEVI=addSAVIandEVI;exports.simpleAddIndices=simpleAddIndices;exports.getTasseledCap=getTasseledCap;exports.simpleGetTasseledCap=simpleGetTasseledCap;exports.simpleAddTCAngles=simpleAddTCAngles;exports.compositeTimeSeries=compositeTimeSeries;exports.addZenithAzimuth=addZenithAzimuth;exports.illuminationCorrection=illuminationCorrection;exports.illuminationCondition=illuminationCondition;exports.addTCAngles=addTCAngles;exports.simpleAddTCAngles=simpleAddTCAngles;exports.exportCompositeCollection=exportCompositeCollection;exports.getProcessedLandsatScenes=getProcessedLandsatScenes;exports.getProcessedSentinel2Scenes=getProcessedSentinel2Scenes;exports.getProcessedLandsatAndSentinel2Scenes=getProcessedLandsatAndSentinel2Scenes;exports.coRegisterCollection=coRegisterCollection;exports.coRegisterGroups=coRegisterGroups;exports.getLandsatWrapper=getLandsatWrapper;exports.getSentinel2Wrapper=getSentinel2Wrapper;exports.getLandsatAndSentinel2HybridWrapper=getLandsatAndSentinel2HybridWrapper;exports.getModisData=getModisData;exports.modisCloudScore=modisCloudScore;exports.despikeCollection=despikeCollection;exports.exportToAssetWrapper=exportToAssetWrapper;exports.exportToAssetWrapper2=exportToAssetWrapper2;exports.exportToDriveWrapper=exportToDriveWrapper;exports.exportToCloudStorageWrapper=exportToCloudStorageWrapper;exports.exportCollection=exportCollection;exports.joinCollections=joinCollections;exports.smartJoin=smartJoin;exports.spatioTemporalJoin=spatioTemporalJoin;exports.joinFeatureCollections=joinFeatureCollections;exports.listToString=listToString;exports.harmonizationRoy=harmonizationRoy;exports.harmonizationChastain=harmonizationChastain;exports.fillEmptyCollections=fillEmptyCollections;exports.nDayComposites=nDayComposites;exports.getHarmonicCoefficientsAndFit=getHarmonicCoefficientsAndFit;exports.getPhaseAmplitudePeak=getPhaseAmplitudePeak;exports.getAreaUnderCurve=getAreaUnderCurve;exports.synthImage=synthImage;exports.getClimateWrapper=getClimateWrapper;exports.exportCollection=exportCollection;exports.changeDirDict=changeDirDict;exports.addSoilIndices=addSoilIndices;exports.addAbsDiff=addAbsDiff;exports.customQualityMosaic=customQualityMosaic;exports.compositeDates=compositeDates;exports.defringeLandsat=defringeLandsat;exports.simpleWaterMask=simpleWaterMask;exports.common_projections=common_projections;exports.testAreas={};(exports.testAreas.CO=ee.Geometry.Polygon([[[-108.28630509064759,38.085343638120925],[-108.28630509064759,37.18051220092945],[-106.74821915314759,37.18051220092945],[-106.74821915314759,38.085343638120925],],],null,false)),(exports.testAreas.CA=ee.Geometry.Polygon([[[-119.96383760287506,37.138150574108714],[-119.96383760287506,36.40774412106424],[-117.95333955600006,36.40774412106424],[-117.95333955600006,37.138150574108714],],],null,false));exports.testAreas.HI=ee.Geometry.Polygon([[[-160.50824874450544,22.659814513909474],[-160.50824874450544,18.54750309959827],[-154.35590499450544,18.54750309959827],[-154.35590499450544,22.659814513909474],],],null,false);