Example #1
0
 public static function timeop($opname, $time_function)
 {
     // Pick sample size, results normalized against median function call cost
     $run_count = 10;
     // Run operation a few times before starting timer
     $result = $time_function(20);
     echo "\n{$opname} result = {$result}";
     // Record time
     $time = array();
     for ($iter = 0; $iter < $run_count; $iter++) {
         $start_time = microtime(true);
         $result = $time_function(10000);
         $end_time = microtime(true);
         if ($iter == 0) {
             echo "\n{$opname} result = {$result}";
         }
         $time[$iter] = ($end_time - $start_time) * 1000;
     }
     // Compute stats
     $max = max($time);
     $min = min($time);
     $mean = mean($time);
     $median = median($time);
     $std_dev = std_dev($time);
     // Confidence in results
     TimeHHOperations::$operationsCount++;
     if ($max > 10 * $min || $std_dev / $mean > 0.1) {
         TimeHHOperations::$lowconfidenceCount++;
     }
     if ($opname == 'function_call') {
         TimeHHOperations::$nmedian = $median;
     }
     // Print stats
     echo "\nCPU cost normalized against median function call cost";
     echo "\n-----------------------------------------------------";
     echo "\n{$opname} max = ", $max / TimeHHOperations::$nmedian;
     echo "\n{$opname} min = ", $min / TimeHHOperations::$nmedian;
     echo "\n{$opname} mean = ", $mean / TimeHHOperations::$nmedian;
     echo "\n{$opname} median = ", $median / TimeHHOperations::$nmedian;
     echo "\n{$opname} std. dev = {$std_dev}";
     echo "\n{$opname} time measurement complete. Run count = {$run_count}.";
     echo "\n";
     // Write stats to csv file
     fputcsv(TimeHhOperations::$file, array($opname, $max / TimeHHOperations::$nmedian, $min / TimeHHOperations::$nmedian, $mean / TimeHHOperations::$nmedian, $median / TimeHHOperations::$nmedian));
 }
function deisotope($mzInt, $prec, $prec_charge)
{
    global $leftIsoWindow, $rightIsoWindow, $proton, $neutron, $ppmWindow, $multWindow, $noise_flag, $debug_mode, $major_debug;
    global $stopIntThres, $stopCountThres;
    $stopThres = $stopIntThres * median(array_values($mzInt));
    $stopCount = 0;
    $newMzInt = array();
    $indMzInt = array();
    while (true) {
        #Find highest peak
        $maxHeight = -1;
        $maxMz = 0;
        foreach ($mzInt as $mz => $int) {
            if ($int > $maxHeight) {
                $maxMz = $mz;
                $maxHeight = $int;
            }
        }
        #If highest peak below threshold, break
        if ($maxHeight < $stopThres) {
            if ($debug_mode) {
                print "Reached height threshold\n";
            }
            break;
        }
        if ($stopCount > $stopCountThres) {
            if ($debug_mode) {
                print "Reached count threshold\n";
            }
            break;
        }
        #Get peaks within window
        $windowPeaks = array();
        if ($debug_mode) {
            print "Found:\n";
        }
        foreach ($mzInt as $mz => $int) {
            if ($mz < $maxMz + $rightIsoWindow && $mz > $maxMz - $leftIsoWindow) {
                $windowPeaks[$mz] = $int;
                if ($debug_mode) {
                    print $mz . "\t" . $int . "\n";
                }
            }
        }
        if ($debug_mode) {
            print "Done Found\n\n";
        }
        $mono = array();
        $charge = array();
        #Find charge state
        list($mono, $charge) = get_charge_state($windowPeaks, $maxMz, null, $prec_charge, $major_debug);
        if ($debug_mode) {
            print "make_mono found:\n";
            foreach ($mono as $monos) {
                print $monos . "\t";
            }
            print "\n";
            foreach ($charge as $charges) {
                print $charges . "\t";
            }
            print "\n";
        }
        $theCharge = max($charge);
        #(m+zh)/z to m+h
        $oldMass = end($mono);
        $newMass = end($mono) * floatval($theCharge) - floatval($theCharge - 1) * $proton;
        #Make sure new mass is less than precursor (cannot be larger)
        if ($mono[0] != 0 && $newMass <= $prec) {
            if ($stopCount > 0) {
                $stopCount--;
            }
            if ($debug_mode) {
                echo "Removing: " . $oldMass . "\t Charge: " . $theCharge . "\t" . $windowPeaks[$oldMass] . "\n";
            }
            #Check if there's a peak already where we're moving
            $newPeak = $newMass;
            foreach ($newMzInt as $mz => $int) {
                $window = calc_diff($newMass, $multWindow);
                if ($mz < $newMass + $window && $mz > $newMass - $window) {
                    $newPeak = $mz;
                }
            }
            #convert to string, php doesn't like float keys
            $newKey = strval($newPeak);
            if ($debug_mode) {
                print "Int for " . $newPeak . " before was: " . $newMzInt[$newKey] . "\n";
            }
            if (isset($indMzInt[$newKey])) {
                $indMzInt[$newKey]++;
            } else {
                $indMzInt[$newKey] = 1;
            }
            for ($i = 0; $i <= 4; $i++) {
                #Find all peaks involved
                $testMz = $oldMass + $i * $neutron / $theCharge;
                $window = calc_diff($testMz, $ppmWindow);
                if ($debug_mode) {
                    print "Looking for: " . $testMz . " with window " . $window . "\n";
                }
                foreach ($windowPeaks as $mz => $int) {
                    #If it's there, add it too
                    if ($mz < $testMz + $window && $mz > $testMz - $window) {
                        if ($debug_mode) {
                            print "Removing: " . $mz . "\t" . $int . "\n";
                        }
                        if (isset($newMzInt[$newKey])) {
                            $newMzInt[$newKey] += $int;
                        } else {
                            $newMzInt[$newKey] = $int;
                        }
                        unset($mzInt[$mz]);
                        if ($debug_mode) {
                            print "Int is now: " . $newMzInt[$newKey] . "\n";
                        }
                    }
                }
            }
            if ($debug_mode) {
                print "Moved to: mz=" . $newPeak . "\tint=" . $newMzInt[$newKey] . "\n";
                print "Done Removed\n\n";
            }
        } else {
            if ($debug_mode) {
                print "make_mono failed (dropping: " . $maxMz . ")\n\n";
            }
            $stopCount++;
            #If not found, get rid of it (and possibly add to noise)
            if ($noise_flag) {
                if (isset($indMzInt[$maxMz])) {
                    $indMzInt[$maxMz]++;
                    $newMzInt[$maxMz] += $maxHeight;
                } else {
                    $indMzInt[$maxMz] = 1;
                    $newMzInt[$maxMz] = $maxHeight;
                }
            }
            unset($mzInt[$maxMz]);
        }
    }
    if ($noise_flag) {
        #Transfer all other peaks
        foreach ($mzInt as $mz => $int) {
            if (isset($indMzInt[$mz])) {
                $indMzInt[$mz]++;
                $newMzInt[$mz] += $int;
            } else {
                $indMzInt[$mz] = 1;
                $newMzInt[$mz] = $int;
            }
        }
    }
    foreach ($newMzInt as $mz => $int) {
        $outMzInt[$mz] = $newMzInt[$mz] / $indMzInt[$mz];
    }
    return $outMzInt;
    // Xdebug call - remove for publication!
    xdebug_pring_function_stack('End of deisotope function');
}
Example #3
0
function stats_summary($array)
{
    $stats = array();
    $stats['min'] = min($array);
    $stats['max'] = max($array);
    $stats['avg'] = round(average($array), 2);
    $stats['median'] = median($array);
    $stats['Q1'] = array_firstQuartile($array);
    $stats['Q3'] = array_thirdQuartile($array);
    $stats['truncatedMean'] = array_truncatedMean($array);
    return $stats;
}
Example #4
0
/**
 * Construct KPI Leadtime Table
 * @param string $status
 * @param string $kpi_closing_date_start
 * @param string $kpi_closing_date_end
 * @return string
 */
