This commit is contained in:
BoHung Chiu 2022-01-22 17:27:15 +08:00
parent 8041af8fd6
commit 96465e34f3
6 changed files with 187 additions and 29 deletions

View File

@ -385,13 +385,13 @@ $(document).ready(function(){
$('#cancer_predict_result_block').css('display','block'); $('#cancer_predict_result_block').css('display','block');
var lpv_real = [result.responseJSON['lpv_variable']]; var lpv_real = [result.responseJSON['lpv_variable']];
var lpv_dict={} var lpv_dict={}
var lpv_calc={0.5:0.9736358,1:0.9548993,1.5:0.9229336} var lpv_calc=/*lpv_calc_formula_start*/{1: "0.8095037^( exp(lpv_current) )",1.5: "0.729158^( exp(lpv_current) )",2: "0.6717211^( exp(lpv_current) )", 2.5: "0.6056773^( exp(lpv_current) )"}/*lpv_calc_formula_end*/
active_treatment.push = function() { active_treatment.push = function() {
if(arguments.length == 1){ if(arguments.length == 1){
var year = $('#current_year').attr('value'); var year = $('#current_year').attr('value');
var lpv_current = change_object_variables(lpv_real[lpv_real.length-1],lpv_dict[arguments[0]],'+'); var lpv_current = change_object_variables(lpv_real[lpv_real.length-1],lpv_dict[arguments[0]],'+');
lpv_real.push(lpv_current); lpv_real.push(lpv_current);
var servive_ratio = round((1 - (lpv_calc[year]**Math.exp(lpv_current)))*100,2); var servive_ratio = round((1 - eval(lpv_calc[year]))*100,2);
var benefit = servive_ratio - servive_ratio_arr[servive_ratio_arr.length - 1]; var benefit = servive_ratio - servive_ratio_arr[servive_ratio_arr.length - 1];
servive_ratio_arr.push(servive_ratio); servive_ratio_arr.push(servive_ratio);
$('tr.'+arguments[0]+' td.Overall_Survival').html(servive_ratio+'%'); $('tr.'+arguments[0]+' td.Overall_Survival').html(servive_ratio+'%');

View File

@ -85,7 +85,7 @@ class Admin::CancerpredictsController < OrbitAdminController
@form_to_show.form_show[ num.to_s ][ sub_property ][params[:locale].to_s] = [] @form_to_show.form_show[ num.to_s ][ sub_property ][params[:locale].to_s] = []
end end
end end
if(property["old_num"] != nil && property["old_num"] != num.to_s) if(property["old_num"].present? && property["old_num"] != num.to_s)
other_in_use_locales.each do |locale| other_in_use_locales.each do |locale|
@form_to_show.form_show[ num.to_s ][ sub_property ][locale] = @form_to_show.form_show_was[ property["old_num"] ][ sub_property ][locale] @form_to_show.form_show[ num.to_s ][ sub_property ][locale] = @form_to_show.form_show_was[ property["old_num"] ][ sub_property ][locale]
end end
@ -279,18 +279,7 @@ class Admin::CancerpredictsController < OrbitAdminController
@form_to_show.mapping_data_from_csv = mapping_data_from_csv.to_json @form_to_show.mapping_data_from_csv = mapping_data_from_csv.to_json
@form_to_show.save @form_to_show.save
fork do fork do
js_codes = auto_write_predict_js @form_to_show.auto_write_predict_js
save_path = `bundle show cancerpredict`
save_path = save_path.sub("\n","") + '/app/assets/javascripts/cancer_predict.js'
file_texts = File.read(save_path)
str1 = "/* auto add start */"
index1 = file_texts.index(str1)
str2 = "/* auto add end */"
index2 = file_texts.index(str2)
file_texts = file_texts.sub(file_texts[(index1+str1.length+2) .. (index2 - 1)] , js_codes)
if !index1.nil? && !index2.nil?
File.write(save_path,file_texts)
end
end end
end end
@index = 0 @index = 0
@ -564,7 +553,7 @@ class Admin::CancerpredictsController < OrbitAdminController
end end
def showSubmit def showSubmit
@page_num = params[:page] || 1 @page_num = params[:page] || 1
@results = Cancerpredictrecord.where("title"=>@app_title).asc(:id).page(@page_num).per(10) @results = Cancerpredictrecord.where("title"=>@app_title).desc(:id).page(@page_num).per(10)
@variables = [] @variables = []
@names = [] @names = []
@form_to_show.form_show.each do |num,property| @form_to_show.form_show.each do |num,property|

View File

@ -98,14 +98,8 @@ class CancerpredictsController < ApplicationController
end end
end end
#result['lpv'] = -0.51427548* (result['sex_value']- 0.508312) + 0.05764604* (result['Age_value'] - 61.894501) + 0.49138819*(result['cal_value'] - 0.334399) rescue 'error' #result['lpv'] = -0.51427548* (result['sex_value']- 0.508312) + 0.05764604* (result['Age_value'] - 61.894501) + 0.49138819*(result['cal_value'] - 0.334399) rescue 'error'
formula = @form_to_show.prediction_formula.gsub("\r\n"," ").gsub("^","**") formula = @form_to_show.tmp_lpv_ruby_code
result.keys.each do |k| formula_variables = @form_to_show.tmp_lpv_variables_ruby_code
formula = formula.gsub(/#{k}?(-|\+|\*|\s|\=)/){ "result[\"#{k}\"]#{$1}" }
end
formula_variables = formula.enum_for(:scan,/([^\=]*)?=/).map { Regexp.last_match[1] }.map{|s| s.strip.split(/(\s*|;\r\n)/).last}
@form_to_show.form_show.values.map{|p| p[:variable]}.each{ |k| formula = formula.gsub(/#{k}?(-|\+|\*|\s|\=)/,"result[\"#{k}\"#{$1}]") }
eval(formula) eval(formula)
result['lpv'] = eval(formula_variables.last) result['lpv'] = eval(formula_variables.last)
result['lpv_variable'] = {} result['lpv_variable'] = {}
@ -136,7 +130,6 @@ class CancerpredictsController < ApplicationController
end end
result['table'] += '</tr>' result['table'] += '</tr>'
end end
@lpv_calc = [0.9736358,0.9548993,0.9229336]
year = params['data']['year'] rescue nil year = params['data']['year'] rescue nil
if year.nil? if year.nil?
year = @years.first.to_f year = @years.first.to_f
@ -144,8 +137,7 @@ class CancerpredictsController < ApplicationController
year = year.to_f year = year.to_f
end end
year_index = @years.index(year) year_index = @years.index(year)
#@servive_ratio = ((1-(@lpv_calc[0]**(Math.exp(result['lpv']))))*100).round(2) rescue 1 @servive_ratio = eval(@form_to_show.tmp_years_settings[year_index])
@servive_ratio = eval(@form_to_show.years_settings[year_index].gsub('^','**').gsub('exp','Math.exp'))
@servive_ratio = ((1 - @servive_ratio) * 100).round(2) @servive_ratio = ((1 - @servive_ratio) * 100).round(2)
@texts = @form_to_show.text_above_texts[locale].to_s.gsub('<br/>','</span><br/><span>').gsub('{{Surgery_only}}','<span class="'+@therapy_names[0]+' Overall_Survival">'+@servive_ratio.round(2).to_s+'</span>') @texts = @form_to_show.text_above_texts[locale].to_s.gsub('<br/>','</span><br/><span>').gsub('{{Surgery_only}}','<span class="'+@therapy_names[0]+' Overall_Survival">'+@servive_ratio.round(2).to_s+'</span>')
@texts = @texts.split('{{years}}') @texts = @texts.split('{{years}}')

View File

@ -1,4 +1,6 @@
class Cancerpredictfields class Cancerpredictfields
require 'pathname'
require 'json'
include Mongoid::Document include Mongoid::Document
include Mongoid::Timestamps include Mongoid::Timestamps
include OrbitModel::Status include OrbitModel::Status
@ -92,10 +94,40 @@ class Cancerpredictfields
+0.2002546*(O9-0.06176471)" +0.2002546*(O9-0.06176471)"
field :years_settings , type: Array , default: ["0.8095037^( exp(A) )","0.729158^( exp(A) )","0.6717211^( exp(A) )","0.6056773^( exp(A) )"] field :years_settings , type: Array , default: ["0.8095037^( exp(A) )","0.729158^( exp(A) )","0.6717211^( exp(A) )","0.6056773^( exp(A) )"]
field :tmp_years_settings , type: Array , default: []
field :lpv_calc, type: Hash, default: {} #for js code
field :tmp_lpv_ruby_code, type: String, default: ""
field :tmp_lpv_variables_ruby_code, type: Array, default: []
field :mapping_data_from_csv , type: String ,default: "" field :mapping_data_from_csv , type: String ,default: ""
scope :can_display, ->{where(:is_hidden=>false,:is_preview => false).any_of({:postdate.lt=>Time.now, :deadline.gt=>Time.now},{:postdate.lt=>Time.now, :deadline=>nil}).order_by([:is_top, :desc],[:postdate, :desc])} scope :can_display, ->{where(:is_hidden=>false,:is_preview => false).any_of({:postdate.lt=>Time.now, :deadline.gt=>Time.now},{:postdate.lt=>Time.now, :deadline=>nil}).order_by([:is_top, :desc],[:postdate, :desc])}
scope :is_approved, ->{where(:approved => true)} scope :is_approved, ->{where(:approved => true)}
#before_create :set_expire #before_create :set_expire
before_save do
result_keys = []
self.form_show.each do |num,property|
variable_name = property[:variable]
if variable_name.present?
result_keys << variable_name
end
end
mapping_data = JSON.parse(self.mapping_data_from_csv) rescue {}
if mapping_data.present?
mapping_data.each do |k,v|
result_keys += (v.keys rescue [])
end
end
formula = self.prediction_formula.gsub("\r\n"," ").gsub("^","**")
result_keys.each do |k|
formula = formula.gsub(/#{k}?(-|\+|\*|\s|\=)/){ "result[\"#{k}\"]#{$1}" }
end
self.tmp_lpv_ruby_code = formula
formula_variables = formula.enum_for(:scan,/([^\=]*)?=/).map { ::Regexp.last_match[1] }.map{|s| s.strip.split(/(\s*|;\r\n)/).last}
self.tmp_lpv_variables_ruby_code = formula_variables
self.tmp_years_settings = self.years_settings.map do |s|
s.gsub('^','**').gsub('exp','Math.exp')
end
self.lpv_calc = get_years_settings_dict
end
def update_user def update_user
User.find(update_user_id) rescue nil User.find(update_user_id) rescue nil
end end
@ -127,4 +159,139 @@ class Cancerpredictfields
b.save b.save
end end
end end
def generate_jscode
js_code = "var map_values , mapping_hash , temp_index ,temp_value , index , closest_value;\r\n"
mapping_data_from_csv = YAML.load(self.mapping_data_from_csv) rescue {}
variable_keys = []
self.form_show.each do |num,property|
@variable = property[:variable]
if @variable.present?
if property[:is_num] == 1
js_code += "\t\t\t\tresult['#{@variable}'] = Number(result_json['#{@variable}']);\r\n"
elsif property[:choice_fields].present?
if property[:map_values].class == Array && property[:choice_fields].class == Array && property[:map_values].length == property[:choice_fields].length
js_code += "\t\t\t\tmap_values = #{property[:map_values]};\r\n"
js_code += "\t\t\t\tresult['#{@variable}'] = map_values[Number(result_json['#{@variable}'']) - 1];\r\n"
else
if property[:revert_value].to_i != 1
js_code += "\t\t\t\tresult['#{@variable}'] = Number(result_json['#{@variable}']) - 1;\r\n"
else
js_code += "\t\t\t\tresult['#{@variable}'] = (#{property[:choice_fields].length} - Number(result_json['#{@variable}']));\r\n"
end
end
end
variable_keys.push(@variable)
if property[:cancer_predict_mapping_file].present?
if (mapping_data_from_csv != {} && !mapping_data_from_csv[@variable].blank?)
variable_keys.concat(mapping_data_from_csv[@variable].keys)
js_code += "\t\t\t\tmapping_hash = mapping_data_from_csv['#{@variable}'];\r\n"
js_code += "\t\t\t\ttemp_index = 0;\r\n"
js_code += "\t\t\t\ttemp_value = result[#{@variable}];\r\n"
js_code += "\t\t\t\tindex = 0;
$.each(mapping_hash,function(k,v){
if( i == 0 ){
var index_val = v.indexOf(temp_value);
if( index_val != -1 ){
temp_index = index_val;
}else{
closest_value = v.get_nearest_value(temp_value);
temp_index = v.indexOf(closest_value)
}
}
result[k] = v[temp_index];
index++;
});\r\n"
end
end
end
end
formula = self.prediction_formula.gsub("\r\n"," ").gsub("^","**")
variable_keys.each do |k|
formula = formula.gsub(/#{k}?(-|\+|\*|\s|\=)/){ "result[\"#{k}\"]#{$1}" }
end
formula_variables = formula.enum_for(:scan,/([^\=]*)?=/).map { ::Regexp.last_match[1] }.map{|s| s.strip.split(/(\s*|;\r\n)/).last}
js_code = "function calculate_first_lpv(result_json){
result = {};
#{js_code}
try{
result['lpv'] = (#{formula});
}catch(e){result['lpv'] = \"error\"};
console.log(result['lpv']);
#{formula_variables.map{|v| "result['lpv_variable']['#{v}'] = #{v};"}.join("\r\n\t\t\t\t") }
return result;
};
function calculate_and_change_result_value(obj){
obj.servive_ratio_arr = [];
for(var i = 0;i<obj.active_treatment.length;i++){
var servive_ratio = round((1-(calculate_servive_ratio(obj.year,obj.lpv_real[i])))*100,2);
var benefit = servive_ratio - obj.servive_ratio_arr[obj.servive_ratio_arr.length-1];
obj.servive_ratio_arr.push(servive_ratio);
$('tr.'+obj.active_treatment[i]+' td.Overall_Survival').html(servive_ratio+'%');
$('.'+obj.active_treatment[i]+'.Overall_Survival').html(servive_ratio);
if(i != 0){
$('tr.'+obj.active_treatment[i]+' td.Additional_Benefit').html(round(benefit,2)+'%');
$('.'+obj.active_treatment[i]+'.Additional_Benefit').html(Math.round(benefit));
}
}
//$('.'+obj.active_treatment[0]+'.Overall_Survival').html(Math.round(obj.servive_ratio_arr[0]));
};"
@years = self.years
switch_texts = "
#{formula_variables.map{|v| "var #{v} = obj['#{v}'];"}.join("\r\n\t\t\t\t")}
switch(year) {"
@years.each do |year|
year_index = @years.index(year)
switch_texts +=
"
case '#{year}':
servive_ratio = #{self.tmp_years_settings[year_index]};
break;
"
end
switch_texts += "
default:
console.log('not found year.');
}"
js_code = js_code +"
function calculate_servive_ratio(year,obj){
var servive_ratio;
#{switch_texts}
return servive_ratio;
}
"
return js_code
end
def auto_write_predict_js
js_codes = generate_jscode
module_app_path = Pathname.new(File.expand_path(__dir__)).dirname.dirname.to_s
save_path = module_app_path + '/app/assets/javascripts/cancer_predict.js'
file_texts = File.read(save_path)
str1 = "/* auto add start */"
index1 = file_texts.index(str1)
str2 = "/* auto add end */"
index2 = file_texts.index(str2)
str3 = "/*lpv_calc_formula_start*/"
index3 = file_texts.index(str3)
str4 = "/*lpv_calc_formula_end*/"
index4 = file_texts.index(str4)
file_texts = file_texts.sub(file_texts[(index1+str1.length+2) .. (index2 - 1)] , js_codes)
file_texts = file_texts.sub(file_texts[(index3+str3.length) .. (index4 - 1)] , self.lpv_calc.to_json.gsub("@","."))
if (!index1.nil? && !index2.nil?) || (!index3.nil? && !index4.nil?)
File.write(save_path,file_texts)
end
end
def get_years_settings_dict
lpv_variable_name = (prediction_formula.include?("=") ? prediction_formula.split("=")[0].strip : "" rescue "")
res = self.years.map.with_index do |y, i|
tmp_formula = self.tmp_years_settings[i]
if lpv_variable_name.present?
tmp_formula = tmp_formula.gsub(lpv_variable_name, "lpv_current")
else
tmp_formula = tmp_formula.gsub("lpv", "lpv_current")
end
[y.to_s.sub(".","@"), tmp_formula]
end
res.to_h
end
end end

View File

@ -16,6 +16,10 @@ class Cancerpredictrecord
scope :is_approved, ->{where(:approved => true)} scope :is_approved, ->{where(:approved => true)}
before_save :set_submit_times before_save :set_submit_times
def set_submit_times def set_submit_times
self.submit_time = Cancerpredictrecord.where(:title=> "cancerpredict").length + 1 self.submit_time = Cancerpredictrecord.all.count + 1
end
def check_missing_data
missing_keys = self.names.keys - self.result.keys rescue []
missing_keys.each{|k| self.result[k] = "" }
end end
end end

View File

@ -1,5 +1,11 @@
Rails.application.routes.draw do Rails.application.routes.draw do
Thread.new do
c = Cancerpredictfields.last
if c
c.save
c.auto_write_predict_js
end
end
locales = Site.first.in_use_locales rescue I18n.available_locales locales = Site.first.in_use_locales rescue I18n.available_locales
scope "(:locale)", locale: Regexp.new(locales.join("|")) do scope "(:locale)", locale: Regexp.new(locales.join("|")) do