Exemplo n.º 1
0
def test_replace():
    vec = robjects.vectors.IntVector(range(1, 6))
    i = array.array('i', [1, 3])
    vec.rx[rlc.TaggedList((i, ))] = 20
    assert vec[0] == 20
    assert vec[1] == 2
    assert vec[2] == 20
    assert vec[3] == 4

    vec = robjects.vectors.IntVector(range(1, 6))
    i = array.array('i', [1, 5])
    vec.rx[rlc.TaggedList((i, ))] = 50
    assert vec[0] == 50
    assert vec[1] == 2
    assert vec[2] == 3
    assert vec[3] == 4
    assert vec[4] == 50

    vec = robjects.vectors.IntVector(range(1, 6))
    vec.rx[1] = 70
    assert tuple(vec[0:5]) == (70, 2, 3, 4, 5)

    vec = robjects.vectors.IntVector(range(1, 6))
    vec.rx[robjects.vectors.IntVector((1, 3))] = 70
    assert tuple(vec[0:5]) == (70, 2, 70, 4, 5)

    m = robjects.r('matrix(1:10, ncol=2)')
    m.rx[1, 1] = 9
    assert m[0] == 9

    m = robjects.r('matrix(1:10, ncol=2)')
    m.rx[2, robjects.vectors.IntVector((1, 2))] = 9
    assert m[1] == 9
    assert m[6] == 9
Exemplo n.º 2
0
def main():
    #read the logs in
    readlogs(LOG_DIRECTORY)
    readlogs('wobLog/')
    node_frame = table_data.createNodesFrame()
    edge_frame = table_data.createLinksFrame()
    print(node_frame)
    print(edge_frame)

    visNetwork = importr('visNetwork')

    plotVisNetwork = ro.r['visNetwork']
    visGroups = ro.r['visGroups']
    visOptions = ro.r['visOptions']
    visSave = ro.r['visSave']
    visIgraphLayout = ro.r['visIgraphLayout']  

    graph = plotVisNetwork(node_frame, edge_frame)
    #graph = visGroups(graph)

    degree_option = rlc.TaggedList([100, 100], tags = ('from', 'to'))
    highlightNearest_option = rlc.TaggedList([True, degree_option, "hierarchical"], ('enabled', 'degree', 'algorithm'))

    graph = visOptions(graph, highlightNearest = highlightNearest_option)
    graph = visIgraphLayout(graph, layout = 'layout_with_sugiyama')
    visSave(graph, file = "network.html")
Exemplo n.º 3
0
def ExampleTable_to_DataFrame(examples):
    attrs = [ attr for attr in examples.domain.variables if attr.varType in \
             [orange.VarTypes.Continuous, orange.VarTypes.Discrete, orange.VarTypes.String]]
    def float_or_NA(value):
        if value.isSpecial():
            return NA_Real
        else:
            return float(value)
        
    def int_or_NA(value):
        if value.isSpecial():
            return NA_Integer
        else:
            return int(value)
    
    def str_or_NA(value):
        if value.isSpecial():
            return NA_Character
        else:
            return str(value)
        
    data = []
    for attr in attrs:
        if attr.varType == orange.VarTypes.Continuous:
            data.append((attr.name, robjects.FloatVector([float_or_NA(ex[attr]) for ex in examples])))
        elif attr.varType == orange.VarTypes.Discrete:
            intvec = robjects.IntVector([int_or_NA(ex[attr]) for ex in examples])
#            factor.levels = robjects.StrVector(list(attr.values))
            data.append((attr.name, intvec))
        elif attr.varType == orange.VarTypes.String:
            data.append((attr.name, robjects.StrVector([str_or_NA(ex[attr]) for ex in examples])))
        
    r_obj = DataFrame(rlc.TaggedList([v for _, v in data], [t for t,_ in data]))
    return r_obj