function kpiLeadtimeLoad($kpi_status, $kpi_closing_date_start = '', $kpi_closing_date_end = '')
{
    use_class('jng_sp');
    use_class('design');
    $class_sp = new jng_sp();
    $sp_b2b = array_keys($class_sp->retrieveList('active_status = 1 AND use_amvd_logistic = 1'));
    $target_leadtime = load_config('kpi-leadtime');
    $design_categories = design::getDesignCategory();
    $initial = array('sourcing' => 0, 'depot-refill-orders' => 0, 'internal-levelling-orders' => 0, 'cust-order-mto-mmo' => 0, 'external-levelling-order' => 0, 'full-dso' => 0, 'mto' => 0);
    foreach ($design_categories as $des_cat_id => $des_cat_name) {
        $initial["design-{$des_cat_id}"] = 0;
    }
    $below_target = $initial;
    $on_target = $initial;
    $above_target_1to3d = $initial;
    $above_target_gt3d = $initial;
    $total = $initial;
    $kpi_leadtime_data_o = array();
    //open
    $kpi_leadtime_data_c = array();
    //closed
    //PREPARE KPI LEADTIME DATA
    if ($kpi_status == 'o') {
        //OPEN ORDERS
        //Sourcing
        $q = " SELECT sp_type, item_id, quantity, MIN(status_date) AS date_start FROM";
        $q .= " (";
        $q .= " SELECT 'sp' AS sp_type, joi.jng_sp_orders_items_id AS item_id" . ", joish.status_date, joi.order_quantity AS quantity";
        $q .= " FROM jng_sp_orders_items joi" . " INNER JOIN jng_sp_orders_items_status_history joish ON joish.jng_sp_orders_items_id = joi.jng_sp_orders_items_id" . " AND joish.status = 2";
        $q .= " WHERE joi.status = 2";
        $q .= " UNION";
        $q .= " SELECT 'jg' AS sp_type, op.orders_products_id AS item_id" . ", opsh.status_date, op.products_quantity AS quantity";
        $q .= " FROM orders_products op" . " INNER JOIN orders_products_status_history opsh ON opsh.orders_products_id = op.orders_products_id" . " AND opsh.status = 2";
        $q .= " WHERE op.status = 2";
        $q .= " UNION";
        $q .= " SELECT 'dp' AS sp_type, do.depot_orders_id AS item_id" . ", dosh.update_time AS status_date, do.quantity";
        $q .= " FROM depot_orders do" . " INNER JOIN depot_orders_status_history dosh ON dosh.depot_orders_id = do.depot_orders_id" . " AND dosh.status = 2";
        $q .= " WHERE do.status = 2";
        $q .= ") dt";
        $q .= " GROUP BY sp_type, item_id";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            //Sourcing Order Type
            $kpi_leadtime_data_o['sourcing'][] = $r;
        }
        //Production
        $q = " SELECT sp_type, item_id, quantity, MIN(status_date) AS date_start, mode, order_type, order_type_id, order_type_name";
        $q .= " FROM (";
        $q .= " SELECT 'sp' AS sp_type, joi.jng_sp_orders_items_id AS item_id" . ", joish.status_date, joi.order_quantity AS quantity, joi.mode" . ", '' AS order_type, '' AS order_type_id, '' AS order_type_name";
        $q .= " FROM jng_sp_orders_items joi" . " INNER JOIN jng_sp_orders_items_status_history joish ON joish.jng_sp_orders_items_id = joi.jng_sp_orders_items_id" . " AND joish.status = 4";
        $q .= " WHERE joi.status = 4";
        $q .= " UNION";
        $q .= " SELECT 'jg' AS sp_type, op.orders_products_id AS item_id" . ", opsh.status_date, op.products_quantity AS quantity, op.mode" . ", '' AS order_type, '' AS order_type_id, '' AS order_type_name";
        $q .= " FROM orders_products op" . " INNER JOIN orders_products_status_history opsh ON opsh.orders_products_id = op.orders_products_id" . " AND opsh.status = 4";
        $q .= " WHERE op.status = 4";
        $q .= " UNION";
        $q .= " SELECT 'dp' AS sp_type, do.depot_orders_id AS item_id" . ", dosh.update_time AS status_date, do.quantity, '' AS mode" . ", trans_type AS order_type, trans_id AS order_type_id, group_name AS order_type_name";
        $q .= " FROM depot_orders do" . " INNER JOIN depot_orders_status_history dosh ON dosh.depot_orders_id = do.depot_orders_id" . " AND dosh.status = 4";
        $q .= " WHERE do.status = 4";
        $q .= ") dt";
        $q .= " GROUP BY sp_type, item_id";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            if ($r['order_type'] == 'AR' || $r['order_type'] == '' && $r['order_type_id'] == depot_orders::MANUAL_REFILL_ID) {
                //Depot Refill Order Type
                $kpi_leadtime_data_o['depot-refill-orders'][] = $r;
            } elseif ($r['order_type_name'] == depot_orders::GROUP_NAME_LTF_INTERNAL) {
                //Internal Levelling Order Type
                $kpi_leadtime_data_o['internal-levelling-orders'][] = $r;
            } elseif ($r['mode'] == 2 || $r['mode'] == 4) {
                //Customer Orders (MTO/MMO) Order Type
                $kpi_leadtime_data_o['cust-order-mto-mmo'][] = $r;
            }
        }
        //Outsourcing
        $q = " SELECT do.depot_orders_id AS item_id, MIN(dosh.update_time) AS status_date, do.quantity";
        $q .= " FROM depot_orders do" . " INNER JOIN depot_orders_status_history dosh ON dosh.depot_orders_id = do.depot_orders_id" . " AND dosh.status = 22";
        $q .= " WHERE do.status = 22";
        $q .= " AND do.trans_type = '' && do.trans_id = " . depot_orders::MANUAL_REFILL_OUTSOURCED;
        $q .= " GROUP BY item_id";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            //External Levelling Order Type
            $kpi_leadtime_data_o['external-levelling-order'][] = $r;
        }
        //Customer Order
        $q = " SELECT sp_type, item_id, quantity, MIN(status_date) AS date_start, mode";
        $q .= " FROM (";
        $q .= " SELECT 'sp' AS sp_type, joi.jng_sp_orders_items_id AS item_id" . ", joish.status_date, joi.order_quantity AS quantity, joi.mode";
        $q .= " FROM jng_sp_orders jo " . " INNER JOIN jng_sp_orders_items joi ON joi.jng_sp_orders_id = jo.jng_sp_orders_id" . " INNER JOIN jng_sp_orders_items_status_history joish ON joish.jng_sp_orders_items_id = joi.jng_sp_orders_items_id" . " AND joish.status = 1";
        $q .= " WHERE joi.status < 9 AND jo.jng_sp_id NOT IN (" . implode(',', $sp_b2b) . ")";
        $q .= " UNION";
        $q .= " SELECT 'jg' AS sp_type, op.orders_products_id AS item_id" . ", opsh.status_date, op.products_quantity AS quantity, op.mode";
        $q .= " FROM orders_products op" . " INNER JOIN orders_products_status_history opsh ON opsh.orders_products_id = op.orders_products_id" . " AND opsh.status = 1";
        $q .= " WHERE op.status < 9";
        $q .= ") dt";
        $q .= " GROUP BY sp_type, item_id";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            if ($r['mode'] == 1) {
                //Full DSO Order Type
                $kpi_leadtime_data_o['full-dso'][] = $r;
            } elseif ($r['mode'] == 2 || $r['mode'] == 3 || $r['mode'] == 4) {
                $kpi_leadtime_data_o['mto'][] = $r;
            }
        }
        //Design
        $q = " SELECT d.designs_category, 1 AS quantity, d.designs_id AS item_id" . ", FROM_UNIXTIME(MIN(dsh.status_time)) AS date_start";
        $q .= " FROM designs d " . " INNER JOIN designs_status_history dsh ON dsh.designs_id = d.designs_id AND dsh.status = 2";
        $q .= " WHERE d.status NOT IN (1, 9)";
        $q .= " GROUP BY d.designs_id";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            $kpi_leadtime_data_o["design-{$r['designs_category']}"][] = $r;
        }
    } elseif ($kpi_status == 'c') {
        $kpi_filter_closing_date_start = date('Y-m-d', strtotime($kpi_closing_date_start));
        $kpi_filter_closing_date_end = date('Y-m-d', strtotime($kpi_closing_date_end));
        //Sourcing
        $q = " SELECT * FROM";
        $q .= " (";
        $q .= " SELECT 'sp' AS sp_type, joi.jng_sp_orders_items_id AS item_id, joi.order_quantity AS quantity" . ", MIN(joish_2.status_date) AS date_start, MAX(joish_3.status_date) AS date_end";
        $q .= " FROM jng_sp_orders_items_status_history joish_3" . " LEFT JOIN jng_sp_orders_items joi ON joi.jng_sp_orders_items_id = joish_3.jng_sp_orders_items_id" . " LEFT JOIN jng_sp_orders_items_status_history joish_2 ON joish_2.jng_sp_orders_items_id = joi.jng_sp_orders_items_id" . " AND joish_2.status = 2";
        $q .= " WHERE joish_3.status_date >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND joish_3.status_date <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND joish_3.status = 3 AND joi.status NOT IN (1, 2)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= " UNION";
        $q .= " SELECT 'jg' AS sp_type, op.orders_products_id AS item_id, op.products_quantity AS quantity" . ", MIN(opsh_2.status_date) AS date_start, MAX(opsh_3.status_date) AS date_end";
        $q .= " FROM orders_products_status_history opsh_3" . " LEFT JOIN orders_products op ON op.orders_products_id = opsh_3.orders_products_id" . " LEFT JOIN orders_products_status_history opsh_2 ON opsh_2.orders_products_id = op.orders_products_id" . " AND opsh_2.status = 2";
        $q .= " WHERE opsh_3.status_date >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND opsh_3.status_date <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND opsh_3.status = 3 AND op.status NOT IN (1, 2)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= " UNION";
        $q .= " SELECT 'dp' AS sp_type, do.depot_orders_id AS item_id, do.quantity" . ", MIN(dosh_2.update_time) AS date_start, MAX(dosh_3.update_time) AS date_end";
        $q .= " FROM depot_orders_status_history dosh_3" . " LEFT JOIN depot_orders do ON do.depot_orders_id = dosh_3.depot_orders_id" . " LEFT JOIN depot_orders_status_history dosh_2 ON dosh_2.depot_orders_id = do.depot_orders_id" . " AND dosh_2.status = 2";
        $q .= " WHERE dosh_3.update_time >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND dosh_3.update_time <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND dosh_3.status = 3 AND do.status NOT IN (1, 2)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= ") dt";
        $q .= " WHERE date_start IS NOT NULL AND date_end IS NOT NULL";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            //Sourcing Order Type
            $kpi_leadtime_data_c['sourcing'][] = $r;
        }
        //Production
        $q = " SELECT * FROM";
        $q .= " (";
        $q .= " SELECT 'sp' AS sp_type, joi.jng_sp_orders_items_id AS item_id, joi.order_quantity AS quantity" . ", MIN(joish_4.status_date) AS date_start, MAX(joish_5.status_date) AS date_end, joi.mode" . ", '' AS order_type, '' AS order_type_id, '' AS order_type_name";
        $q .= " FROM jng_sp_orders_items_status_history joish_5" . " LEFT JOIN jng_sp_orders_items joi ON joi.jng_sp_orders_items_id = joish_5.jng_sp_orders_items_id" . " LEFT JOIN jng_sp_orders_items_status_history joish_4 ON joish_4.jng_sp_orders_items_id = joi.jng_sp_orders_items_id" . " AND joish_4.status = 4";
        $q .= " WHERE joish_5.status_date >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND joish_5.status_date <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND joish_5.status = 5 AND joi.status NOT IN (1, 2, 3, 4)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= " UNION";
        $q .= " SELECT 'jg' AS sp_type, op.orders_products_id AS item_id, op.products_quantity AS quantity" . ", MIN(opsh_4.status_date) AS date_start, MAX(opsh_5.status_date) AS date_end, op.mode" . ", '' AS order_type, '' AS order_type_id, '' AS order_type_name";
        $q .= " FROM orders_products_status_history opsh_5" . " LEFT JOIN orders_products op ON op.orders_products_id = opsh_5.orders_products_id" . " LEFT JOIN orders_products_status_history opsh_4 ON opsh_4.orders_products_id = op.orders_products_id" . " AND opsh_4.status = 4";
        $q .= " WHERE opsh_5.status_date >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND opsh_5.status_date <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND opsh_5.status = 5 AND op.status NOT IN (1, 2, 3, 4)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= " UNION";
        $q .= " SELECT 'dp' AS sp_type, do.depot_orders_id AS item_id, do.quantity" . ", MIN(dosh_4.update_time) AS date_start, MAX(dosh_5.update_time) AS date_end, '' AS mode" . ", trans_type AS order_type, trans_id AS order_type_id, group_name AS order_type_name";
        $q .= " FROM depot_orders_status_history dosh_5" . " LEFT JOIN depot_orders do ON do.depot_orders_id = dosh_5.depot_orders_id" . " LEFT JOIN depot_orders_status_history dosh_4 ON dosh_4.depot_orders_id = do.depot_orders_id" . " AND dosh_4.status = 4";
        $q .= " WHERE dosh_5.update_time >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND dosh_5.update_time <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND dosh_5.status = 5 AND do.status NOT IN (1, 2, 3, 4)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= ") dt";
        $q .= " WHERE date_start IS NOT NULL AND date_end IS NOT NULL";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            if ($r['order_type'] == 'AR' || $r['order_type'] == '' && $r['order_type_id'] == depot_orders::MANUAL_REFILL_ID) {
                //Depot Refill Order Type
                $kpi_leadtime_data_c['depot-refill-orders'][] = $r;
            } elseif ($r['order_type_name'] == depot_orders::GROUP_NAME_LTF_INTERNAL) {
                //Internal Levelling Order Type
                $kpi_leadtime_data_c['internal-levelling-orders'][] = $r;
            } elseif ($r['mode'] == 2 || $r['mode'] == 4) {
                //Customer Orders (MTO/MMO) Order Type
                $kpi_leadtime_data_c['cust-order-mto-mmo'][] = $r;
            }
        }
        //Outsourcing
        $q = " SELECT * FROM";
        $q .= " (";
        $q .= " SELECT do.depot_orders_id AS item_id, do.quantity" . ", MIN(dosh_8.update_time) AS date_start, MAX(dosh_22.update_time) AS date_end";
        $q .= " FROM depot_orders_status_history dosh_22" . " LEFT JOIN depot_orders do ON do.depot_orders_id = dosh_22.depot_orders_id" . " LEFT JOIN depot_orders_status_history dosh_8 ON dosh_8.depot_orders_id = do.depot_orders_id" . " AND dosh_8.status = 8";
        $q .= " WHERE dosh_22.update_time >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND dosh_22.update_time <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND do.trans_type = '' AND do.trans_id = " . depot_orders::MANUAL_REFILL_OUTSOURCED . " AND dosh_22.status = 22 AND do.status NOT IN (1, 2, 3, 4, 5, 6, 7, 8, 9)";
        $q .= " GROUP BY item_id";
        $q .= ") dt";
        $q .= " WHERE date_start IS NOT NULL AND date_end IS NOT NULL";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            //External Levelling Order Type
            $kpi_leadtime_data_c['external-levelling-order'][] = $r;
        }
        //Customer Order (only B2C Sales Partner)
        $q = " SELECT * FROM";
        $q .= " (";
        $q .= " SELECT 'sp' AS sp_type, joi.jng_sp_orders_items_id AS item_id, joi.order_quantity AS quantity" . ", MIN(joish_1.status_date) AS date_start, MAX(joish_9.status_date) AS date_end, joi.mode";
        $q .= " FROM jng_sp_orders_items_status_history joish_9" . " LEFT JOIN jng_sp_orders_items joi ON joi.jng_sp_orders_items_id = joish_9.jng_sp_orders_items_id" . " INNER JOIN jng_sp_orders jo ON jo.jng_sp_orders_id = joi.jng_sp_orders_id" . " LEFT JOIN jng_sp_orders_items_status_history joish_1 ON joish_1.jng_sp_orders_items_id = joi.jng_sp_orders_items_id" . " AND joish_1.status = 1";
        $q .= " WHERE joish_9.status_date >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND joish_9.status_date <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND joish_9.status = 9 AND joi.status NOT IN (1, 2, 3, 4, 5, 6, 7, 8)" . " AND jo.jng_sp_id NOT IN (" . implode(',', $sp_b2b) . ")";
        $q .= " GROUP BY sp_type, item_id";
        $q .= " UNION";
        $q .= " SELECT 'jg' AS sp_type, op.orders_products_id AS item_id, op.products_quantity AS quantity" . ", MIN(opsh_1.status_date) AS date_start, MAX(opsh_9.status_date) AS date_end, op.mode";
        $q .= " FROM orders_products_status_history opsh_9" . " LEFT JOIN orders_products op ON op.orders_products_id = opsh_9.orders_products_id" . " LEFT JOIN orders_products_status_history opsh_1 ON opsh_1.orders_products_id = op.orders_products_id" . " AND opsh_1.status = 1";
        $q .= " WHERE opsh_9.status_date >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND opsh_9.status_date <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND opsh_9.status = 9 AND op.status NOT IN (1, 2, 3, 4, 5, 6, 7, 8)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= " UNION";
        $q .= " SELECT 'dp' AS sp_type, do.depot_orders_id AS item_id, do.quantity" . ", MIN(dosh_1.update_time) AS date_start, MAX(dosh_9.update_time) AS date_end, '' AS mode";
        $q .= " FROM depot_orders_status_history dosh_9" . " LEFT JOIN depot_orders do ON do.depot_orders_id = dosh_9.depot_orders_id" . " LEFT JOIN depot_orders_status_history dosh_1 ON dosh_1.depot_orders_id = do.depot_orders_id" . " AND dosh_1.status = 1";
        $q .= " WHERE dosh_9.update_time >= '{$kpi_filter_closing_date_start} 00:00:00'" . " AND dosh_9.update_time <= '{$kpi_filter_closing_date_end} 23:59:59'" . " AND dosh_9.status = 9 AND do.status NOT IN (1, 2, 3, 4, 5, 6, 7, 8)";
        $q .= " GROUP BY sp_type, item_id";
        $q .= ") dt";
        $q .= " WHERE date_start IS NOT NULL AND date_end IS NOT NULL";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            if ($r['mode'] == 1) {
                //Full DSO Order Type
                $kpi_leadtime_data_c['full-dso'][] = $r;
            } elseif ($r['mode'] == 2 || $r['mode'] == 3 || $r['mode'] == 4) {
                $kpi_leadtime_data_c['mto'][] = $r;
            }
        }
        //Design
        $q = " SELECT d.designs_category, 1 AS quantity, d.designs_id AS item_id" . ", FROM_UNIXTIME(MIN(dsh_2.status_time)) AS date_start" . ", FROM_UNIXTIME(MAX(dsh_9.status_time)) AS date_end";
        $q .= " FROM designs_status_history dsh_9 " . " LEFT JOIN designs d ON d.designs_id = dsh_9.designs_id" . " LEFT JOIN designs_status_history dsh_2 ON dsh_2.designs_id = d.designs_id AND dsh_2.status = 2";
        $q .= " WHERE dsh_9.status_time >= " . strtotime($kpi_filter_closing_date_start . " 00:00:00") . " AND dsh_9.status_time <= " . strtotime($kpi_filter_closing_date_end . " 23:59:59") . " AND dsh_9.status = 9 AND d.status = 9";
        $q .= " GROUP BY d.designs_id";
        $dbq = tep_db_query($q);
        while ($r = tep_db_fetch_array($dbq)) {
            $kpi_leadtime_data_c["design-{$r['designs_category']}"][] = $r;
        }
    }
    $today = date('d-m-Y');
    if ($kpi_status == 'c') {
        $kpi_leadtime_data = $kpi_leadtime_data_c;
    } else {
        $kpi_leadtime_data = $kpi_leadtime_data_o;
    }
    $leadtime_arr = array();
    foreach ($kpi_leadtime_data as $order_type => $klds) {
        //klds: kpi leadtime datas
        foreach ($klds as $kld) {
            $lsd = $kld['date_start'];
            $led = $kpi_status == 'o' ? $today : $kld['date_end'];
            $qty = $kld['quantity'];
            $datediff_sec = strtotime($led) - strtotime($lsd);
            $leadtime = ceil($datediff_sec / 3600 / 24);
            //in days format (round up)
            $leadtime_arr[$order_type][] = $leadtime;
            $target = $target_leadtime[$order_type];
            $total[$order_type] += $qty;
            if ($leadtime < $target) {
                $below_target[$order_type] += $qty;
            } elseif ($leadtime == $target) {
                $on_target[$order_type] += $qty;
            } elseif ($leadtime > $target + 3) {
                $above_target_gt3d[$order_type] += $qty;
            } else {
                $above_target_1to3d[$order_type] += $qty;
            }
        }
        $leadtime_avg[$order_type] = count($leadtime_arr[$order_type]) > 0 ? number_format(array_sum($leadtime_arr[$order_type]) / count($leadtime_arr[$order_type]), 2) : '-';
        $leadtime_median[$order_type] = median($leadtime_arr[$order_type], 2);
    }
    //DRAW KPI LEADTIME TABLE
    $tooltip_info_saved = ' title="press enter to save changes" ';
    $border_dotted_bottom = 'border-bottom:1px dotted #ccc; ';
    $border_dotted_right = 'border-right:1px dotted #ccc; ';
    $kpi_lead = '<h3>' . ($kpi_status == 'o' ? 'Lead time of currently open orders/process (' . date('d.m.Y') . ')' : 'Lead time of orders with closing date from ' . date('d.m.Y', strtotime($kpi_closing_date_start)) . ' to ' . date('d.m.Y', strtotime($kpi_closing_date_end))) . '</h3>';
    $kpi_lead .= '<table class="spo" cellspacing="0" cellpadding="0">';
    $kpi_lead .= '<thead>';
    $kpi_lead .= '<tr class="o">';
    $kpi_lead .= '<th class="i" colspan="2" style="' . $border_dotted_bottom . $border_dotted_right . '">Running Lead Time / Lead Time</th>';
    $kpi_lead .= '<th class="r" rowspan="2" style="' . $border_dotted_right . '">Target Lead Time<br/>in Days</th>';
    $kpi_lead .= '<th class="d" rowspan="2" style="' . $border_dotted_right . '">Below Target</th>';
    $kpi_lead .= '<th class="d" rowspan="2" style="' . $border_dotted_right . '">On Target</th>';
    $kpi_lead .= '<th class="r" rowspan="2" style="' . $border_dotted_right . '">Above Target<br/>1 to 3 days</th>';
    $kpi_lead .= '<th class="r" rowspan="2" style="' . $border_dotted_right . '">Above Target<br/>&gt; 3 days</th>';
    $kpi_lead .= '<th class="r" rowspan="2" style="' . $border_dotted_right . '">Total<br/>(based on Qty)</th>';
    $kpi_lead .= '<th class="r" rowspan="2" style="' . $border_dotted_right . '">Lead Time<br/>Average in Days</th>';
    $kpi_lead .= '<th class="r" rowspan="2">Lead Time<br/>Median in Days</th>';
    $kpi_lead .= '</tr>';
    $kpi_lead .= '<tr>';
    $kpi_lead .= '<th style="' . $border_dotted_right . '">Category</th>';
    $kpi_lead .= '<th style="' . $border_dotted_right . '">Order Type</th>';
    $kpi_lead .= '</tr>';
    $kpi_lead .= '</thead>';
    $kpi_lead .= '<tbody>';
    //Sourcing
    $kpi_lead .= '<tr class="e">';
    $kpi_lead .= '<td><strong>Sourcing</strong></td>';
    $kpi_lead .= '<td>Sourcing</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-sourcing" value="' . $target_leadtime['sourcing'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['sourcing'] . '<br/>' . kpiFormatPercentage($total['sourcing'], $below_target['sourcing']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['sourcing'] . '<br/>' . kpiFormatPercentage($total['sourcing'], $on_target['sourcing']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['sourcing'] . '<br/>' . kpiFormatPercentage($total['sourcing'], $above_target_1to3d['sourcing']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['sourcing'] . '<br/>' . kpiFormatPercentage($total['sourcing'], $above_target_gt3d['sourcing']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['sourcing'] . '<br/>' . kpiFormatPercentage($total['sourcing'], $total['sourcing']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['sourcing']) ? $leadtime_avg['sourcing'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['sourcing']) ? $leadtime_median['sourcing'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    //Production
    $kpi_lead .= '<tr class="o">';
    $kpi_lead .= '<td rowspan="3"><strong>Production</strong></td>';
    $kpi_lead .= '<td>Depot Refill Orders</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-depot-refill-orders" value="' . $target_leadtime['depot-refill-orders'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['depot-refill-orders'] . '<br/>' . kpiFormatPercentage($total['depot-refill-orders'], $below_target['depot-refill-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['depot-refill-orders'] . '<br/>' . kpiFormatPercentage($total['depot-refill-orders'], $on_target['depot-refill-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['depot-refill-orders'] . '<br/>' . kpiFormatPercentage($total['depot-refill-orders'], $above_target_1to3d['depot-refill-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['depot-refill-orders'] . '<br/>' . kpiFormatPercentage($total['depot-refill-orders'], $above_target_gt3d['depot-refill-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['depot-refill-orders'] . '<br/>' . kpiFormatPercentage($total['depot-refill-orders'], $total['depot-refill-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['depot-refill-orders']) ? $leadtime_avg['depot-refill-orders'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['depot-refill-orders']) ? $leadtime_median['depot-refill-orders'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    $kpi_lead .= '<tr class="o">';
    $kpi_lead .= '<td>Internal Levelling Orders</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-internal-levelling-orders" value="' . $target_leadtime['internal-levelling-orders'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['internal-levelling-orders'] . '<br/>' . kpiFormatPercentage($total['internal-levelling-orders'], $below_target['internal-levelling-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['internal-levelling-orders'] . '<br/>' . kpiFormatPercentage($total['internal-levelling-orders'], $on_target['internal-levelling-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['internal-levelling-orders'] . '<br/>' . kpiFormatPercentage($total['internal-levelling-orders'], $above_target_1to3d['internal-levelling-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['internal-levelling-orders'] . '<br/>' . kpiFormatPercentage($total['internal-levelling-orders'], $above_target_gt3d['internal-levelling-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['internal-levelling-orders'] . '<br/>' . kpiFormatPercentage($total['internal-levelling-orders'], $total['internal-levelling-orders']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['internal-levelling-orders']) ? $leadtime_avg['internal-levelling-orders'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['internal-levelling-orders']) ? $leadtime_median['internal-levelling-orders'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    $kpi_lead .= '<tr class="o">';
    $kpi_lead .= '<td>Customer Orders (MTO/MMO)</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-cust-order-mto-mmo" value="' . $target_leadtime['cust-order-mto-mmo'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['cust-order-mto-mmo'] . '<br/>' . kpiFormatPercentage($total['cust-order-mto-mmo'], $below_target['cust-order-mto-mmo']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['cust-order-mto-mmo'] . '<br/>' . kpiFormatPercentage($total['cust-order-mto-mmo'], $on_target['cust-order-mto-mmo']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['cust-order-mto-mmo'] . '<br/>' . kpiFormatPercentage($total['cust-order-mto-mmo'], $above_target_1to3d['cust-order-mto-mmo']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['cust-order-mto-mmo'] . '<br/>' . kpiFormatPercentage($total['cust-order-mto-mmo'], $above_target_gt3d['cust-order-mto-mmo']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['cust-order-mto-mmo'] . '<br/>' . kpiFormatPercentage($total['cust-order-mto-mmo'], $total['cust-order-mto-mmo']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['cust-order-mto-mmo']) ? $leadtime_avg['cust-order-mto-mmo'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['cust-order-mto-mmo']) ? $leadtime_median['cust-order-mto-mmo'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    //Outsourcing
    $kpi_lead .= '<tr class="e">';
    $kpi_lead .= '<td><strong>Outsourcing</strong></td>';
    $kpi_lead .= '<td>External Levelling Orders</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-external-levelling-order" value="' . $target_leadtime['external-levelling-order'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['external-levelling-order'] . '<br/>' . kpiFormatPercentage($total['external-levelling-order'], $below_target['external-levelling-order']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['external-levelling-order'] . '<br/>' . kpiFormatPercentage($total['external-levelling-order'], $on_target['external-levelling-order']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['external-levelling-order'] . '<br/>' . kpiFormatPercentage($total['external-levelling-order'], $above_target_1to3d['external-levelling-order']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['external-levelling-order'] . '<br/>' . kpiFormatPercentage($total['external-levelling-order'], $above_target_gt3d['external-levelling-order']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['external-levelling-order'] . '<br/>' . kpiFormatPercentage($total['external-levelling-order'], $total['external-levelling-order']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['external-levelling-order']) ? $leadtime_avg['external-levelling-order'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['external-levelling-order']) ? $leadtime_median['external-levelling-order'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    //Customer Order
    $kpi_lead .= '<tr class="o">';
    $kpi_lead .= '<td rowspan="2"><strong>Customer Order</strong></td>';
    $kpi_lead .= '<td>Full DSO</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-full-dso" value="' . $target_leadtime['full-dso'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['full-dso'] . '<br/>' . kpiFormatPercentage($total['full-dso'], $below_target['full-dso']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['full-dso'] . '<br/>' . kpiFormatPercentage($total['full-dso'], $on_target['full-dso']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['full-dso'] . '<br/>' . kpiFormatPercentage($total['full-dso'], $above_target_1to3d['full-dso']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['full-dso'] . '<br/>' . kpiFormatPercentage($total['full-dso'], $above_target_gt3d['full-dso']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['full-dso'] . '<br/>' . kpiFormatPercentage($total['full-dso'], $total['full-dso']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['full-dso']) ? $leadtime_avg['full-dso'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['full-dso']) ? $leadtime_median['full-dso'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    $kpi_lead .= '<tr class="o">';
    $kpi_lead .= '<td>MTO (Full MTO and Mixed Orders)</td>';
    $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-mto" value="' . $target_leadtime['mto'] . '"' . $tooltip_info_saved . '/></td>';
    $kpi_lead .= '<td class="tac">' . $below_target['mto'] . '<br/>' . kpiFormatPercentage($total['mto'], $below_target['mto']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $on_target['mto'] . '<br/>' . kpiFormatPercentage($total['mto'], $on_target['mto']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_1to3d['mto'] . '<br/>' . kpiFormatPercentage($total['mto'], $above_target_1to3d['mto']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $above_target_gt3d['mto'] . '<br/>' . kpiFormatPercentage($total['mto'], $above_target_gt3d['mto']) . '</td>';
    $kpi_lead .= '<td class="tac">' . $total['mto'] . '<br/>' . kpiFormatPercentage($total['mto'], $total['mto']) . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg['mto']) ? $leadtime_avg['mto'] : 'N/A') . '</td>';
    $kpi_lead .= '<td class="tac">' . (isset($leadtime_median['mto']) ? $leadtime_median['mto'] : 'N/A') . '</td>';
    $kpi_lead .= '</tr>';
    //Design
    $kpi_lead .= '<tr class="e">';
    $kpi_lead .= '<td rowspan="' . count($design_categories) . '"><strong>Design</strong></td>';
    $des_cat_id_counter = 0;
    foreach ($design_categories as $des_cat_id => $des_cat_name) {
        $des_cat_id_counter++;
        if ($des_cat_id_counter > 1) {
            $kpi_lead .= '<tr class="e">';
        }
        $design_order_type = "design-{$des_cat_id}";
        $kpi_lead .= "<td>{$des_cat_name}</td>";
        $kpi_lead .= '<td class="tac"><input type="text" class="target_leadtime w040 tac" name="lt-design-' . $des_cat_id . '" value="' . $target_leadtime[$design_order_type] . '"' . $tooltip_info_saved . '/></td>';
        $kpi_lead .= '<td class="tac">' . $below_target[$design_order_type] . '<br/>' . kpiFormatPercentage($total[$design_order_type], $below_target[$design_order_type]) . '</td>';
        $kpi_lead .= '<td class="tac">' . $on_target[$design_order_type] . '<br/>' . kpiFormatPercentage($total[$design_order_type], $on_target[$design_order_type]) . '</td>';
        $kpi_lead .= '<td class="tac">' . $above_target_1to3d[$design_order_type] . '<br/>' . kpiFormatPercentage($total[$design_order_type], $above_target_1to3d[$design_order_type]) . '</td>';
        $kpi_lead .= '<td class="tac">' . $above_target_gt3d[$design_order_type] . '<br/>' . kpiFormatPercentage($total[$design_order_type], $above_target_gt3d[$design_order_type]) . '</td>';
        $kpi_lead .= '<td class="tac">' . $total[$design_order_type] . '<br/>' . kpiFormatPercentage($total[$design_order_type], $total[$design_order_type]) . '</td>';
        $kpi_lead .= '<td class="tac">' . (isset($leadtime_avg[$design_order_type]) ? $leadtime_avg[$design_order_type] : 'N/A') . '</td>';
        $kpi_lead .= '<td class="tac">' . (isset($leadtime_median[$design_order_type]) ? $leadtime_median[$design_order_type] : 'N/A') . '</td>';
        $kpi_lead .= '</tr>';
    }
    $kpi_lead .= '</tbody>';
    $kpi_lead .= '</table>';
    return $kpi_lead;
}
Example #5
0
            foreach ($players as $player_id => $apm) {
                $playerApms[$player_id][] = $apm;
            }
        }
        foreach ($playerApms as $player_id => $apmArray) {
            $playerApms[$player_id] = median($apmArray);
        }
        $weightedApm = array_fill_keys(array_keys($playerApms), 0);
        // initialize with zeroes
        $weightSum = 0;
        foreach ($tmp as $time => $action_counts) {
            $weights = $action_counts;
            foreach ($action_counts as $player_id => $action_count) {
                $weights[$player_id] = 1 / (1 + exp(2 * ($action_count - $playerApms[$player_id]) / $timespan));
            }
            $weight = median($weights);
            $weightSum += $weight;
            foreach ($action_counts as $player_id => $action_count) {
                $weightedApm[$player_id] += $weight * $action_count;
            }
        }
        //die('<pre>'.print_r($weightedApm,true).'</pre></html>');
        $width = round(10 * 100 / (1 + sizeof($player_names))) / 10;
        // must add 1 to account for the time column
        $clr = '222233';
        echo '<h2>Player actions</h2>
				<a href="javascript:display(\'actions\');">&#187; Show APM table</a><div id="actions" class="additional">
				<p><table width="100%"><tr><td align=center bgcolor=' . $clr . ' width="' . $width . '%"><b>Time (s)</b></td>';
        $jsData = "\n['Time' ";
        foreach ($player_names as $player_id => $player_name) {
            $jsData .= ", '" . str_replace(',', '', $player_name) . "'";
Example #6
0
	function Search($s) {
		//print_r($s);
		
		/*
			***************** steps to searching *****************
			1) build the search string
			2) run the query
			3) depending on the query type, either...
				a) display the query, then end
				b) display the results
		*/
		
		/* --------- [1] get the SQL search string ---------- */
		$sqlstring = BuildSQLString($s);

		if ($sqlstring == "") { return; }
		
		/* escape all the variables and put them back into meaningful variable names */
		foreach ($s as $key => $value) {
			if (is_scalar($value)) { $$key = mysql_real_escape_string($s[$key]); }
			else { $$key = $s[$key]; }
		}
		
		/* make modality lower case to conform with table names... MySQL table names are case sensitive when using the 'show tables' command */
		$s_studymodality = strtolower($s_studymodality);
		
		/* ---------- [2] run the query ----------- */
		$starttime = microtime(true);
		$result = MySQLQuery($sqlstring, __FILE__, __LINE__);
		$querytime = microtime(true) - $starttime;
		
		if ($s_resultorder == "debug") {
			?>
			<span class="sublabel">Query returned <?php 
echo mysql_num_rows($result);
?>
 rows in <?php 
echo number_format($querytime, 4);
?>
 sec</span>
			<div style="background-color: #EEEEEE"><?php 
echo $sqlstring;
?>
</div><br>
			<div style="background-color: #EEEEEE"><?php 
echo getFormattedSQL($sqlstring);
?>
</div>
			<br><br><br><br>
			<?
			return;
		}

		/* display the results */
		if (mysql_num_rows($result) > 0) {
		
			if ((mysql_num_rows($result) > 100000) && ($s_resultorder != "pipelinecsv")) {
				?>
				<div style="border: 2px solid darkred; background-color: #FFEEEE; text-align: left; padding:5px; border-radius: 5px">
				<b>Your search returned <? echo number_format(mysql_num_rows($result),0); ?> results... which is a lot</b>
				<br>
				Try changing the search criteria to return fewer results or select a .csv format
				</div>
				<?
				return;
			}

			/* generate a color gradient in an array (green to yellow to red) */
			$colors = GenerateColorGradient();
			$colors2 = GenerateColorGradient2();
			
			/* display the number of rows and the search time */
			?>
			<span class="sublabel">Query returned <? echo number_format(mysql_num_rows($result),0); ?> rows in <?php 
echo number_format($querytime, 4);
?>
 sec</span>
			<details>
				<summary style="font-size:9pt">View SQL query:</summary>
				<div style="background-color: #EEEEEE; font-family:courier new; font-size:10pt"><?php 
echo getFormattedSQL($sqlstring);
?>
<br></div>
			</details>
			<style>
			#preview {
				position:absolute;
				border:1px solid #ccc;
				background:gray;
				padding:0px;
				display:none;
				color:#fff;
			}
			</style>
			<script type="text/javascript">
			// Popup window code
			function newPopup(url) {
				popupWindow = window.open(
					url,'popUpWindow','height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no')
			}
			</script>
			<?
			
			/* ---------- pipeline results ------------ */
			if (($s_resultorder == "pipeline") || ($s_resultorder == "pipelinecsv")) {
				if ($s_pipelineresulttype == "i") {
					/* get the result names first (due to MySQL bug which prevents joining in this table in the main query) */
					$sqlstringX = "select * from analysis_resultnames where result_name like '%$s_pipelineresultname%' ";
					$resultX = MySQLQuery($sqlstringX,__FILE__,__LINE__);
					while ($rowX = mysql_fetch_array($resultX, MYSQL_ASSOC)) {
						$resultnames[$rowX['resultname_id']] = $rowX['result_name'];
					}
					/* and get the result unit (due to the same MySQL bug) */
					$sqlstringX = "select * from analysis_resultunit where result_unit like '%$s_pipelineresultunit%' ";
					$resultX = MySQLQuery($sqlstringX,__FILE__,__LINE__);
					while ($rowX = mysql_fetch_array($resultX, MYSQL_ASSOC)) {
						$resultunit[$rowX['resultunit_id']] = $rowX['result_unit'];
					}
					
					/* ---------------- pipeline results (images) --------------- */
					while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
						//PrintVariable($row,'row');
					
						$step = $row['analysis_step'];
						$pipelinename = $row['pipeline_name'];
						$uid = $row['uid'];
						$subject_id = $row['subject_id'];
						$gender = $row['gender'];
						$study_id = $row['study_id'];
						$study_num = $row['study_num'];
						$type = $row['result_type'];
						$size = $row['result_size'];
						//$name = $row['result_name'];
						$name = $resultnames[$row['result_nameid']];
						$unit = $resultunit[$row['result_unitid']];
						$filename = $row['result_filename'];
						$swversion = $row['result_softwareversion'];
						$important = $row['result_isimportant'];
						$lastupdate = $row['result_lastupdate'];
						
						switch($type) {
							case "v": $thevalue = $value; break;
							case "f": $thevalue = $filename; break;
							case "t": $thevalue = $text; break;
							case "h": $thevalue = $filename; break;
							case "i": $thevalue = $filename; break;
						}
						$tables["$uid$study_num"][$name] = $thevalue;
						$tables["$uid$study_num"]['subjectid'] = $subject_id;
						$tables["$uid$study_num"]['studyid'] = $study_id;
						$tables["$uid$study_num"]['studynum'] = $study_num;
						$names[$name] = "blah";
					}
					//PrintVariable($tables,'Tables');
					?>
					<table cellspacing="0" class="multicoltable">
						<thead>
						<tr>
							<th>UID</th>
							<?
							foreach ($names as $name => $blah) {
								?>
								<th align="center" style="font-size:9pt"><?php 
echo $name;
?>
</th>
								<?
							}
						?>
						</tr>
						</thead>
						<?
							$maximgwidth = 1200/count($names);
							$maximgwidth -= ($maximgwidth*0.05); /* subtract 5% of image width to give a gap between them */
							if ($maximgwidth < 100) { $maximgwidth = 100; }
							foreach ($tables as $uid => $valuepair) {
								?>
								<tr style="font-weight: <?php 
echo $bold;
?>
">
									<td><a href="studies.php?id=<?php 
echo $tables[$uid]['studyid'];
?>
"><b><?php 
echo $uid;
?>
</b></a></td>
									<?
									foreach ($names as $name => $blah) {
										if ($tables[$uid][$name] == "") { $dispval = "-"; }
										else { $dispval = $tables[$uid][$name]; }
										list($width, $height, $type, $attr) = getimagesize("/mount$filename");
										$filesize = number_format(filesize("/mount$filename")/1000) . " kB";
									?>
										<td style="padding:2px"><a href="preview.php?image=/mount<?php 
echo $dispval;
?>
" class="preview"><img src="preview.php?image=/mount<?php 
echo $dispval;
?>
" style="max-width: <?php 
echo $maximgwidth;
?>
px"></a></td>
										
									<?
									}
									?>
								</tr>
								<?
							}
						?>
					</table>
					<br><br><br><br><br><br><br><br>
					<?
				}
				else {
				/* ---------------- pipeline results (values) --------------- */
				/* get the result names first (due to MySQL bug which prevents joining in this table in the main query) */
				$sqlstringX = "select * from analysis_resultnames where result_name like '%$s_pipelineresultname%' ";
				$resultX = MySQLQuery($sqlstringX,__FILE__,__LINE__);
				while ($rowX = mysql_fetch_array($resultX, MYSQL_ASSOC)) {
					$resultnames[$rowX['resultname_id']] = $rowX['result_name'];
				}
				/* and get the result unit (due to the same MySQL bug) */
				$sqlstringX = "select * from analysis_resultunit where result_unit like '%$s_pipelineresultunit%' ";
				$resultX = MySQLQuery($sqlstringX,__FILE__,__LINE__);
				while ($rowX = mysql_fetch_array($resultX, MYSQL_ASSOC)) {
					$resultunit[$rowX['resultunit_id']] = $rowX['result_unit'];
				}

				/* load the data into a useful table */
				while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
					
					$step = $row['analysis_step'];
					$pipelinename = $row['pipeline_name'];
					$uid = $row['uid'];
					$subject_id = $row['subject_id'];
					$study_id = $row['study_id'];
					$study_num = $row['study_num'];
					$birthdate = $row['birthdate'];
					$gender = $row['gender'];
					$study_datetime = $row['study_datetime'];
					$type = $row['result_type'];
					$size = $row['result_size'];
					$name = $resultnames[$row['result_nameid']];
					$name2 = $resultnames[$row['result_nameid']];
					$unit = $resultunit[$row['result_unitid']];
					$unit2 = $resultunit[$row['result_unitid']];
					$text = $row['result_text'];
					$value = $row['result_value'];
					$filename = $row['result_filename'];
					$swversion = $row['result_softwareversion'];
					$important = $row['result_isimportant'];
					$lastupdate = $row['result_lastupdate'];
					
					/* calculate age at scan */
					list($year, $month, $day) = explode("-", $birthdate);
					$d1 = mktime(0,0,0,$month,$day,$year);
					list($year, $month, $day, $extra) = explode("-", $study_datetime);
					$d2 = mktime(0,0,0,$month,$day,$year);
					$ageatscan = number_format((($d2-$d1)/31536000),1);					
					
					if (strpos($unit,'^') !== false) {
						$unit = str_replace('^','<sup>',$unit);
						$unit .= '</sup>';
					}
					
					switch($type) {
						case "v": $thevalue = $value; break;
						case "f": $thevalue = $filename; break;
						case "t": $thevalue = $text; break;
						case "h": $thevalue = $filename; break;
						case "i":
							?>
							<a href="preview.php?image=/mount<?php 
echo $filename;
?>
" class="preview"><img src="images/preview.gif" border="0"></a>
							<?
							break;
					}
					if (substr($name, -(strlen($unit))) != $unit) {
						$name .= " <b>$unit</b>";
						$name2 .= " " . $row['result_unit'];
					}
					$tables[$uid][$name] = $thevalue;
					$tables[$uid][$name2] = $thevalue;
					$tables[$uid]['age'] = $ageatscan;
					$tables[$uid]['gender'] = $gender;
					$tables[$uid]['subjectid'] = $subject_id;
					$tables[$uid]['studyid'] = $study_id;
					$tables[$uid]['studynum'] = $study_num;
					//$names[$name] = "blah";
					if (($thevalue > $names[$name]['max']) || ($names[$name]['max'] == "")) { $names[$name]['max'] = $thevalue; }
					if (($thevalue < $names[$name]['min']) || ($names[$name]['min'] == "")) { $names[$name]['min'] = $thevalue; }
					
					if (($thevalue > $names2[$name2]['max']) || ($names2[$name2]['max'] == "")) { $names2[$name2]['max'] = $thevalue; }
					if (($thevalue < $names2[$name2]['min']) || ($names2[$name2]['min'] == "")) { $names2[$name2]['min'] = $thevalue; }
				}

				if ($s_resultorder == "pipelinecsv") {
					$csv = "uid,studynum,sex,age";
					foreach ($names2 as $name2 => $blah) {
						$csv .= ",$name2";
					}
					$csv .= "\n";
					foreach ($tables as $uid => $valuepair) {
						$csv .= $uid . ',' . $tables[$uid]['studynum'] . ',' . $tables[$uid]['gender'] . ',' . $tables[$uid]['age'];
						foreach ($names2 as $name2 => $blah) {
							$csv .= ',' . $tables[$uid][$name2];
						}
						$csv .= "\n";
					}
					$filename = "query" . GenerateRandomString(10) . ".csv";
					file_put_contents("/tmp/" . $filename, $csv);
					?>
					<br><br>
					<div width="50%" align="center" style="background-color: #FAF8CC; padding: 5px;">
					Download .csv file <a href="download.php?type=file&filename=<?php 
echo "/tmp/{$filename}";
?>
"><img src="images/download16.png"></a>
					</div>
					<?
				}
				else {
				?>
					<br><br><br><br><br>
					<br><br><br><br><br>
					<br><br><br><br><br>
					<style>
						tr.rowhover:hover { background-color: ffff96; }
						td.tdhover:hover { background-color: yellow; }
					</style>
					<table cellspacing="0">
						<tr>
							<td>UID</td>
							<td>Sex</td>
							<td>Age</td>
							<?
							$csv = "studyid,sex,age";
							foreach ($names as $name => $blah) {
								$csv .= ",$name";
								?>
								<td style="max-width:25px;"><span style="padding-left: 8px; font-size:10pt; white-space:nowrap; display: block; -webkit-transform: rotate(-70deg) translate3d(0,0,0); -moz-transform: rotate(-70deg);"><?php 
echo $name;
?>
</span></td>
								<?
							}
							$csv .= "\n";
						?>
						</tr>
						<?
							foreach ($tables as $uid => $valuepair) {
								?>
								<tr style="font-weight: <?php 
echo $bold;
?>
" class="rowhover">
									<td>
									<a href="studies.php?id=<?php 
echo $tables[$uid]['studyid'];
?>
"><b><?php 
echo $uid;
?>
</b><?php 
echo $tables[$uid]['studynum'];
?>
</a>
									</td>
									<td style="border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:9pt; padding:2px;"><?php 
echo $tables[$uid]['gender'];
?>
</td>
									<td style="border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:9pt; padding:2px;"><?php 
echo $tables[$uid]['age'];
?>
</td>
									<?
									$stats[0][$tables[$uid]['gender']]++;
									$stats[1][] = $tables[$uid]['age'];
									$csv .= $tables[$uid]['studyid'] . ',' . $tables[$uid]['gender'] . ',' . $tables[$uid]['age'];
									$i=2;
									foreach ($names as $name => $blah) {
										$val = $tables[$uid][$name];
										$range = $names[$name]['max'] - $names[$name]['min'];
										if (($val > 0) && ($range > 0)) {
											$cindex = round((($val - $names[$name]['min'])/$range)*100);
											//echo "[$val, $range, $cindex]<br>";
											if ($cindex > 100) { $cindex = 100; }
										}
										
										if ($tables[$uid][$name] == "") {
											$dispval = "-";
										}
										else {
											$dispval = $tables[$uid][$name];
											$stats[$i][] = $val;
											//$stats[$i]['numintotal'] ++;
										}
										$csv .= ',' . $tables[$uid][$name];
										if ($dispval != '-') {
											if (($dispval + 0) > 10000) { $dispval = number_format($dispval,0); }
											elseif (($dispval + 0) > 1000) { $dispval = number_format($dispval,2); }
											else { $dispval = number_format($dispval,4); }
										}
									?>
										<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px; background-color: <? if ($s_pipelinecolorize) { if (trim($dispval) == '-') { echo "#EEE"; } else { echo $colors[$cindex]; } } ?>"><?php 
echo $dispval;
?>
</td>
									<?
										$i++;
									}
									$csv .= "\n";
									?>
								</tr>
								<?
							}
							if ($s_pipelineresultstats == 1) {
								?>
								<tr class="rowhover">
									<td align="right"><b>N</b></td>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;">
									<?
										foreach ($stats[0] as $key => $value) { echo "$key -> $value<br>"; }
									?>
									</td>
									<?
									for($i=1;$i<count($stats);$i++) {
										$count = count($stats[$i]);
										?><td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"><?php 
echo $count;
?>
</td><?
									}
									?>
								</tr>
								<tr class="rowhover">
									<td align="right"><b>Min</b></td>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"></td>
									<?
									for($i=1;$i<count($stats);$i++) {
										$min = min($stats[$i]);
										?><td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"><?php 
echo $min;
?>
</td><?
									}
									?>
								</tr>
								<tr class="rowhover">
									<td align="right"><b>Max</b></td>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"></td>
									<?
									for($i=1;$i<count($stats);$i++) {
										$max = max($stats[$i]);
										?><td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"><?php 
echo $max;
?>
</td><?
									}
									?>
								</tr>
								<tr class="rowhover">
									<td align="right"><b>Mean</b></td>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"></td>
									<?
									for($i=1;$i<count($stats);$i++) {
										$avg = number_format(array_sum($stats[$i])/count($stats[$i]),2);
										?><td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"><?php 
echo $avg;
?>
</td><?
									}
									?>
								</tr>
								<tr class="rowhover">
									<td align="right"><b>Median</b></td>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"></td>
									<?
									for($i=1;$i<count($stats);$i++) {
										$median = number_format(median($stats[$i]),2);
										?><td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"><?php 
echo $median;
?>
</td><?
									}
									?>
								</tr>
								<tr class="rowhover">
									<td align="right"><b>Std Dev</b></td>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"></td>
									<?
									for($i=1;$i<count($stats);$i++) {
										$stdev = number_format(sd($stats[$i]),2);
										?><td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px;"><?php 
echo $stdev;
?>
</td><?
									}
									?>
								</tr>
								<?
							}
						?>
					</table>
					<? if ($s_pipelinecormatrix == 1) { ?>
					<br><br><br><br>
					<br><br><br><br>
					<b>Correlation Matrix (r)</b><br>
					<?
						foreach ($names as $name => $blah) {
							foreach ($tables as $uid => $valuepair) {
								$lists['age'][] = $tables[$uid]['age'];
								
								/* this loop gets the data into an array */
								foreach ($names as $name => $blah) {
									$lists[$name][] = $tables[$uid][$name];
								}
								
							}
						}
					?>
					<table cellspacing="0">
						<tr>
							<td>&nbsp;</td>
							<? foreach ($lists as $label => $vals1) { ?>
							<td style="max-width:25px;"><span style="padding-left: 8px; font-size:10pt; white-space:nowrap; display: block; -webkit-transform: rotate(-70deg) translate3d(0,0,0); -moz-transform: rotate(-70deg);"><?php 
echo $label;
?>
</span></td>
							<? } ?>
						</tr>
						<?
							$kashi = new Kashi();
							foreach ($lists as $label => $vals1) {
								for ($i=0;$i<count($vals1);$i++) {
									if ($vals1[$i] == 0) { $vals1[$i] = 0.000001; }
								}
								?>
								<tr class="rowhover">
									<td align="right" style="font-size:10pt"><?php 
echo $label;
?>
</td>
								<?
								foreach ($lists as $label => $vals2) {
									$starttime1 = microtime(true);
									/* compare vals1 to vals2 */
									//$coeff = Correlation($vals1,$vals2);
									for ($i=0;$i<count($vals2);$i++) {
										if ($vals2[$i] == 0) { $vals2[$i] = 0.000001; }
									}
									$coeff = $kashi->cor($vals1,$vals2);
									$coefftime = microtime(true) - $starttime1;
									
									$cindex = round((($coeff - (-1))/2)*100);
									//echo "[$val, $range, $cindex]<br>";
									if ($cindex > 100) { $cindex = 100; }
									/* display correlation coefficient */
									?>
									<td class="tdhover" style="text-align: right; border-left: 1px solid #AAAAAA; border-top: 1px solid #AAAAAA; font-size:8pt; padding:2px; background-color: <?php 
echo $colors2[$cindex];
?>
"><?php 
echo number_format($coeff, 3);
?>
</td>
									<?
									flush();
								}
								?>
								</tr>
								<?
							}
						?>
					</table>
					<?
						}
					}
				}
			}
			elseif ($s_resultorder == 'subject') {
				/* display only subject data */
				SearchStudy($result);
			}
			elseif ($s_resultorder == 'uniquesubject') {
				/* display only unique subject data */
				SearchSubject($result);
			}
			elseif ($s_resultorder == 'long') {
				/* display longitudinal data */
				SearchLongitudinal($result);
			}
			else {
				SearchDefault($result, $s, $colors, $colors2);
			}
		}
		else {
			?>
			<span class="sublabel">Query returned <? echo number_format(mysql_num_rows($result),0); ?> rows in <?php 
echo number_format($querytime, 4);
?>
 sec</span>
			<details>
				<summary style="font-size:9pt">View SQL query:</summary>
				<div style="background-color: #EEEEEE; font-family:courier new; font-size:10pt"><?php 
echo getFormattedSQL($sqlstring);
?>
<br></div>
			</details>
			<br>
			<?
		}
	}
Example #7
0
 public static function getResultHistoricalValue($data, $obj)
 {
     $value = 0;
     if (count($data) <= 1) {
         return $value;
         //TODO: Handle cases where amount of data returned is less than expected
     }
     $historical_data = array_slice($data, 0, count($data) - 1);
     if ($obj->getBaseline() == 'average') {
         $value = average($historical_data);
     } elseif ($obj->getBaseline() == 'median') {
         $value = median($historical_data);
     }
     return $value;
 }
Example #8
0
function process_microarray_data_adaptive_quantification_method($file)
{
    // find data for first column and row, and remove all headings;
    $file = substr($file, strpos($file, "1\t1\t"));
    // remove from file returns (\r) and (\")
    $file = preg_replace("/\r|\"/", "", $file);
    // split file into lines ($data_array)
    $data_array = preg_split("/\n/", $file, -1, PREG_SPLIT_NO_EMPTY);
    // compute data-background (save result in $data_array2) and
    //   sum of all data-background ($sum_ch1 and $sum_ch2)
    $sum_ch1 = 0;
    $sum_ch2 = 0;
    foreach ($data_array as $key => $val) {
        // example of line to be splitted:
        // 1        2        G16        1136        159        538        118
        // where        1 and 2 define position in the plate
        //              G16 is name of gene/experiment
        //              1136 is reading of chanel 1, and 159 is the background
        //              538 is reading of chanel 2, and 159 is the background
        $line_element = preg_split("/\t/", $val, -1, PREG_SPLIT_NO_EMPTY);
        if (sizeof($line_element) < 7) {
            continue;
        }
        // This is the name of the gene studied
        $name = $line_element[2];
        // For chanel 1
        // calculate data obtained in chanel 1 minus background
        $ch1_bg = $line_element[3] - $line_element[4];
        // save data to a element in $data_array2 (separate diferent calculations from the same gene with commas)
        $data_array2[$name][1] .= "," . $ch1_bg;
        // $sum_ch1 will record the sum of all (chanel 1 - background) values
        $sum_ch1 += $ch1_bg;
        // For chanel 2
        // calculate data obtained in chanel 2 minus background
        $ch2_bg = $line_element[5] - $line_element[6];
        // save data to a element in $data_array2 (separate diferent calculations from the same gene with commas)
        $data_array2[$name][2] .= "," . $ch2_bg;
        // $sum_ch1 will record the sum of all (chanel 2 - background) values
        $sum_ch2 += $ch2_bg;
        // count number of total elements
        $n_data++;
    }
    // Compute (data-background)*100/sum(data-background)),
    //    where sum(data-background) is $sum_ch1 or $sum_ch2
    //    and save data in  $data_array3
    foreach ($data_array2 as $key => $val) {
        // split data separated by comma (chanel 1)
        $data_element = preg_split("/,/", $data_array2[$key][1], -1, PREG_SPLIT_NO_EMPTY);
        foreach ($data_element as $key2 => $value) {
            // compute ratios
            $ratio = $value * 100 / $sum_ch1;
            // save result to $data_array3
            $data_array3[$key][1] .= ",{$ratio}";
        }
        // split data separated by comma (chanel 2)
        $data_element = preg_split("/,/", $data_array2[$key][2], -1, PREG_SPLIT_NO_EMPTY);
        foreach ($data_element as $key2 => $value) {
            // compute ratios
            $ratio = $value * 100 / $sum_ch2;
            // save result to $data_array3
            $data_array3[$key][2] .= ",{$ratio}";
        }
    }
    // Compute ratios for values in chanel 1 and chanel 2
    //     chanel 1/chanel 2  and  chanel 2/chanel 1
    // save results to $data_array4
    foreach ($data_array3 as $key => $val) {
        $data_element1 = preg_split("/,/", $data_array3[$key][1], -1, PREG_SPLIT_NO_EMPTY);
        $data_element2 = preg_split("/,/", $data_array3[$key][2], -1, PREG_SPLIT_NO_EMPTY);
        foreach ($data_element1 as $key2 => $value) {
            //compute ch1/ch2
            $ratio = $data_element1[$key2] / $data_element2[$key2];
            // and save
            $data_array4[$key][1] .= ",{$ratio}";
            //compute ch2/ch1
            $ratio = $data_element2[$key2] / $data_element1[$key2];
            // and save
            $data_array4[$key][2] .= ",{$ratio}";
        }
    }
    ksort($data_array4);
    foreach ($data_array4 as $key => $val) {
        $results[$key]["n_data"] = substr_count($data_array4[$key][1], ",");
        $results[$key]["median1"] = median($data_array4[$key][1]);
        $results[$key]["median2"] = median($data_array4[$key][2]);
    }
    return $results;
}
Example #9
0
            $middle = (sizeof($list) - 1) / 2 + 1;
            return $list[$middle - 1];
        }
    }
    ?>
                <th>Median</th>
                <th class="text-right"><?php 
    echo round(median($male_count_per_day));
    ?>
</th>
                <th class="text-right"><?php 
    echo round(median($female_count_per_day));
    ?>
</th>
                <th class="text-right"><?php 
    echo round(median($total_count_per_day));
    ?>
</th>
        </tr>
        <tr>
                <th>Average</th>
                <th class="text-right"><?php 
    echo round($total_male / $number_of_records);
    ?>
</th>
                <th class="text-right"><?php 
    echo round($total_female / $number_of_records);
    ?>
</th>
                <th class="text-right"><?php 
    echo round($total / $number_of_records);
Example #10
0
 public function testMedian()
 {
     $values = array(1 => 0, 2 => 1, 3 => 3, 4 => 6, 5 => 10);
     $this->assertEquals(3, median($values));
 }
Example #11
0
function get_class_avg($gradebook_test_id)
{
    global $db;
    $sql = "SELECT * FROM " . TABLE_PREFIX . "gradebook_tests WHERE gradebook_test_id=" . $gradebook_test_id;
    $result = mysql_query($sql, $db) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    if ($row["id"] != 0) {
        require_once AT_INCLUDE_PATH . '../mods/_standard/tests/lib/test_result_functions.inc.php';
        $sql_test = "SELECT * FROM " . TABLE_PREFIX . "tests WHERE test_id=" . $row["id"];
        $result_test = mysql_query($sql_test, $db) or die(mysql_error());
        $row_test = mysql_fetch_assoc($result_test);
        if ($row_test['out_of'] == 0 || $row_test['result_release'] == AT_RELEASE_NEVER) {
            return _AT("na");
        }
        $sql_marks = "SELECT * FROM " . TABLE_PREFIX . "tests_results WHERE test_id=" . $row["id"] . " AND status=1";
        $result_marks = mysql_query($sql_marks, $db) or die(mysql_error());
        $num_students = 0;
        $total_final_score = 0;
        $total_out_of = 0;
        while ($row_marks = mysql_fetch_assoc($result_marks)) {
            if ($row_marks['final_score'] == '') {
                continue;
            }
            $num_students++;
            $total_final_score += $row_marks["final_score"];
            if ($row_test['random']) {
                $total_out_of += get_random_outof($row_marks['test_id'], $row_marks['result_id']);
            } else {
                $total_out_of += $row_test['out_of'];
            }
        }
        if ($num_students > 0) {
            $avg_final_score = round($total_final_score / $num_students);
            $avg_out_of = round($total_out_of / $num_students);
        }
        if ($avg_final_score != "") {
            $avg_grade = get_mark_by_grade($row["grade_scale_id"], $avg_final_score, $avg_out_of);
        } else {
            $avg_grade = "";
        }
    } else {
        $sql_grades = "SELECT * FROM " . TABLE_PREFIX . "gradebook_detail WHERE gradebook_test_id=" . $gradebook_test_id . " ORDER BY grade";
        $result_grades = mysql_query($sql_grades, $db) or die(mysql_error());
        $grade_array = array();
        while ($row_grades = mysql_fetch_assoc($result_grades)) {
            $grade_array[] = $row_grades["grade"];
        }
        $avg_grade = median($grade_array);
    }
    if ($avg_grade == "") {
        return _AT("na");
    } else {
        return $avg_grade;
    }
}
Example #12
0
	function DisplayPipelineForm($type, $id) {
	
		$level = 0;
		/* populate the fields if this is an edit */
		if ($type == "edit") {
			$sqlstring = "select a.*, b.username from pipelines a left join users b on a.pipeline_admin = b.user_id where a.pipeline_id = $id";
			$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
			$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
			$title = $row['pipeline_name'];
			$pipeline_status = $row['pipeline_status'];
			$pipeline_statusmessage = $row['pipeline_statusmessage'];
			$pipeline_laststart = $row['pipeline_laststart'];
			$pipeline_lastfinish = $row['pipeline_lastfinish'];
			$pipeline_lastcheck = $row['pipeline_lastcheck'];
			$desc = $row['pipeline_desc'];
			$numproc = $row['pipeline_numproc'];
			$submithost = $row['pipeline_submithost'];
			$queue = $row['pipeline_queue'];
			$remove = $row['pipeline_removedata'];
			$version = $row['pipeline_version'];
			$directory = $row['pipeline_directory'];
			$usetmpdir = $row['pipeline_usetmpdir'];
			$tmpdir = $row['pipeline_tmpdir'];
			$pipelinenotes = $row['pipeline_notes'];
			$pipelinegroup = $row['pipeline_group'];
			$resultscript = $row['pipeline_resultsscript'];
			$deplevel = $row['pipeline_dependencylevel'];
			$depdir = $row['pipeline_dependencydir'];
			$deplinktype = $row['pipeline_deplinktype'];
			$completefiles = $row['pipeline_completefiles'];
			$dependency = $row['pipeline_dependency'];
			$groupid = $row['pipeline_groupid'];
			$dynamicgroupid = $row['pipeline_dynamicgroupid'];
			$level = $row['pipeline_level'];
			$owner = $row['username'];
			$ishidden = $row['pipeline_ishidden'];
			$isenabled = $row['pipeline_enabled'];

			//echo "<pre>";
			//print_r($GLOBALS);
			//echo "</pre>";
			
			if (($owner == $GLOBALS['username']) || ($GLOBALS['issiteadmin'])) {
				$readonly = false;
			}
			else {
				$readonly = true;
			}
			
			$formaction = "update";
			$formtitle = "$title";
			$submitbuttonlabel = "Update Pipeline Info";
		}
		else {
			$formaction = "add";
			$formtitle = "Add new pipeline";
			$submitbuttonlabel = "Add Pipeline Info";
			$remove = "0";
			$level = 1;
			$directory = "/home/" . $GLOBALS['username'] . "/onrc/data";
			$readonly = false;
		}
		
		if ($readonly) {
			$disabled = "disabled";
		}
		else {
			$disabled = "";
		}
		
		if ($numproc == "") { $numproc = 1; }
		
		//$urllist['Analysis'] = "analysis.php";
		$urllist['Pipelines'] = "pipelines.php";
		$urllist[$title] = "pipelines.php?action=editpipeline&id=$id";
		NavigationBar("Analysis", $urllist);
	?>
	
		<script type="text/javascript">
			$(document).ready(function() {
				/* default action */
				<? if($level == 1) { ?>
				$('.level0').hide();
				$('.level1').show();
				$('.level2').hide();
				<? } elseif ($level == 0) { ?>
				$('.level0').show();
				$('.level1').hide();
				$('.level2').hide();
				<? } else { ?>
				$('.level0').hide();
				$('.level1').show();
				$('.level2').show();
				<? } ?>
				
				/* click events */
				$('#level0').click(function() {
					if($('#level0').is(':checked')) {
						$('.level0').show("highlight",{},1000);
						$('.level1').hide();
						$('.level2').hide();
					}
				});
				$('#level1').click(function() {
					if($('#level1').is(':checked')) {
						$('.level0').hide();
						$('.level1').show("highlight",{},1000);
						$('.level2').hide();
					}
				});
				$('#level2').click(function() {
					if($('#level2').is(':checked')) {
						$('.level0').hide();
						$('.level1').show();
						$('.level2').show("highlight",{},1000);
					}
				});
			});

			function AlphaNumeric(e) {
				var key;
				var keychar;

				if (window.event)
					key = window.event.keyCode;
				else if (e)
					key = e.which;
				else
					return true;
					
				keychar = String.fromCharCode(key);
				keychar = keychar.toLowerCase();

				// control keys
				if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
					return true;
				// alphas and numbers
				else if ((("abcdefghijklmnopqrstuvwxyz0123456789_").indexOf(keychar) > -1))
					return true;
				else
					return false;
			}
		</script>
	
		<fieldset style="border: 3px solid #999; border-radius:5px">
			<legend style="background-color: #3B5998; color:white; padding:5px 10px; border-radius:5px">Status</legend>
			<table class="entrytable" style="border:0px">
				<tr>
					<td class="label" valign="top">Enabled</td>
					<td valign="middle">
						<?
							if ($isenabled) {
								?><a href="pipelines.php?action=disable&returnpage=pipeline&id=<?php 
echo $id;
?>
"><img src="images/checkedbox16.png"title="Pipeline enabled, click to disable"></a><?
							}
							else {
								?><a href="pipelines.php?action=enable&returnpage=pipeline&id=<?php 
echo $id;
?>
"><img src="images/uncheckedbox16.png" title="Pipeline disabled, click to enable"></a><?
							}
						?>
					</td>
				</tr>
				<tr>
					<td class="label" valign="top">Status<br><br></td>
					<td valign="top" style="font-size: 10pt">
						<b>Status</b> <?php 
echo $pipeline_status;
?>
<br>
						<b>Status message</b> <?php 
echo $pipeline_statusmessage;
?>
<br>
						<b>Last start</b> <?php 
echo $pipeline_laststart;
?>
<br>
						<b>Last finish</b> <?php 
echo $pipeline_lastfinish;
?>
<br>
						<b>Last check</b> <?php 
echo $pipeline_lastcheck;
?>
<br>
					</td>
				</tr>
			</table>
		</fieldset>
		<br>
		<fieldset style="border: 3px solid #999; border-radius:5px">
			<legend style="background-color: #3B5998; color:white; padding:5px 10px; border-radius:5px"> <b><?php 
echo $formtitle;
?>
</b> version <?php 
echo $version;
?>
 </legend>
		<table>
			<tr>
				<td style="padding-right:40px">
					<table class="entrytable" style="border:0px">
						<form method="post" action="pipelines.php">
						<input type="hidden" name="action" value="<?php 
echo $formaction;
?>
">
						<input type="hidden" name="id" value="<?php 
echo $id;
?>
">
						<tr>
							<td class="label" valign="top">Title</td>
							<td valign="top">
								<input type="text" name="pipelinetitle" value="<?php 
echo $title;
?>
" maxlength="50" size="60" onKeyPress="return AlphaNumeric(event)" <? if ($type == "edit") { echo "readonly style='background-color: #EEE; border: 1px solid gray; color: #888'"; } ?>>
							</td>
						</tr>
						<tr>
							<td class="label" valign="top">Description</td>
							<td valign="top"><input type="text" <?php 
echo $disabled;
?>
 name="pipelinedesc" value="<?php 
echo $desc;
?>
" size="60"></td>
						</tr>
						<tr>
							<td class="label" valign="top">Stats level</td>
							<td valign="top">
								<!--<input type="radio" name="level" id="level0" value="0" <?php 
echo $disabled;
?>
 <? if ($level == 0) echo "checked"; ?>>One-shot <span class="tiny">Runs only once. No associated data</span><br>-->
								<input type="radio" name="level" id="level1" value="1" <?php 
echo $disabled;
?>
 <? if ($level == 1) echo "checked"; ?>>First <span class="tiny">subject level</span><br>
								<input type="radio" name="level" id="level2" value="2" <?php 
echo $disabled;
?>
 <? if ($level == 2) echo "checked"; ?>>Second <span class="tiny">group level</span><br>
							</td>
						</tr>
						<tr>
							<td class="label" valign="top">Group</td>
							<td valign="top">
								<input type="text" name="pipelinegroup" list="grouplist" <?php 
echo $disabled;
?>
 value="<?php 
echo $pipelinegroup;
?>
" maxlength="255" size="60">
							</td>
							<datalist id="grouplist">
								<?
									$sqlstring = "select distinct(pipeline_group) 'pipeline_group' from pipelines";
									$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
									while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
										$pgroup = $row['pipeline_group'];
										echo "<option value='$pgroup'>";
									}
								?>
							</datalist>
						</tr>
						<tr>
							<td class="label" valign="top">Directory <img src="images/help.gif" title="<b>Directory</b><br><br>A directory called <b>Title</b> (same name as this analysis) will be created inside this directory and will contain the analyses for this pipeline.<br><br>If blank, the analyses for this pipeline will be written to the default pipeline directory: <span style='color: #E8FFFF'>[<?php 
echo $GLOBALS['cfg']['analysisdir'];
?>
]</span>"></td>
							<td valign="top">
								<input type="text" name="pipelinedirectory" <?php 
echo $disabled;
?>
 value="<?php 
echo $directory;
?>
" maxlength="255" size="60" <? if ($type == "edit") { echo "readonly style='background-color: #EEE; border: 1px solid gray; color: #888'"; } ?> >
							</td>
						</tr>
						<tr class="level1">
							<td class="label" valign="top">Concurrent processes <img src="images/help.gif" title="<b>Concurrent processes</b><br><br>This is the number of concurrent jobs allowed to be submitted to the cluster at a time. This number is separate from the number of slots available in the cluster queue, which specified in the grid engine setup"></td>
							<td valign="top"><input type="number" name="pipelinenumproc" <?php 
echo $disabled;
?>
 value="<?php 
echo $numproc;
?>
" min="1" max="350"></td>
						</tr>
						<tr>
							<td class="label" valign="top">Submit host <img src="images/help.gif" title="<b>Submit host</b><br><br>The hostname of the SGE head node to submit to. If blank, the default submit host is used (<?php 
echo $GLOBALS['cfg']['clustersubmithost'];
?>
)"></td>
							<td valign="top"><input type="text" name="pipelinesubmithost" <?php 
echo $disabled;
?>
 value="<?php 
echo $submithost;
?>
"></td>
						</tr>
						<tr>
							<td class="label" valign="top">Queue name <img src="images/help.gif" title="<b>Queue name</b><br><br>The sun grid (SGE) queue to submit to"></td>
							<td valign="top"><input type="text" name="pipelinequeue" <?php 
echo $disabled;
?>
 value="<?php 
echo $queue;
?>
" required></td>
						</tr>
						<tr>
							<td class="label" valign="top">Use temporary directory <img src="images/help.gif" title="<b>Use tmp directory</b><br><br>This option will copy all data into the temporary directory first, process it there, and copy it back to its final location"></td>
							<td valign="top"><input type="checkbox" name="pipelineusetmpdir" <?php 
echo $disabled;
?>
 value="1" <? if ($usetmpdir == "1") { echo "checked"; } ?>> <input type="text" name="pipelinetmpdir" <?php 
echo $disabled;
?>
 value="<?php 
echo $tmpdir;
?>
" size="56"><br>
							<span class="tiny">Usually <tt>/tmp</tt>. Check with your sysadmin</span></td>
						</tr>
						<!--<tr class="level1">
							<td class="label" valign="top">Data download</td>
							<td valign="top">
								<input type="radio" name="dataand" value="0" <?php 
echo $disabled;
?>
 <? if ($dataand == 0) echo "checked"; ?>>or <span class="tiny">download any of the data specified below</span><br>
								<input type="radio" name="dataand" value="1" <?php 
echo $disabled;
?>
 <? if ($dataand == 1) echo "checked"; ?>>and <span class="tiny">only download data if all of the series specified exist in the study</span><br>
								<input type="radio" name="dataand" value="-1" <?php 
echo $disabled;
?>
 <? if ($dataand == -1) echo "checked"; ?>>none <span class="tiny">no data download. only use if the pipeline has a dependency</span>
							</td>
						</tr>-->
						<!--<tr class="level1">
							<td class="label" valign="top">Remove downloaded data?</td>
							<td valign="top" title="<b>Remove downloaded data</b><br><br>Deletes all downloaded (raw) data after analysis is complete. Assumes that the analsysis will have copied or converted the necessary data and no longer needs it"><input type="checkbox" name="pipelineremovedata" value="1" <? if ($remove) { echo "checked"; } ?>></td>
						</tr>-->
						<tr>
							<td class="label" valign="top">Successful files <img src="images/help.gif" title="<b>Successful files</b><br><br>The analysis is marked as successful if ALL of the files specified exist at the end of the analysis. If left blank, the analysis will always be marked as successful"></td>
							<td valign="top"><textarea name="completefiles" <?php 
echo $disabled;
?>
 rows="5" cols="60"><?php 
echo $completefiles;
?>
</textarea><br>
							<span class="tiny">Comma seperated list of files (relative paths)</span></td>
						</tr>
						<tr>
							<td class="label" valign="top">Results script <img src="images/help.gif" title="<b>Results script</b><br><br>This script will be executed last and can be re-run separate from the analysis pipeline. The results script would often be used to create thumbnails of images and parse text files, and reinsert those results back into the database. The same pipeline variables available in the script command section below are available here to be passed as parameters to the results script"></td>
							<td valign="top">
								<textarea name="pipelineresultsscript" rows="3" cols="60"><?php 
echo $resultscript;
?>
</textarea>
							</td>
						</tr>
						<tr class="level1">
							<td class="label" valign="top">Pipeline dependency<br>
							</td>
							<td valign="top">
								<table class="entrytable">
									<tr>
										<td valign="top" align="right" style="font-size:10pt; font-weight:bold;color: #555;">Dependency</td>
										<td valign="top">
											<select name="dependency[]" <?php 
echo $disabled;
?>
 multiple="multiple" size="7">
												<option value="">(No dependency)</option>
												<?
													$sqlstring = "select * from pipelines order by pipeline_name";
													$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
													while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
														$d_name = $row['pipeline_name'];
														$d_id = $row['pipeline_id'];
														$d_ver = $row['pipeline_version'];
														
														/* get the number of analyses in the pipeline */
														$sqlstringA = "select count(*) 'count' from analysis where pipeline_id = $d_id and analysis_status = 'complete'";
														$resultA = MySQLiQuery($sqlstringA,__FILE__,__LINE__);
														$rowA = mysqli_fetch_array($resultA, MYSQLI_ASSOC);
														$nummembers = $rowA['count'];
														
														if (in_array($d_id, explode(",",$dependency))) { $selected = "selected"; }
														//if ($d_id == $dependency) { $selected = "selected"; }
														else { $selected = ""; }
														if ($id != $d_id) {
														?>
														<option value="<?php 
echo $d_id;
?>
" <?php 
echo $selected;
?>
><?php 
echo $d_name;
?>
  [<?php 
echo $nummembers;
?>
]</option>
														<?
														}
													}
												?>
											</select>
										</td>
									</tr>
									<tr>
										<td valign="top" align="right" style="font-size:10pt; font-weight:bold;color: #555;">Criteria</td>
										<td valign="top">
											<input type="radio" name="deplevel" value="study" <?php 
echo $disabled;
?>
 <? if (($deplevel == "study") || ($deplevel == "")) { echo "checked"; } ?>> study <span class="tiny">use dependencies from same study</span><br>
											<input type="radio" name="deplevel" value="subject" <?php 
echo $disabled;
?>
 <? if ($deplevel == "subject") { echo "checked"; } ?>> subject <span class="tiny">use dependencies from same subject (other studies)</span>
										</td>
									</tr>
									<tr>
										<td valign="top" align="right" style="font-size:10pt; font-weight:bold;color: #555;">Directory</td>
										<td valign="top">
											<input type="radio" name="depdir" value="root" <?php 
echo $disabled;
?>
 <? if (($depdir == "root") || ($depdir == "")) { echo "checked"; } ?>> root directory <img src="images/help.gif" title="copies all files into the analysis root directory <code>{analysisrootdir}/*</code>"><br>
											<input type="radio" name="depdir" value="subdir" <?php 
echo $disabled;
?>
 <? if ($depdir == "subdir") { echo "checked"; } ?>> sub-directory <img src="images/help.gif" title="copies dependency into a subdirectory of the analysis <code>{analysisrootdir}/<i>DependencyName</i>/*</code>">
										</td>
									</tr>
									<tr>
										<td valign="top" align="right" style="font-size:10pt; font-weight:bold;color: #555;">Linking type</td>
										<td valign="top">
											<input type="radio" name="deplinktype" value="hardlink" <?php 
echo $disabled;
?>
 <? if (($deplinktype == "hardlink") || ($deplinktype == "")) { echo "checked"; } ?>> hard link<br>
											<input type="radio" name="deplinktype" value="softlink" <?php 
echo $disabled;
?>
 <? if ($deplinktype == "softlink") { echo "checked"; } ?>> soft link<br>
											<input type="radio" name="deplinktype" value="regularcopy" <?php 
echo $disabled;
?>
 <? if ($deplinktype == "regularcopy") { echo "checked"; } ?>> Regular copy<br>
										</td>
									</tr>
								</table>
							</td>
						</tr>
						<tr class="level1">
							<td class="label" valign="top">Group(s) <img src="images/help.gif" title="Perform this analysis ONLY<br>on the studies in the specified groups"><br>
							<span class="level2" style="color:darkred; font-size:8pt; font-weight:normal"> Second level must have<br> at least one group.<br>Group(s) must be identical to<br>first level <b>dependency's</b> group(s)</span>
							</td>
							<td valign="top">
								<select name="groupid[]" <?php 
echo $disabled;
?>
 multiple="multiple" size="7">
									<option value="">(No group)</option>
									<?
										$sqlstring = "select * from groups where group_type = 'study' order by group_name";
										$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
										while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
											$g_name = $row['group_name'];
											$g_id = $row['group_id'];
											
											/* get the number of members of the group */
											$sqlstringA = "select count(*) 'count' from group_data where group_id = $g_id";
											$resultA = MySQLiQuery($sqlstringA,__FILE__,__LINE__);
											$rowA = mysqli_fetch_array($resultA, MYSQLI_ASSOC);
											$nummembers = $rowA['count'];
											
											if (in_array($g_id, explode(",",$groupid))) { $selected = "selected"; }
											else { $selected = ""; }
											?>
											<option value="<?php 
echo $g_id;
?>
" <?php 
echo $selected;
?>
><?php 
echo $g_name;
?>
  [<?php 
echo $nummembers;
?>
]</option>
											<?
										}
									?>
								</select>
							</td>
						</tr>
						<tr>
							<td class="label" valign="top">Notes<br><span class="tiny">Any information about the analysis</span></td>
							<td valign="top"><textarea name="pipelinenotes" <?php 
echo $disabled;
?>
 rows="8" cols="60"><?php 
echo $pipelinenotes;
?>
</textarea></td>
						</tr>
						<tr>
							<td class="label" valign="top">Hidden?</td>
							<td valign="top" title="<b>Hidden</b><br><br>Useful to hide a pipeline from the main pipeline list. The pipeline still exists, but it won't show up"><input type="checkbox" name="pipelineishidden" value="1" <? if ($ishidden) { echo "checked"; } ?>></td>
						</tr>
						<tr>
							<td colspan="2" align="center">
								<br>
								<input type="submit" <?php 
echo $disabled;
?>
 value="<?php 
echo $submitbuttonlabel;
?>
">
							</td>
						</tr>
						</form>
					</table>
				</td>
				<? if ($formaction == "update") { ?>
				<td valign="top">
					<?
						/* gather statistics about the analyses */
						$sqlstring = "select sum(timestampdiff(second, analysis_clusterstartdate, analysis_clusterenddate)) 'cluster_time' from analysis a left join studies b on a.study_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.pipeline_id = $id and analysis_status = 'complete'";
						$result = MySQLQuery($sqlstring,__FILE__,__LINE__);
						$row = mysql_fetch_array($result, MYSQL_ASSOC);
						$totaltime = $row['cluster_time'];
						$totaltime = number_format(($totaltime/60/60),2);
						//$parts = explode(':', $totaltime);
						//$totaltime = $parts[0]. "h " . $parts[1] . "m " . $parts[2] . "s";
						
						$sqlstring = "select count(*) 'numcomplete' from analysis a left join studies b on a.study_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.pipeline_id = $id and analysis_status = 'complete'";
						$result = MySQLQuery($sqlstring,__FILE__,__LINE__);
						$row = mysql_fetch_array($result, MYSQL_ASSOC);
						$numcomplete = $row['numcomplete'];
						
						$sqlstring = "select count(*) 'numprocessing' from analysis a left join studies b on a.study_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.pipeline_id = $id and analysis_status = 'processing'";
						$result = MySQLQuery($sqlstring,__FILE__,__LINE__);
						$row = mysql_fetch_array($result, MYSQL_ASSOC);
						$numprocessing = $row['numprocessing'];
						
						$sqlstring = "select count(*) 'numpending' from analysis a left join studies b on a.study_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.pipeline_id = $id and analysis_status = 'pending'";
						$result = MySQLQuery($sqlstring,__FILE__,__LINE__);
						$row = mysql_fetch_array($result, MYSQL_ASSOC);
						$numpending = $row['numpending'];
						
						/* get mean processing times */
						$sqlstring = "select analysis_id, timestampdiff(second, analysis_startdate, analysis_enddate) 'analysis_time', timestampdiff(second, analysis_clusterstartdate, analysis_clusterenddate) 'cluster_time' from analysis a left join studies b on a.study_id = b.study_id left join enrollment c on b.enrollment_id = c.enrollment_id left join subjects d on c.subject_id = d.subject_id where a.pipeline_id = $id and analysis_status <> ''";
						//PrintSQL($sqlstring);
						$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
						while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
							//$analysis_id = $row['analysis_id'];
							$analysistimes[] = $row['analysis_time'];
							$clustertimes[] = $row['cluster_time'];
						}
						if (count($clustertimes) == 0) {
							$clustertimes[] = 0;
						}
						if (count($analysistimes) == 0) {
							$analysistimes[] = 0;
						}
						
						?>
						<table class="twocoltable">
							<tr>
								<th colspan="2">Analysis Statistics</th>
							</tr>
							<tr>
								<td>Complete<br>Total analysis time</td>
								<td><a href="pipelines.php?action=viewanalyses&id=<?php 
echo $id;
?>
"><?php 
echo $numcomplete;
?>
</a><br><?php 
echo $totaltime;
?>
 hr</td>
							</tr>
							<tr>
								<td>Processing</td>
								<td><?php 
echo $numprocessing;
?>
</td>
							</tr>
							<tr>
								<td>Pending</td>
								<td><?php 
echo $numpending;
?>
</td>
							</tr>
							<tr>
								<td>Mean Cluster time</td>
								<td><?php 
echo number_format(mean($clustertimes) / 60 / 60, 2);
?>
 hr</td>
							</tr>
							<tr>
								<td>Median Cluster time</td>
								<td><?php 
echo number_format(median($clustertimes) / 60 / 60, 2);
?>
 hr</td>
							</tr>
							<tr>
								<td>Min/Max Cluster time</td>
								<td><?php 
echo number_format(min($clustertimes) / 60 / 60, 2);
?>
 - <?php 
echo number_format(max($clustertimes) / 60 / 60, 2);
?>
 hr</td>
							</tr>
							<tr>
								<td>Mean Setup time</td>
								<td><?php 
echo number_format(mean($analysistimes), 1);
?>
 sec</td>
							</tr>
							<tr>
								<td>Median Setup time</td>
								<td><?php 
echo number_format(median($analysistimes), 1);
?>
 sec</td>
							<tr>
							</tr>
								<td>Min/Max Setup time</td>
								<td><?php 
echo number_format(min($analysistimes), 1);
?>
 - <?php 
echo number_format(max($analysistimes), 1);
?>
 sec</td>
							</tr>
						</table>
					<br>
					<script>
						function GetNewPipelineName(){
							var newname = prompt("Please enter a name for the new pipeline","<?php 
echo $title;
?>
");
							if (newname != null){
							  $("#newname").attr("value", newname);
							  document.copypipeline.submit();
						   }
						}
					</script>

					<span style="color:#555; font-size:11pt; font-weight: bold">Where is my data?</span><br><br>
					<span style="background-color: #ddd; padding:5px; font-family: monospace; border-radius:3px">
					<? if ($directory != "") { echo $directory; } else { echo $GLOBALS['cfg']['analysisdir']; } ?>/<i>UID</i>/<i>StudyNum</i>/<?php 
echo $title;
?>
					</span>
					<br><br>
					<details>
						<summary style="color: #3B5998"> Pipeline Operations </summary>
						<br>
						<a href="pipelines.php?action=viewpipeline&id=<?php 
echo $id;
?>
"><img src="images/printer16.png" border="0"> Print view</a> <span class="tiny">(and previous pipeline versions)</span><br><br>
						<a href="pipelines.php?action=viewanalyses&id=<?php 
echo $id;
?>
"><img src="images/preview.gif"> View analyses</a><br><br>
						<a href="pipelines.php?action=viewfailedanalyses&id=<?php 
echo $id;
?>
" title="View all imaging studies which did not meet the data criteria, and therefore the pipeline did not attempt to run the analysis"><img src="images/preview.gif"> View ignored studies</a><br><br>
						
						<form action="pipelines.php" method="post" name="copypipeline">
						<input type="hidden" name="action" value="copy">
						<input type="hidden" name="id" value="<?php 
echo $id;
?>
">
						<input type="hidden" name="newname" id="newname" value="<?php 
echo $id;
?>
">
						<img src="images/copy16.gif"> <input type="button" value="Copy to new pipeline..." onClick="GetNewPipelineName();"><br><br>
						</form>
						<? if (!$readonly) { ?>
						Change pipeline owner:
						<form>
						<input type="hidden" name="action" value="changeowner">
						<input type="hidden" name="id" value="<?php 
echo $id;
?>
">
						<select name="newuserid">
							<?
								$sqlstring="select * from users where user_enabled = 1 order by username";
								$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
								while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
									$userid = $row['user_id'];
									$username = $row['username'];
									$userfullname = $row['user_fullname'];
									if ($userfullname != "") {
										$userfullname = "[$userfullname]";
									}
									?><option value="<?php 
echo $userid;
?>
"><?php 
echo $username;
?>
 <?php 
echo $userfullname;
?>
</option><?
								}
							?>
						</select>
						<input type="submit" value="Change">
						</form>
						<a href="pipelines.php?action=detach$id=<?php 
echo $id;
?>
" onclick="return confirm('Are you sure you want to completely detach this pipeline?')" title="This will completely inactivate the pipeline and remove all analyses from the pipeline control. Since the data will no longer be under pipeline control, all analysis results will be deleted. All analysis data will be moved to the directory you specify"><img src="images/disconnect16.png"> Detach entire pipeline</a><br><br>
						<a href="pipelines.php?action=resetanalyses&id=<?php 
echo $id;
?>
" onclick="return confirm('Are you sure you want to reset the analyses for this pipeline?')" title="This will remove any entries in the database for studies which were not analyzed. If you change your data specification, you will want to reset the analyses. This option does not remove existing analyses, it only removes the flag set for studies that indicates the study has been checked for the specified data"><img src="images/reset16.png"> Reprocess ignored studies</a><br><br>
						<a href="pipelines.php?action=delete&id=<?php 
echo $id;
?>
" onclick="return confirm('Are you sure you want to delete this pipeline?')"><img src="images/delete16.png"> Delete this pipeline</a>
						<? } ?>
					</details>
				</td>
					<?
				}
			?>
			</tr>
		</table>
		</fieldset>

		<?
		if ($type == "edit") {
		?>
		<br><br>
		
		<script>
			function addParam(value,id){
				var TheTextBox = document.getElementById(id);
				TheTextBox.value = TheTextBox.value + ' ' + value;
			}
		</script>

		
		<fieldset style="border: 3px solid #999; border-radius:5px">
			<legend style="background-color: #3B5998; color:white; padding:5px 10px; border-radius:5px"> Pipeline specification </legend>
			
		<form method="post" action="pipelines.php" name="stepsform" id="stepsform">
		<input type="hidden" name="action" value="updatepipelinedef">
		<input type="hidden" name="id" value="<?php 
echo $id;
?>
">
		<? if (($level == 1) || (($level == 2) && ($dependency == ''))) { ?>
		<br>
		<style>
			td.dataheader { padding: 5px; border-bottom: 2px solid #999; background-color: #eee; text-align: center }
		</style>
		<div style="text-align:left; font-size:12pt; font-weight: bold; color:#214282;" class="level1">Data</div>
		<br>
		<table class="level1" cellspacing="0" cellpadding="0">
			<tr style="color:#444; font-size:10pt;">
				<td class="dataheader"><b>Enabled</b></td>
				<td class="dataheader"><b>Optional</b></td>
				<td class="dataheader"><b>Order</b></td>
				<td class="dataheader"><b>Protocol</b></td>
				<td class="dataheader"><b>Modality</b></td>
				<td class="dataheader"><b>Where's the data coming from?</b> <img src="images/help.gif" title="<b>Data Source</b><br>All analyses are run off of the study level. If you want data from this subject, but the data was collected in a different study, select the Subject data level. For example, the subject has been scanned on three different dates, but only one of them has"></td>
				<td class="dataheader"><b>Subject linkage</b> <img src="images/help.gif" title="<b>Data Level</b><br>Only use this option if your data is coming from the subject level"></td>
			</tr>
		<?
		$neworder = 1;
		/* display all other rows, sorted by order */
		$sqlstring = "select * from pipeline_data_def where pipeline_id = $id and pipeline_version = $version order by pdd_order + 0";
		$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
		while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
			$pipelinedatadef_id = $row['pipelinedatadef_id'];
			$dd_order = $row['pdd_order'];
			$dd_seriescriteria = $row['pdd_seriescriteria'];
			$dd_protocol = $row['pdd_protocol'];
			$dd_modality = $row['pdd_modality'];
			$dd_dataformat = $row['pdd_dataformat'];
			$dd_imagetype = $row['pdd_imagetype'];
			$dd_gzip = $row['pdd_gzip'];
			$dd_location = $row['pdd_location'];
			$dd_useseries = $row['pdd_useseries'];
			$dd_preserveseries = $row['pdd_preserveseries'];
			$dd_behformat = $row['pdd_behformat'];
			$dd_behdir = $row['pdd_behdir'];
			$dd_enabled = $row['pdd_enabled'];
			$dd_assoctype = $row['pdd_assoctype'];
			$dd_optional = $row['pdd_optional'];
			$dd_datalevel = $row['pdd_level'];
			$dd_numimagescriteria = $row['pdd_numimagescriteria'];
			
			//PrintVariable($row);
			?>
			<script>
				$(document).ready(function() {
					$('.row<?php 
echo $neworder;
?>
').mouseover(function() {
						$('.row<?php 
echo $neworder;
?>
').css('background-color','#eee');
					})
					.mouseout(function() {
						$('.row<?php 
echo $neworder;
?>
').css('background-color','');
					});
				});
			</script>
			<tr class="row<?php 
echo $neworder;
?>
">
				<td width="10" valign="top" style="padding: 5px;" align="center">
					<input class="small" type="checkbox" name="dd_enabled[<?php 
echo $neworder;
?>
]" value="1" <? if ($dd_enabled) {echo "checked";} ?>>
				</td>
				<td valign="top" style="padding: 5px" align="center">
					<input type="checkbox" name="dd_optional[<?php 
echo $neworder;
?>
]" value="1" <? if ($dd_optional) { echo "checked"; } ?>>
				</td>
				<td style="padding: 5px" valign="top">
					<input class="small" type="text" name="dd_order[<?php 
echo $neworder;
?>
]" size="2" maxlength="3" value="<?php 
echo $neworder;
?>
">
				</td>
				<td valign="top" style="padding: 5px">
					<input class="small" type="text" name="dd_protocol[<?php 
echo $neworder;
?>
]" size="50" value='<?php 
echo $dd_protocol;
?>
' title='Enter exact protocol name(s). Use quotes if entering a protocol with spaces or entering more than one protocol: "Task1" "Task 2" "Etc". Use multiple protocol names ONLY if you do not expect the protocols to occur in the same study'>
				</td>
				<td id="row<?php 
echo $neworder;
?>
" valign="top" style="padding: 5px">
					<select class="small" name="dd_modality[<?php 
echo $neworder;
?>
]">
						<option value="">(Select modality)</option>
					<?
						$sqlstringA = "select * from modalities order by mod_desc";
						$resultA = MySQLiQuery($sqlstringA,__FILE__,__LINE__);
						while ($rowA = mysqli_fetch_array($resultA, MYSQLI_ASSOC)) {
							$mod_code = $rowA['mod_code'];
							$mod_desc = $rowA['mod_desc'];
							
							/* check if the modality table exists */
							$sqlstring2 = "show tables from " . $GLOBALS['cfg']['mysqldatabase'] . " like '" . strtolower($mod_code) . "_series'";
							//echo $sqlstring2;
							$result2 = MySQLiQuery($sqlstring2,__FILE__,__LINE__);
							if (mysqli_num_rows($result2) > 0) {
							
								/* if the table does exist, allow the user to search on it */
								if ($mod_code == $dd_modality) {
									$selected = "selected";
								}
								else {
									$selected = "";
								}
								?>
								<option value="<?php 
echo $mod_code;
?>
" <?php 
echo $selected;
?>
><?php 
echo $mod_code;
?>
</option>
								<?
							}
						}
					?>
					</select>
				</td>
				<td valign="top" style="font-size:8pt; padding: 5px" align="left">
					<select name="dd_datalevel[<?php 
echo $neworder;
?>
]">
						<option value="">(select data level)
						<option value="study" <? if (($dd_datalevel == "study") || ($dd_datalevel == "")) { echo "selected"; } ?>>Study
						<option value="subject" <? if ($dd_datalevel == "subject") { echo "selected"; } ?>>Subject
					</select>
				</td>
				<td valign="top" style="font-size:8pt; padding: 5px" align="left">
					<select name="dd_studyassoc[<?php 
echo $neworder;
?>
]">
						<option value="">(select study link)
						<option value="nearestintime" <? if (($dd_assoctype == "nearestintime") || ($dd_assoctype == "")) { echo "selected"; } ?>>Nearest in time
						<option value="samestudytype" <? if ($dd_assoctype == "samestudytype") { echo "selected"; } ?>>Same study type
					</select>
				</td>
			</tr>
			<tr class="row<?php 
echo $neworder;
?>
">
				<td valign="top" colspan="7" style="padding-left:25px">
					<details class="level1" style="padding:0px;margin:0px">
						<summary style="padding:0px; font-size:9pt">Options</summary>
						<table class="entrytable" style="background-color: #EEE; border-radius:4px; border: 1px solid #999" width="100%">
							<tr>
								<td class="label">Data format</td>
								<td>
									<select class="small" name="dd_dataformat[<?php 
echo $neworder;
?>
]">
										<option value="native" <? if ($dd_dataformat == "native") { echo "selected"; } ?>>Native</option>
										<option value="dicom" <? if ($dd_dataformat == "dicom") { echo "selected"; } ?>>DICOM</option>
										<option value="nifti3d" <? if ($dd_dataformat == "nifti3d") { echo "selected"; } ?>>Nifti 3D</option>
										<option value="nifti4d" <? if ($dd_dataformat == "nifti4d") { echo "selected"; } ?>>Nifti 4D</option>
										<option value="analyze3d" <? if ($dd_dataformat == "analyze3d") { echo "selected"; } ?>>Analyze 3D</option>
										<option value="analyze4d" <? if ($dd_dataformat == "analyze4d") { echo "selected"; } ?>>Analyze 4D</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="label">Image type</td>
								<td><input class="small" type="text" name="dd_imagetype[<?php 
echo $neworder;
?>
]" size="30" value="<?php 
echo $dd_imagetype;
?>
"></td>
							</tr>
							<tr>
								<td class="label">g-zip</td>
								<td><input class="small" type="checkbox" name="dd_gzip[<?php 
echo $neworder;
?>
]" value="1" <? if ($dd_gzip) {echo "checked";} ?>></td>
							</tr>
							<tr>
								<td class="label">Directory<br><span class="tiny">Relative to analysis root</span></td>
								<td title="<b>Tip:</b> choose a directory called 'data/<i>taskname</i>'. If converting data or putting into a new directory structure, this data directory can be used as a staging area and can then be deleted later in your script"><input class="small" type="text" name="dd_location[<?php 
echo $neworder;
?>
]" size="30" value="<?php 
echo $dd_location;
?>
"></td>
							</tr>
							<tr>
								<td class="label">Criteria <img src="images/help.gif" title="<b>All</b> - All matching series will be downloaded<br><b>First</b> - Only the lowest numbered series will be downloaded<br><b>Last</b> - Only the highest numbered series will be downloaded<br><b>Largest</b> - Only one series with the most number of volumes or slices will be downloaded<br><b>Smallest</b> - Only one series with the least number of volumes or slices will be downloaded"></td>
								<td>
									<select class="small" name="dd_seriescriteria[<?php 
echo $neworder;
?>
]">
										<option value="all" <? if ($dd_seriescriteria == "all") { echo "selected"; } ?>>All</option>
										<option value="first" <? if ($dd_seriescriteria == "first") { echo "selected"; } ?>>First</option>
										<option value="last" <? if ($dd_seriescriteria == "last") { echo "selected"; } ?>>Last</option>
										<option value="largestsize" <? if ($dd_seriescriteria == "largestsize") { echo "selected"; } ?>>Largest</option>
										<option value="smallestsize" <? if ($dd_seriescriteria == "smallestsize") { echo "selected"; } ?>>Smallest</option>
										<option value="usesizecriteria" <? if ($dd_seriescriteria == "usesizecriteria") { echo "selected"; } ?>>Use size criteria below</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="label">Number of BOLD reps <img src="images/help.gif" title="<b>Must be an integer or a criteria:</b><ul><li><i>N</i> (exactly N)<li>> <i>N</i> (greater than)<li>>= <i>N</i> (greater than or equal to)<li>< <i>N</i> (less than)<li><= <i>N</i> (less than or equal to)<li>~ <i>N</i> (not)</ul>"></td>
								<td><input type="text" name="dd_numboldreps[<?php 
echo $neworder;
?>
]" value="<?php 
echo $dd_numboldreps;
?>
"></td>
							</tr>
							<tr>
								<td class="label">Use series directories</td>
								<td title="<b>Tip:</b> If you plan to download multiple series with the same name, you will want to use series directories. This option will place each series into its own directory (data/task/1, data/task/2, etc)"><input class="small" type="checkbox" name="dd_useseriesdirs[<?php 
echo $neworder;
?>
]" value="1" <? if ($dd_useseries) {echo "checked";} ?>></td>
							</tr>
							<tr>
								<td class="label">Preserve series numbers <img src="images/help.gif" title="If data is placed in a series directory, check this box to preserve the original series number. Otherwise the series number directories will be sequential starting at 1, regardless of the orignal series number"></td>
								<td><input class="small" type="checkbox" name="dd_preserveseries[<?php 
echo $neworder;
?>
]" value="1" <? if ($dd_preserveseries) {echo "checked";} ?>></td>
							</tr>
							<tr>
								<td class="label">Behavioral data directory format</td>
								<td>
									<select class="small" name="dd_behformat[<?php 
echo $neworder;
?>
]">
										<option value="behnone" <? if ($dd_behformat == "behnone") { echo "selected"; } ?>>Don't download behavioral data</option>
										<option value="behroot" <? if ($dd_behformat == "behroot") { echo "selected"; } ?>>Place in root (file.log)</option>
										<option value="behrootdir" <? if ($dd_behformat == "behrootdir") { echo "selected"; } ?>>Place in directory in root (beh/file.log)</option>
										<option value="behseries" <? if ($dd_behformat == "behseries") { echo "selected"; } ?>>Place in series (2/file.log)</option>
										<option value="behseriesdir" <? if ($dd_behformat == "behseriesdir") { echo "selected"; } ?>>Place in directory in series (2/beh/file.log)</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="label">Behavioral data directory name</td>
								<td><input class="small" type="text" name="dd_behdir[<?php 
echo $neworder;
?>
]" value="<?php 
echo $dd_behdir;
?>
"></td>
							</tr>
						</table>
						<br>
					</details>
				</td>
			</tr>
			<?
			$neworder++;
		}
		for ($ii=0;$ii<5;$ii++) {
		?>
			<script>
				$(document).ready(function() {
					$('.row<?php 
echo $neworder;
?>
').mouseover(function() {
						$('.row<?php 
echo $neworder;
?>
').css('background-color','#eee');
					})
					.mouseout(function() {
						$('.row<?php 
echo $neworder;
?>
').css('background-color','');
					});
				});
			</script>
			<tr class="row<?php 
echo $neworder;
?>
">
				<td width="10" valign="top" style="padding: 5px;" align="center">
					<input class="small" type="checkbox" name="dd_enabled[<?php 
echo $neworder;
?>
]" value="1">
				</td>
				<td valign="top" style="padding: 5px" align="center">
					<input type="checkbox" name="dd_optional[<?php 
echo $neworder;
?>
]" value="1">
				</td>
				<td style="padding: 5px" valign="top">
					<input class="small" type="text" name="dd_order[<?php 
echo $neworder;
?>
]" size="2" maxlength="3" value="<?php 
echo $neworder;
?>
">
				</td>
				<td valign="top" style="padding: 5px">
					<input class="small" type="text" name="dd_protocol[<?php 
echo $neworder;
?>
]" size="50" title='Enter exact protocol name(s). Use quotes if entering a protocol with spaces or entering more than one protocol: "Task1" "Task 2" "Etc". Use multiple protocol names ONLY if you do not expect the protocols to occur in the same study'>
				</td>
				<td valign="top" style="padding: 5px">
					<select class="small" name="dd_modality[<?php 
echo $neworder;
?>
]">
						<option value="">(Select modality)</option>
					<?
						$sqlstringA = "select * from modalities order by mod_desc";
						$resultA = MySQLiQuery($sqlstringA,__FILE__,__LINE__);
						while ($rowA = mysqli_fetch_array($resultA, MYSQLI_ASSOC)) {
							$mod_code = $rowA['mod_code'];
							$mod_desc = $rowA['mod_desc'];
							
							/* check if the modality table exists */
							$sqlstring2 = "show tables from " . $GLOBALS['cfg']['mysqldatabase'] . " like '" . strtolower($mod_code) . "_series'";
							//echo $sqlstring2;
							$result2 = MySQLiQuery($sqlstring2,__FILE__,__LINE__);
							if (mysqli_num_rows($result2) > 0) {
								?>
								<option value="<?php 
echo $mod_code;
?>
"><?php 
echo $mod_code;
?>
</option>
								<?
							}
						}
					?>
					</select>
				</td>
				<td valign="top" style="font-size:8pt; padding: 5px" align="left">
					<select name="dd_datalevel[<?php 
echo $neworder;
?>
]">
						<option value="">(select data level)
						<option value="study" selected>Study
						<option value="subject">Subject
					</select>
				</td>
				<td valign="top" style="font-size:8pt; padding: 5px" align="left">
					<select name="dd_studyassoc[<?php 
echo $neworder;
?>
]">
						<option value="">(select study link)
						<option value="nearestintime" selected>Nearest in time
						<option value="samestudytype">Same study type
					</select>
				</td>
			</tr>
			<tr class="row<?php 
echo $neworder;
?>
">
				<td valign="top" colspan="7" style="padding-left:25px">
					<details class="level1" style="padding:0px;margin:0px">
						<summary style="padding:0px; font-size:9pt">Options</summary>
						<table class="entrytable" style="background-color: #EEE; border-radius:4px; border: 1px solid #999" width="100%">
							<tr>
								<td class="label">Data format</td>
								<td>
									<select class="small" name="dd_dataformat[<?php 
echo $neworder;
?>
]">
										<option value="native" selected>Native</option>
										<option value="dicom">DICOM</option>
										<option value="nifti3d">Nifti 3D</option>
										<option value="nifti4d">Nifti 4D</option>
										<option value="analyze3d">Analyze 3D</option>
										<option value="analyze4d">Analyze 4D</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="label">Image type</td>
								<td><input class="small" type="text" name="dd_imagetype[<?php 
echo $neworder;
?>
]" size="30"></td>
							</tr>
							<tr>
								<td class="label">g-zip</td>
								<td><input class="small" type="checkbox" name="dd_gzip[<?php 
echo $neworder;
?>
]" value="1"></td>
							</tr>
							<tr>
								<td class="label">Directory<br><span class="tiny">Relative to analysis root</span></td>
								<td title="<b>Tip:</b> choose a directory called 'data/<i>taskname</i>'. If converting data or putting into a new directory structure, this data directory can be used as a staging area and can then be deleted later in your script"><input class="small" type="text" name="dd_location[<?php 
echo $neworder;
?>
]" size="30"></td>
							</tr>
							<tr>
								<td class="label">Criteria <img src="images/help.gif" title="<b>All</b> - All matching series will be downloaded<br><b>First</b> - Only the lowest numbered series will be downloaded<br><b>Last</b> - Only the highest numbered series will be downloaded<br><b>Largest</b> - Only one series with the most number of volumes or slices will be downloaded<br><b>Smallest</b> - Only one series with the least number of volumes or slices will be downloaded"></td>
								<td>
									<select class="small" name="dd_seriescriteria[<?php 
echo $neworder;
?>
]">
										<option value="all" selected>All</option>
										<option value="first">First</option>
										<option value="last">Last</option>
										<option value="largestsize">Largest</option>
										<option value="smallestsize">Smallest</option>
										<option value="usesizecriteria">Use size criteria below</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="label">Number of BOLD reps <img src="images/help.gif" title="<b>Must be an integer or a criteria:</b><ul><li><i>N</i> (exactly N)<li>> <i>N</i> (greater than)<li>>= <i>N</i> (greater than or equal to)<li>< <i>N</i> (less than)<li><= <i>N</i> (less than or equal to)<li>~ <i>N</i> (not)</ul>"></td>
								<td><input type="text" name="dd_numboldreps[<?php 
echo $neworder;
?>
]"></td>
							</tr>
							<tr>
								<td class="label">Use series directories</td>
								<td title="<b>Tip:</b> If you plan to download multiple series with the same name, you will want to use series directories. This option will place each series into its own directory (data/task/1, data/task/2, etc)"><input class="small" type="checkbox" name="dd_useseriesdirs[<?php 
echo $neworder;
?>
]" value="1"></td>
							</tr>
							<tr>
								<td class="label">Preserve series numbers <img src="images/help.gif" title="If data is placed in a series directory, check this box to preserve the original series number. Otherwise the series number directories will be sequential starting at 1, regardless of the orignal series number"></td>
								<td><input class="small" type="checkbox" name="dd_preserveseries[<?php 
echo $neworder;
?>
]" value="1"></td>
							</tr>
							<tr>
								<td class="label">Behavioral data directory format</td>
								<td>
									<select class="small" name="dd_behformat[<?php 
