001 // Copyright 2012, 2013 Brad Block, Pawjaw, LLC. (an Ohio Limited Liability Company) 002 // 003 // This file is part of JBTCRF. 004 // 005 // JBTCRF is free software: you can redistribute it and/or modify 006 // it under the terms of the GNU General Public License as published by 007 // the Free Software Foundation, either version 3 of the License, or 008 // (at your option) any later version. 009 // 010 // JBTCRF is distributed in the hope that it will be useful, 011 // but WITHOUT ANY WARRANTY; without even the implied warranty of 012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 // GNU General Public License for more details. 014 // 015 // You should have received a copy of the GNU General Public License 016 // along with JBTCRF. If not, see <http://www.gnu.org/licenses/>. 017 018 package com.pawjaw.classification.crf.lmcbt; 019 020 public class CRFMath { 021 public static final double LOGZERO = Double.NaN; 022 public static final double LOGONE = 0; 023 024 public static final boolean isLogZero(double x) { 025 return Double.isNaN(x); 026 } 027 028 public static final double eExp(double x) { 029 return isLogZero(x) ? 0 : Math.exp(x); 030 } 031 032 public static final double eLog(double x) { 033 if(x == 0) 034 return LOGZERO; 035 else if(x > 0) 036 return Math.log(x); 037 else 038 throw new IllegalArgumentException(); 039 } 040 041 public static final double eLogSum(double elogx, double elogy) { 042 if(isLogZero(elogx)) 043 return elogy; 044 else if(isLogZero(elogy)) 045 return elogx; 046 else if(elogx > elogy) 047 return elogx + eLog(1.0 + Math.exp(elogy - elogx)); 048 else 049 return elogy + eLog(1.0 + Math.exp(elogx - elogy)); 050 } 051 052 public static final double eLogProduct(double elogx, double elogy) { 053 if(isLogZero(elogx) || isLogZero(elogy)) 054 return LOGZERO; 055 else 056 return elogx + elogy; 057 } 058 }