Exemplo n.º 4
0
    def testNewFromTaggedList(self):
        letters = robjects.r.letters
        numbers = robjects.r('1:26')
        df = robjects.DataFrame(
            rlc.TaggedList((letters, numbers), tags=('letters', 'numbers')))

        self.assertEqual("data.frame", df.rclass[0])
Exemplo n.º 5
0
def test_init_from_taggedlist():
    letters = robjects.r.letters
    numbers = robjects.r('1:26')
    df = robjects.DataFrame(
        rlc.TaggedList((letters, numbers), tags=('letters', 'numbers')))

    assert df.rclass[0] == 'data.frame'
Exemplo n.º 6
0
 def test_remove(self):
     tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
     assert len(tl) == 3
     tl.remove(2)
     assert len(tl) == 2
     assert tl.tags == ('a', 'c')
     assert tuple(tl) == (1, 3)
Exemplo n.º 7
0
 def test_append(self):
     tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
     assert len(tl) == 3
     tl.append(4, tag='a')
     assert len(tl) == 4
     assert tl[3] == 4
     assert tl.tags == ('a', 'b', 'c', 'a')
Exemplo n.º 8
0
 def testDim(self):
     letters = robjects.r.letters
     numbers = robjects.r('1:26')
     df = robjects.DataFrame(
         rlc.TaggedList((letters, numbers), tags=('letters', 'numbers')))
     self.assertEqual(26, df.nrow)
     self.assertEqual(2, df.ncol)
Exemplo n.º 9
0
    def testReplace(self):
        vec = robjects.r.seq(1, 10)
        i = array.array('i', [1, 3])
        vec.rx[rlc.TaggedList((i, ))] = 20
        self.assertEquals(20, vec[0])
        self.assertEquals(2, vec[1])
        self.assertEquals(20, vec[2])
        self.assertEquals(4, vec[3])

        i = array.array('i', [1, 5])
        vec.rx[rlc.TaggedList((i, ))] = 50
        self.assertEquals(50, vec[0])
        self.assertEquals(2, vec[1])
        self.assertEquals(20, vec[2])
        self.assertEquals(4, vec[3])
        self.assertEquals(50, vec[4])
Exemplo n.º 10
0
 def testremove(self):
     tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
     self.assertEqual(3, len(tl))
     tl.remove(2)
     self.assertEqual(2, len(tl))
     self.assertEqual(tl.tags, ('a', 'c'))
     self.assertEqual(tuple(tl), (1, 3))
Exemplo n.º 11
0
 def test__delitem__(self):
     tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
     self.assertEqual(3, len(tl))
     del tl[1]
     self.assertEqual(2, len(tl))
     self.assertEqual(tl.tags, ('a', 'c'))
     self.assertEqual(tuple(tl), (1, 3))
Exemplo n.º 12
0
def test_dim():
    letters = robjects.r.letters
    numbers = robjects.r('1:26')
    df = robjects.DataFrame(
        rlc.TaggedList((letters, numbers), tags=('letters', 'numbers')))
    assert df.nrow == 26
    assert df.ncol == 2
Exemplo n.º 13
0
 def testappend(self):
     tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
     self.assertEqual(3, len(tl))
     tl.append(4, tag='a')
     self.assertEqual(4, len(tl))
     self.assertEqual(4, tl[3])
     self.assertEqual(('a', 'b', 'c', 'a'), tl.tags)
Exemplo n.º 14
0
 def test__delitem__(self):
     tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
     assert len(tl) == 3
     del tl[1]
     assert len(tl) == 2
     assert tl.tags == ('a', 'c')
     assert tuple(tl) == (1, 3)
Exemplo n.º 15
0
 def test_reverse(self):
     tn = ['a', 'b', 'c']
     tv = [1, 2, 3]
     tl = rlc.TaggedList(tv, tags=tn)
     tl.reverse()
     assert len(tl) == 3
     assert tl.tags == ('c', 'b', 'a')
     assert tuple(tl) == (3, 2, 1)