echo $neworder;
?>
]">
										<option value="behnone" selected>Don't download behavioral data</option>
										<option value="behroot">Place in root (file.log)</option>
										<option value="behrootdir">Place in directory in root (beh/file.log)</option>
										<option value="behseries">Place in series (2/file.log)</option>
										<option value="behseriesdir">Place in directory in series (2/beh/file.log)</option>
									</select>
								</td>
							</tr>
							<tr>
								<td class="label">Behavioral data directory name</td>
								<td><input class="small" type="text" name="dd_behdir[<?php 
echo $neworder;
?>
]"></td>
							</tr>
						</table>
						<br>
					</details>
				</td>
			</tr>
			<? $neworder++; ?>
			<? } ?>
		</table>
		<?
		} /* end of the check to display the data specs */ ?>
		
		<br><br>
		<div style="text-align:left; font-size:12pt; font-weight: bold; color:#214282;">Script commands<br><span class="tiny" style="font-weight:normal">Ctrl+S to save</span></span>
		<br><br>
		
		<style type="text/css" media="screen">
			#commandlist { 
				position: relative;
				width: 1000px;
				height: 700px;
				top: 0;
				right: 0;
				bottom: 0;
				left: 0;
			}
		</style>
		</b>
		<table>
			<tr>
				<td valign="top">
		<textarea name="commandlist" style="font-weight:normal"><?
			$sqlstring = "select * from pipeline_steps where pipeline_id = $id and pipeline_version = $version order by ps_order + 0";
			$result = MySQLiQuery($sqlstring,__FILE__,__LINE__);
			while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
				$pipelinestep_id = $row['pipelinestep_id'];
				$ps_desc = $row['ps_description'];
				$ps_order = $row['ps_order'];
				$ps_command = $row['ps_command'];
				$ps_workingdir = $row['ps_workingdir'];
				$ps_enabled = $row['ps_enabled'];
				$ps_logged = $row['ps_logged'];
				if ($ps_enabled == 1) { $enabled = ""; } else { $enabled = "#"; }
				if ($ps_logged == 1) { $logged = ""; } else { $logged = "{NOLOG}"; }
