<commit_before>/*
 * Copyright ActionML, LLC under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * ActionML licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.actionml.templates.navhinting
import akka.actor._
import cats.data.Validated
import cats.data.Validated.{Invalid, Valid}
import com.actionml.core.storage._
import com.actionml.core.template._
import com.actionml.core.validate.{JsonParser, ParseError, ValidRequestExecutionError, ValidateError}
import com.typesafe.scalalogging.LazyLogging
import org.joda.time.DateTime
import salat.dao.SalatDAO

import scala.concurrent.Future
import scala.math._
import scala.concurrent.ExecutionContext.Implicits.global


/** Creates an Actor to train for each input. The Actor works in a thread and when complete will accept any
  * new training request and start anew. In parallel queries can be made of the existing model. When training
  * is done, the live model is updated atomically. This is therefore a Kappa style learner, that is eventually
  * consistent with all input. The difference between real time and eventually is arbitrary and based on compute
  * power. All input is persisted before the model is calculated to guarantee the model can be recreated. We may
  * be able to train and persist in parallel when we switch to the new async DB client.
  */
class NavHintingAlgorithm(dataset: NavHintingDataset)
  extends Algorithm[NHQuery, NHQueryResult] with KappaAlgorithm[NavHintingAlgoInput] with JsonParser with Mongo {

  val serverHome = sys.env("HARNESS_HOME")

  //private val actors: ActorSystem = ActorSystem(dataset.resourceId)

  var writer: Future[Map[String, Double]] = _
  var params: NHAlgoParams = _
  val resourceId: String = dataset.resourceId
  var model: Map[String, Double] = Map.empty
  var activeJourneys: Map[String, Seq[(String, DateTime)]] = Map.empty // kept as key - user-id, sequence of nav-ids and timestamps

  override def init(json: String, rsrcId: String): Validated[ValidateError, Boolean] = {
    parseAndValidate[NHAllParams](json).andThen { p =>
      if (DecayFunctionNames.All.contains(p.algorithm.decayFunction.getOrElse(DecayFunctionNames.ClickTimes))) {
        params = p.algorithm.copy()
        // init the in-memory model, from which predicitons will be made and to which new conversion Journeys will be added
        dataset.activeJourneysDAO.find(allCollectionObjects).foreach { j =>

          activeJourneys += (j._id -> j.trail)
        }
        // TODO: create model from conversion Trails
        // trigger Train and wait for finish, then input will trigger Train and Query will us the latest trained model
        model = dataset.navHintsDAO.findOne(allCollectionObjects).getOrElse(Hints(Map.empty)).hints
        //trainer = Some(new NavHintTrainer(convertedJourneys, params, resourceId, model, this).self)<commit_msg>Nearly complete NavHinting, needs model persistence<commit_after>/*
 * Copyright ActionML, LLC under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * ActionML licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.actionml.templates.navhinting
import akka.actor._
import cats.data.Validated
import cats.data.Validated.{Invalid, Valid}
import com.actionml.core.storage._
import com.actionml.core.template._
import com.actionml.core.validate.{JsonParser, ParseError, ValidRequestExecutionError, ValidateError}
import com.typesafe.scalalogging.LazyLogging
import org.joda.time.DateTime
import salat.dao.SalatDAO

import scala.concurrent.Future
import scala.math._
import scala.concurrent.ExecutionContext.Implicits.global


/** Creates an Actor to train for each input. The Actor works in a thread and when complete will accept any
  * new training request and start anew. In parallel queries can be made of the existing model. When training
  * is done, the live model is updated atomically. This is therefore a Kappa style learner, that is eventually
  * consistent with all input. The difference between real time and eventually is arbitrary and based on compute
  * power. All input is persisted before the model is calculated to guarantee the model can be recreated. We may
  * be able to train and persist in parallel when we switch to the new async DB client.
  */
class NavHintingAlgorithm(dataset: NavHintingDataset)
  extends Algorithm[NHQuery, NHQueryResult] with KappaAlgorithm[NavHintingAlgoInput] with JsonParser with Mongo {

  val serverHome = sys.env("HARNESS_HOME")

  //private val actors: ActorSystem = ActorSystem(dataset.resourceId)

  var params: NHAlgoParams = _
  val resourceId: String = dataset.resourceId
  var model: Map[String, Double] = Map.empty
  var activeJourneys: Map[String, Seq[(String, DateTime)]] = Map.empty // kept as key - user-id, sequence of nav-ids and timestamps

  override def init(json: String, rsrcId: String): Validated[ValidateError, Boolean] = {
    parseAndValidate[NHAllParams](json).andThen { p =>
      if (DecayFunctionNames.All.contains(p.algorithm.decayFunction.getOrElse(DecayFunctionNames.ClickTimes))) {
        params = p.algorithm.copy()
        // init the in-memory model, from which predicitons will be made and to which new conversion Journeys will be added
        dataset.activeJourneysDAO.find(allCollectionObjects).foreach { j =>

          activeJourneys += (j._id -> j.trail)
        }
        // TODO: create model from conversion Trails
        // trigger Train and wait for finish, then input will trigger Train and Query will us the latest trained model
        model = dataset.navHintsDAO.findOne(allCollectionObjects).getOrElse(Hints(Map.empty)).hints
        //trainer = Some(new NavHintTrainer(convertedJourneys, params, resourceId, model, this).self)
{'fraction_non_alphanumeric': 0.07360552041403105, 'fraction_numerical': 0.0011500862564692352, 'mean_word_length': 4.207335329341317, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5330594', 'n_tokens_mistral': 1861, 'n_tokens_neox': 1827, 'n_words': 740}