Exemplo n.º 16
0
    def test_sort(self):
        tn = ['a', 'c', 'b']
        tv = [1, 3, 2]
        tl = rlc.TaggedList(tv, tags=tn)
        tl.sort()

        assert tl.tags == ('a', 'b', 'c')
        assert tuple(tl) == (1, 2, 3)
Exemplo n.º 17
0
    def testsort(self):
        tn = ['a', 'c', 'b']
        tv = [1, 3, 2]
        tl = rlc.TaggedList(tv, tags=tn)
        tl.sort()

        self.assertEqual(tl.tags, ('a', 'b', 'c'))
        self.assertEqual(tuple(tl), (1, 2, 3))
Exemplo n.º 18
0
 def testreverse(self):
     tn = ['a', 'b', 'c']
     tv = [1, 2, 3]
     tl = rlc.TaggedList(tv, tags=tn)
     tl.reverse()
     self.assertEqual(3, len(tl))
     self.assertEqual(tl.tags, ('c', 'b', 'a'))
     self.assertEqual(tuple(tl), (3, 2, 1))
Exemplo n.º 19
0
def make_data_frame(colnames, coltypes, rows=None, cols=None):
    """Make a data frame from a list of rows or columns and definitions
    (name and type) of the columns found in each row.

    See COLTYPE documentation for a description of accepted input types
    for each column type.

    Args:
      - rows (object[][]): Rows of data, each of the same length and types
      - cols (object[][]): Columns of data, each of the same length
      - colnames (str[]): Name of each column
      - column_type (COLTYPE[]): Type of each column. 

    Return:
      - robjects.DataFrame: Data frame

    Exceptions:
      - TypeError: Column value does not match stated type
    """
    # Check trivial cases.
    if (rows is not None and len(rows) == 0) or \
       (cols is not None and len(cols) == 0):
        return robjects.DataFrame({})
    # Transpose rows into appropriately typed columns.
    if rows is not None:
        columns = rlc.TaggedList([])
        for i in range(len(rows[0])):
            col = []
            for row in rows:
                col.append(row[i])
            # convert column to R type
            ct = coltypes[i]
            vec = make_rvector(col, ct)
            columns.append(vec, tag=colnames[i].encode())
    elif cols is not None:
        columns = rlc.TaggedList([])
        for (vec, ct, name) in zip(cols, coltypes, colnames):
            columns.append(make_rvector(vec, ct), tag=name.encode())
    else:
        raise ValueError("one of 'rows' or 'cols' must be given")
    # Create data frame from columns.
    df = robjects.DataFrame(columns)
    # Collect temporaries [perhaps]
    gc.collect()
    return(df)
Exemplo n.º 20
0
 def __getitem__(self, item):
     fun = self._extractfunction
     args = rlc.TaggedList(item)
     for i, (k, v) in enumerate(args.iteritems()):
         args[i] = conversion.py2ro(v)
     args.insert(0, self._parent)
     res = fun.rcall(args.items(), globalenv_ri)
     res = conversion.py2ro(res)
     return res
Exemplo n.º 21
0
    def testReplace(self):
        vec = robjects.IntVector(range(1, 6))
        i = array.array('i', [1, 3])
        vec.rx[rlc.TaggedList((i, ))] = 20
        self.assertEqual(20, vec[0])
        self.assertEqual(2, vec[1])
        self.assertEqual(20, vec[2])
        self.assertEqual(4, vec[3])

        vec = robjects.IntVector(range(1, 6))
        i = array.array('i', [1, 5])
        vec.rx[rlc.TaggedList((i, ))] = 50
        self.assertEqual(50, vec[0])
        self.assertEqual(2, vec[1])
        self.assertEqual(3, vec[2])
        self.assertEqual(4, vec[3])
        self.assertEqual(50, vec[4])

        vec = robjects.IntVector(range(1, 6))
        vec.rx[1] = 70
        self.assertEqual(70, vec[0])
        self.assertEqual(2, vec[1])
        self.assertEqual(3, vec[2])
        self.assertEqual(4, vec[3])
        self.assertEqual(5, vec[4])

        vec = robjects.IntVector(range(1, 6))
        vec.rx[robjects.IntVector((1, 3))] = 70
        self.assertEqual(70, vec[0])
        self.assertEqual(2, vec[1])
        self.assertEqual(70, vec[2])
        self.assertEqual(4, vec[3])
        self.assertEqual(5, vec[4])


        m = robjects.r('matrix(1:10, ncol=2)')
        m.rx[1, 1] = 9
        self.assertEqual(9, m[0])

        m = robjects.r('matrix(1:10, ncol=2)')
        m.rx[2, robjects.IntVector((1,2))] = 9
        self.assertEqual(9, m[1])
        self.assertEqual(9, m[6])