echo "$enabled$ps_command     # $logged $ps_desc\n";
			}
		?></textarea>
		<div id="commandlist" style="border: 1px solid #666; font-weight: normal"></div>
		<script src="scripts/aceeditor/ace.js" type="text/javascript" charset="utf-8"></script>
		<!--<script src="http://d1n0x3qji82z53.cloudfront.net/src-min-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>-->
		<script>
			var editor = ace.edit("commandlist");
			var textarea = $('textarea[name="commandlist"]').hide();
			editor.setFontSize(12);
			editor.getSession().setMode("ace/mode/sh");
			editor.getSession().setUseWrapMode(false);
			editor.getSession().setValue(textarea.val());
			<?if ($readonly) { ?>
			editor.setReadOnly();
			<? } ?>
			editor.getSession().on('change', function(){
			  textarea.val(editor.getSession().getValue());
			});
			editor.setTheme("ace/theme/xcode");
			
			function insertText(text) {
				editor.insert(text);
			}
			function toggleWrap() {
				if (editor.getSession().getUseWrapMode()) {
					editor.getSession().setUseWrapMode(false);
				}
				else {
					editor.getSession().setUseWrapMode(true);
				}
			}
			$(window).bind('keydown', function(event) {
				if (event.ctrlKey || event.metaKey) {
					switch (String.fromCharCode(event.which).toLowerCase()) {
						case 's':
							event.preventDefault();
							//alert('ctrl-s');
							document.getElementById('stepsform').submit();
							break;
					}
				}
			});		
		</script>
				</td>
				<td valign="top" align="center">
				<b>Available pipeline variables</b><br>
				<span class="tiny">Click variable to insert at current editor location</span>
				<br><br>
				<table>
					<tr><td class="pipelinevariable" onclick="insertText('{analysisrootdir}');" title="Full path to the root directory of the analysis">{analysisrootdir}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{subjectuid}');" title="Example: S1234ABC">{subjectuid}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{studynum}');" title="Example: 1">{studynum}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{uidstudynum}');" title="Example: S1234ABC1">{uidstudynum}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{pipelinename}');" title="<?php 
echo $title;
?>
">{pipelinename}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{studydatetime}');" title="YYYYMMDDHHMMSS">{studydatetime}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{first_ext_file}');" title="Expands to first file found with extenstion. Replace ext with the extension">{first_ext_file}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{first_n_ext_files}');" title="Finds first file with extension">{first_n_ext_files}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{last_ext_file}');" title="Finds last file (alphabetically) with extension">{last_ext_file}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{all_ext_files}');" title="Finds all files matching the extension">{all_ext_files}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{command}');" title="Full command, excluding comment">{command}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{workingdir}');" title="Not dynamic, not changed at run-time">{workingdir}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{description}');" title="The description (comment)">{description}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{analysisid}');" title="Analysis ID">{analysisid}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{NOLOG}');" title="Insert in the comment and the line will not be logged. Useful if the command is using the > or >> operators to write to a file">{NOLOG}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{NOCHECKIN}');" title="Insert in the comment and the step will not be reported. Useful for command line for-loops">{NOCHECKIN}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{subjectuids}');" title="Space separated list of UIDs. For group analyses">{subjectuids}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{studydatetimes}');" title="Space separated list of datetimes, ordered by datetime. For group analyses">{studydatetimes}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{analysisgroupid}');" title="Group analysis ID">{analysisgroupid}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{uidstudynums}');" title="Space separated list of uidstudynums for all groups">{uidstudynums}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{numsubjects}');" title="Number of subjects from all groups">{numsubjects}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{groups}');" title="Space separated list of groups">{groups}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{numsubjects_groupname}');" title="Number of subjects (sessions) in the group specified">{numsubjects_groupname}</td></tr>
					<tr><td class="pipelinevariable" onclick="insertText('{uidstudynums_groupname}');" title="Space separated list of uidstudynums for the group specified">{uidstudynums_groupname}</td></tr>
				</table>
				<br><br>
				<span class="editoroptions" onClick="toggleWrap()">Toggle text wrap</span>
				</td>
			</tr>
		</table>
				<tr>
					<td colspan="6" align="center">
						<br><br>
						<input type="submit" <?php 