Exemplo n.º 22
0
def neuroCheck(maxtomin, delay, length, angle1, angle2):
    angles = angle1 / angle2
    ro.r('.libPaths("/home/pilat/R/x86_64-pc-linux-gnu-library/3.0/")')  #
    nnet = importr("nnet")
    ro.r.load(os.getcwd() + "/.RneuroModel8")
    tmpMatrix = ro.r['data.frame'](ro.DataFrame(
        container.TaggedList(
            [length, delay, maxtomin, angle1, angles],
            ['length', 'delay', 'maxtomin', 'angle1', 'angles'])))
    result = ro.r.predict(ro.r['neuroModel'], tmpMatrix)
    return array(result)[0][0]
Exemplo n.º 23
0
    def test_tags(self):
        tn = ['a', 'b', 'c']
        tv = [1, 2, 3]
        tl = rlc.TaggedList(tv, tags=tn)
        tags = tl.tags
        assert isinstance(tags, tuple) is True
        assert tags == ('a', 'b', 'c')

        tn = ['d', 'e', 'f']
        tl.tags = tn
        assert isinstance(tags, tuple) is True
        assert tl.tags == tuple(tn)
Exemplo n.º 24
0
    def testtags(self):
        tn = ['a', 'b', 'c']
        tv = [1, 2, 3]
        tl = rlc.TaggedList(tv, tags=tn)
        tags = tl.tags
        self.assertTrue(isinstance(tags, tuple))
        self.assertEqual(tags, ('a', 'b', 'c'))

        tn = ['d', 'e', 'f']
        tl.tags = tn
        self.assertTrue(isinstance(tags, tuple))
        self.assertEqual(tuple(tn), tl.tags)
Exemplo n.º 25
0
    def testpop(self):
        tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
        self.assertEqual(3, len(tl))
        elt = tl.pop()
        self.assertEqual(3, elt)
        self.assertEqual(2, len(tl))
        self.assertEqual(tl.tags, ('a', 'b'))
        self.assertEqual(tuple(tl), (1, 2))

        elt = tl.pop(0)
        self.assertEqual(1, elt)
        self.assertEqual(1, len(tl))
        self.assertEqual(tl.tags, ('b', ))
Exemplo n.º 26
0
    def test_pop(self):
        tl = rlc.TaggedList((1, 2, 3), tags=('a', 'b', 'c'))
        assert len(tl) == 3
        elt = tl.pop()
        assert elt == 3
        assert len(tl) == 2
        assert tl.tags == ('a', 'b')
        assert tuple(tl) == (1, 2)

        elt = tl.pop(0)
        assert elt == 1
        assert len(tl) == 1
        assert tl.tags == ('b', )
Exemplo n.º 27
0
 def fit(self, X):
     verbose = self.log_path is not None
     if verbose:
         ro.r.sink(self.log_path, type='output')
     if self.indep_test == 'gauss':
         indep_test = pcalg.gaussCItest
         corr = np.corrcoef(X.T)
         nr, nc = corr.shape
         corr = ro.r.matrix(corr, nrow=nr, ncol=nc)
         ro.r.assign("Corr", corr)
         indep_test_args = rlc.TaggedList([corr, len(X)], ['C', 'n'])
     else:
         indep_test = self.indep_test
         if self.indep_test_args is None:
             indep_test_args = ro.NULL
         else:
             indep_test_args = self.indep_test_args
     n_samples, self.n_nodes = X.shape
     if self.algorithm == 'fci':
         res = pcalg.fci(suffStat=indep_test_args,
                         indepTest=indep_test,
                         p=self.n_nodes,
                         alpha=self.p_value,
                         skel_method="stable.fast",
                         numCores=self.num_cores,
                         verbose=verbose)
         g = res.slots['amat']
         self.edges = self._from_array_to_edges(np.array(g, dtype=int))
     elif self.algorithm == 'fci+':
         res = pcalg.fciPlus(suffStat=indep_test_args,
                             indepTest=indep_test,
                             p=self.n_nodes,
                             alpha=self.p_value,
                             verbose=verbose)
         g = res.slots['amat']
         self.edges = self._from_array_to_edges(np.array(g, dtype=int))
     else:
         res = pcalg.pc(suffStat=indep_test_args,
                        indepTest=indep_test,
                        p=self.n_nodes,
                        alpha=self.p_value,
                        skel_method="stable.fast",
                        solve_confl=True,
                        u2pd='relaxed',
                        verbose=verbose,
                        numCores=self.num_cores)
         self.edges = self._from_r_graph_to_edges(res)
     try:
         self.sepset = self.extract_sepsets(res)
     except Exception:
         self.sepset = None
Exemplo n.º 28
0
def dataframe(data, variables=None):
    """
    Convert an Orange.data.Table to R's DataFrame.
    Converts only the input variables if given.
    """
    if not variables:
        variables = [ attr for attr in data.domain.variables if attr.var_type in \
                 [ Orange.feature.Descriptor.Continuous, 
                   Orange.feature.Descriptor.Discrete, 
                   Orange.feature.Descriptor.String ] ]
           
    odata = []
    for attr in variables:
        odata.append((attr.name, variable_to_vector(data, attr)))

    r_obj = DataFrame(rlc.TaggedList([v for _,v in odata], [t for t,_ in odata]))
    return r_obj
Exemplo n.º 29
0
def train(x_data, y_values, weights):
    x_float_vector = [ro.FloatVector(x) for x in np.array(x_data).transpose()]
    y_float_vector = ro.FloatVector(y_values)
    weights_float_vector = ro.FloatVector(weights)
    names = ['v' + str(i) for i in xrange(len(x_float_vector))]
    d = rlc.TaggedList(x_float_vector + [y_float_vector], names + ['y'])
    data = ro.DataFrame(d)
    formula = 'y ~ '
    for x in names:
        formula += x + '+'
    formula = formula[:-1]
    fit_res = ro.r.glm(formula=ro.r(formula),
                       data=data,
                       weights=weights_float_vector,
                       family=ro.r('binomial(link="logit")'))

    ## print fit_res
    print "formula:", formula
Exemplo n.º 30
0
def optimize_nb_R(y, x, weights):
    from rpy2 import robjects as ro
    import rpy2.rlike.container as rlc
    from rpy2.robjects.packages import importr
    ro.r['options'](warn=1)
    mass = importr("MASS")

    x_float_vector = [ro.FloatVector(xx) for xx in x]

    y_float_vector = ro.FloatVector(y)

    weights_float_vector = ro.FloatVector(weights)

    names = ['v' + str(i) for i in xrange(len(x_float_vector))]
    d = rlc.TaggedList(x_float_vector + [y_float_vector], names + ['y'])
    data = ro.DataFrame(d)
    formula = 'y ~ ' + '+ '.join(names) + ' - 1'

    try:
        fit_res = mass.glm_nb(formula=ro.r(formula), data=data, weights=weights_float_vector)
    except:
        return NegBinomialOptimizationFailure

    return fit_res.rx2('theta')[0], list(fit_res.rx2('coefficients'))