echo $disabled;
?>
 value="Update Pipeline Definition Only">
					</td>
				</tr>
				</form>
			</tbody>
		</table>
		</fieldset>
		
		<br><br>
		<br><br>
		
		<?
		}
	}
 private function getSummaryTimes($prof)
 {
     $diffValues = array_map(array($this, 'mapDiffTime'), array_filter($prof, array($this, 'filterEndMarker')));
     $times = array();
     $times['times'] = $this->runCount;
     $times['median'] = median($diffValues) * 1000;
     $times['average'] = average($diffValues) * 1000;
     $times['max'] = max($diffValues) * 1000;
     return $times;
 }
Example #14
0
function get_class_avg($gradebook_test_id)
{
    $sql = "SELECT * FROM %sgradebook_tests WHERE gradebook_test_id=%d";
    $row = queryDB($sql, array(TABLE_PREFIX, $gradebook_test_id), TRUE);
    if ($row["id"] != 0) {
        require_once AT_INCLUDE_PATH . '../mods/_standard/tests/lib/test_result_functions.inc.php';
        $sql_test = "SELECT * FROM %stests WHERE test_id=%d";
        $row_test = queryDB($sql_test, array(TABLE_PREFIX, $row["id"]), TRUE);
        if ($row_test['out_of'] == 0 || $row_test['result_release'] == AT_RELEASE_NEVER) {
            return _AT("na");
        }
        $sql_marks = "SELECT * FROM %stests_results WHERE test_id=%d AND status=1";
        $rows_marks = queryDB($sql_marks, array(TABLE_PREFIX, $row["id"]));
        $num_students = 0;
        $total_final_score = 0;
        $total_out_of = 0;
        foreach ($rows_marks as $row_marks) {
            if ($row_marks['final_score'] == '') {
                continue;
            }
            $num_students++;
            $total_final_score += $row_marks["final_score"];
            if ($row_test['random']) {
                $total_out_of += get_random_outof($row_marks['test_id'], $row_marks['result_id']);
            } else {
                $total_out_of += $row_test['out_of'];
            }
        }
        if ($num_students > 0) {
            $avg_final_score = round($total_final_score / $num_students);
            $avg_out_of = round($total_out_of / $num_students);
        }
        if ($avg_final_score != "") {
            $avg_grade = get_mark_by_grade($row["grade_scale_id"], $avg_final_score, $avg_out_of);
        } else {
            $avg_grade = "";
        }
    } else {
        $sql_grades = "SELECT * FROM %sgradebook_detail WHERE gradebook_test_id= %d ORDER BY grade";
        $rows_grades = queryDB($sql_grades, array(TABLE_PREFIX, $gradebook_test_id));
        $grade_array = array();
        foreach ($rows_grades as $row_grades) {
            $grade_array[] = $row_grades["grade"];
        }
        $avg_grade = median($grade_array);
    }
    if ($avg_grade == "") {
        return _AT("na");
    } else {
        return $avg_grade;
    }
}